blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
02350014103279d5c3d072b18cae6a3e0798de75 | teddyk251/alx-higher_level_programming-1 | /0x07-python-test_driven_development/2-matrix_divided.py | 1,289 | 4.28125 | 4 | #!/usr/bin/python3
""" divides all elements of a matrix """
def matrix_divided(matrix, div):
"""
divides all elements of a matrix
Args:
matrix: matrix to be divided
div: number used to divide
Return:
matrix with divided elements
"""
if not all(isinstance(matrix, list)):
raise TypeError(
'matrix must be a matrix (list of lists)of integers/floats'
)
""" if all lists are of the same length """
it = iter(matrix)
length = len(next(it))
if not all(len(l) == length for l in it):
raise TypeError('Each row of the matrix must have the same size')
""" checking for list values """
for lst in matrix:
for num in lst:
if type(num) not in [int, float] or num is None:
raise TypeError(
'matrix must be a matrix (list of lists)'
' of integers/floats'
)
""" checking for div """
if type(div) not in [int, float] or div is None:
raise TypeError('div must be a number')
if div == 0:
raise ZeroDivisionError('division by zero')
""" else, divide the matrix """
return([list(map(lambda x: round(x / div, 2), num))for num in matrix])
| true |
a4b17d50fcc0e1c5ff7bc85f4315217397529ea9 | nakashi120/PythonLectureKame | /basic/dictionary_func.py | 535 | 4.1875 | 4 | fruits_colors = {'apple': 'red', 'lemon': 'yellow', 'grapes': 'purple'}
if 'peach' in fruits_colors:
print(fruits_colors['peach'])
else:
print('the key is not found')
# .get(): dictionaryから値を取得する→なくてもエラーにならない
# fruits_colors.get('peach', 'nothing')
fruit = input("フルーツの名前を指定してください:")
print(fruits_colors.get(fruit, 'Nothing'))
# .update()
fruits_colors2 = {'peach': 'pink', 'kiwi': 'green'}
fruits_colors.update(fruits_colors2)
print(fruits_colors) | false |
c50d56c52c0a4b7c106abf365dccf609029e4792 | nakashi120/PythonLectureKame | /basic/if_non.py | 216 | 4.125 | 4 | # if文でのNoneの取り扱い
a = None # 「なにも値が入っていない」が入っている
# if a is None:
# print("a is None!")
# else:
# print("a has value!")
if not a:
print("a is None")
| false |
758b8709a3d0133fa00beb506b662cb00bd51129 | rkgitvinay/python-basic-tutorials | /3-control_flow.py | 714 | 4.21875 | 4 | """ Control Flow Statements """
"""
uses an expression to evaluate whether a statement is True or False.
If it is True, it executes what is inside the “if” statement.
"""
""" If Statement """
if True:
print("Hello This is if statement!")
""" Output: Hello This is if statement! """
if 5 > 2:
print("5 is greater than 2.")
""" Output: 5 is greater than 2. """
""" If Else Statement """
if 5 < 2:
print("5 is lss than 2.")
else:
print("5 is greater than 2.")
""" Outpur: 5 is greater than 2."""
""" If Else If Statement """
if 1 > 2:
print("1 is greater than 2")
elif 2 > 1:
print("1 is not greater than 2")
else:
print("1 is equal to 2")
""" Output: 1 is not greater than 2 """
| true |
06e0b06b985e0ac48cfe3ecd6c1ca1de69334424 | ybettan/ElectricalLabs | /electrical_lab_3/aws_experiment/part2/preliminary/q4.py | 279 | 4.3125 | 4 |
grades = {"python": 99, "java": 90, "c": 90}
grades_list = [x for _, x in grades.items()]
max_grade = max(grades_list)
min_grade = min(grades_list)
print "My lowest grade this semester was {}".format(min_grade)
print "My highest grade this semester was {}".format(max_grade)
| true |
2d11b7b1d939f6be364dc2394728fe2a21b99e95 | Nduwal3/python-Basics | /function-Assignments/soln16.py | 377 | 4.125 | 4 | """
Write a Python program to square and cube every number in a given list of
integers using Lambda.
"""
def calc_square_and_cube(input_list):
square_list = map(lambda num: num * num, input_list)
cube_list = map(lambda num: num ** 3, input_list)
print(list(square_list))
print(list(cube_list))
sample_list = [1, 3, 5, 7, 9]
calc_square_and_cube(sample_list) | true |
f4fd513b8f8706e0339d7da3284b5f22364b5d04 | Nduwal3/python-Basics | /soln43.py | 374 | 4.25 | 4 | """
Write a Python program to remove an item from a tuple.
"""
# since python tuples are immutable we cannot append or remove item from a tuple.
# but we can achive it by converting the tuple into a list and again converting the list back to a tuple
my_tuple = ('ram', 37, "ram@r.com")
my_list = list(my_tuple)
my_list.remove(37)
my_tuple = tuple(my_list)
print(my_tuple) | true |
10047fa0561ecf373381ce8abed48587402952b3 | Nduwal3/python-Basics | /function-Assignments/soln7.py | 825 | 4.21875 | 4 | """
Write a Python function that accepts a string and calculate the number of
upper case letters and lower case letters.
Sample String : 'The quick Brow Fox'
Expected Output :
No. of Upper case characters : 3
No. of Lower case Characters : 12
"""
def count_string_lower_and_upper_case(input_string):
count_upper_case = 0
count_lower_case = 0
for char in input_string:
if char.isupper():
count_upper_case += 1
elif char.islower():
count_lower_case += 1
else:
continue
return count_upper_case , count_lower_case
upper_case_count, lower_case_count = count_string_lower_and_upper_case('The quick Brow Fox')
print("No. of Upper case characters : {}".format(upper_case_count))
print("No. of Lower case characters : {}".format(lower_case_count))
| true |
4af30bc0c5fa913415ad507c23232f86a20fad8a | Nduwal3/python-Basics | /function-Assignments/soln9.py | 591 | 4.15625 | 4 | """
Write a Python function that takes a number as a parameter and check the
number is prime or not.
Note : A prime number (or a prime) is a natural number greater than 1 and that
has no positive divisors other than 1 and itself.
"""
def check_prime(num):
is_prime = False
if num > 1:
for i in range(2, num):
if num % i == 0:
is_prime = False
break
else:
is_prime = True
return is_prime
num = 16
if(check_prime(num)):
print("the number is prime")
else:
print("the number is not prime") | true |
515a4847f1592a5d8329f075cf40506c63350f82 | Nduwal3/python-Basics | /soln25.py | 548 | 4.1875 | 4 | """
Write a Python program to check whether all dictionaries in a list are empty or
not.
Sample list : [{},{},{}]
Return value : True
Sample list : [{1,2},{},{}]
Return value : False
"""
def check_empty_dictionaries(sample_list):
is_empty = False
for item in sample_list:
if item:
is_empty = False
break
else:
is_empty = True
print(is_empty)
sample_list1 = [{},{},{}]
sample_list2 = [{},{1,2},{}]
check_empty_dictionaries(sample_list1)
check_empty_dictionaries(sample_list2)
| true |
b15c7f66e5d574148dc9ac92344d92440ec0744f | arossouw/study | /python/math/factorial.py | 204 | 4.28125 | 4 | #!/usr/bin/python
# recursive function for factorial
# factorial example: 4! = 4 * 3 * 2 * 1 = 24
def factorial(n):
if n == 0:
return 1
return n * factorial(n-1)
print factorial(4)
| false |
fc5d4c5006f3c9217d58848447a4fd76382a4a72 | GravityJack/keyed-merge | /keyed_merge/merge.py | 880 | 4.1875 | 4 | import functools
import heapq
def merge(*iterables, key=None):
"""
Merge multiple sorted iterables into a single sorted iterable.
Requires each sequence in iterables be already sorted with key, or by value if key not present.
:param iterables: Iterable objects to merge
:param key: optional, callable
Key function, identical to that used by builtin sorted().
If not present, items will be compared by value.
:return: iterator to the sorted sequence
"""
if key is None:
for x in heapq.merge(*iterables):
yield x
else:
bound_key = functools.partial(_add_key, key)
with_key = map(bound_key, iterables)
merged = heapq.merge(*with_key)
for key, value in merged:
yield value
def _add_key(key, iterable):
for x in iterable:
yield key(x), x | true |
270e8bd8f98d915bb4c3eab7214254d168e6c5af | MarcosMaciel-MMRS/Desenvolvimento-python | /Python-desenvolvimento/ex100.py | 730 | 4.1875 | 4 | #Faça um programa que tenha uma lista chamada números e duas funções chamadas sorteia() e somaPar().
#A primeira função vai sortear 5 números e vai colocá-los dentro da lista e a segunda função vai mostrar
#a soma entre todos os valores pares sorteados pela função anterior.
from random import randint
numeros = list()
def sorteia(numeros):
for n in range(0,5):
n = randint(0,9)
numeros.append(n)
print(f'Os Números sorteados: {numeros}')
def somapar(numeros):
soma = 0
for valor in numeros:
if valor % 2 == 0:
soma += valor
print(f'A some dos números pares: {soma}')
print('FIM!')
#programa
sorteia(numeros)
somapar(numeros)
| false |
f1a8f4d31bebc4ac16a5398074c3b239b157b57f | MarcosMaciel-MMRS/Desenvolvimento-python | /Python-desenvolvimento/ex043.py | 988 | 4.15625 | 4 | #ler a altura e o peso, e diga o IMC da pessoa
print('-=-'*15)
print(' Tabela IMC')
print('-=-'*15)
print('''Classifição de IMC:
-Abaixo de 18.5: Abaixo do Peso
-Entre 18.5 e 25: Peso ideal
-25 até 30: Sobrepeso
-30 até 40: Obsesidade
-Acima de 40: Obesidade Mórbida''')
altura = float(input('Informe sua Altura: '))
peso = float(input('Informe seu peso: '))
imc = peso/ (altura**2)
if imc < 18.5:
print('Seu peso está abixo do ideal, seu IMC é de {:.2f}'.format(imc))
elif imc >=18.5 and imc< 25:
print('seu IMC é de {:.2f}, e você esta no peso ideal'.format(imc).capitalize())#so para nao esquecer o capitalize
elif imc >=25 and imc< 30:
print('Seu IMC é de {:.2f}, e você está acima do peso ideal.'.format(imc))
elif imc >=30 and imc <40:
print('O seu IMC é de {:.2f}, e vc esta em Obsidade.'.format(imc))
else:
print('Eita porra, eita porra, eita porra, GORDO PRA CARALHO, quer infartar?! Vou nem falar o IMC ')
| false |
79bbbe4ccc0ed72472e0afb9ee68195e2987b4a7 | MarcosMaciel-MMRS/Desenvolvimento-python | /Python-desenvolvimento/ex072.py | 767 | 4.3125 | 4 | #ler um némero entre 0-20 e mostrar ele por extenso ex: 1 - um
tupla = ('Zero','um','dois','tres', 'quatro', 'cinco', 'seis', 'sete', 'oito','nove','dez',
'onze','dose','treze','quatorze','quinze','dezesseis', 'dezessete','dezoioto','dezenove','vinte')
from time import sleep
while True:
numero = ' '
while numero not in range(0,21):# Assim, o meu programa so vai aceitar números entre 0-20.
numero = int(input('Digite um número entre 0-20: '))
print(f'Você digitou o número {tupla[numero]}')
resp = ' '
while resp not in 'SN':
resp = str(input('Outro número: [S/N]')).strip().upper()[0]# armazena a opção s/n
if resp == 'N':
break
print('Finalizando...')
sleep(2)
print('Volte sempre!')
| false |
4215f51f733aee82705cb8c4eef62d371153ab4a | MarcosMaciel-MMRS/Desenvolvimento-python | /Python-desenvolvimento/ex016.py | 521 | 4.15625 | 4 | #receber um numero real e converter em inteiro
#from math import trunc
import math
n = float(input('Informe um Número Real: '))
#assim é sem importar nenhuma biblioteca
print('O número {} tem a aparte inteira {}.'.format(n, int(n)))
#print('O número {} tem a aparte inteira {}.'.format(n, math.tunc(n)))-- usando o import math(que possibilita todas as funçoes matematicas)
#print('O número {} tem a aparte inteira {}.'.format(n, trunc(n)))-- usando o from math import trunc(limitei o importe paara o trunc)
| false |
0ae9854fa9f101ff2544726d2b4a26b7798dfd2e | MarcosMaciel-MMRS/Desenvolvimento-python | /Python-desenvolvimento/ex103.py | 668 | 4.15625 | 4 | #Faça um programa que tenha uma função chamada ficha(), que receba dois parâmetros opcionais:
#o nome de um jogador e quantos gols ele marcou. O programa deverá ser capaz de mostrar a ficha do jogador,
#mesmo que algum dado não tenha sido informado corretamente.
#função
def ficha(nome = 'Desconhecido', gols = 0):
print('Ficha:')
print(f'O jogador {nome}, fez {gols} no campionato')
#programa
nome = str(input('Nome do jogador: ')).capitalize().strip()
gols = str(input('Número de gols: '))
if gols.isnumeric():
gols = int(gols)
else:
g = 0
if nome.strip() == '':
ficha(gols=gols)
else:
ficha(nome, gols)
| false |
670e0cdf838b9b91613d24164ac5ec9882e3d96f | MarcosMaciel-MMRS/Desenvolvimento-python | /Python-desenvolvimento/ex075.py | 540 | 4.1875 | 4 | #gerar uma tupla aleatoria com 5 números.
#mostrar quem é o maior, e quem é o menor.
from random import randint
numeros = (randint(1,10), randint(1,10), randint(1,10),
randint(1,10), randint(1,10))
print('Os números Sorteados foram: ', end = ' ')
for n in numeros:
print(f'{n}', end = ' ')
print('\nO maior valor foi : {}'.format(max(numeros)))#metodo próprio do python que fala o maior valor de uma tupla
print('O menor valor foi: {}'.format(min(numeros)))#metodo próprio do python q mostra o menor valor
| false |
ce66653d7fff7ecf1b4546c0b1e1bcefe823c01c | MarcosMaciel-MMRS/Desenvolvimento-python | /Python-desenvolvimento/ex086.py | 624 | 4.28125 | 4 | #Crie um programa que declare uma matriz de dimensão 3x3 e preencha com valores lidos pelo teclado.
#No final, mostre a matriz na tela, com a formatação correta.
from random import randint
aleatorio = randint(0,10)
matriz = [[0,0,0], [0,0,0], [0,0,0]]
for l in range(0,3):#para ler o camando na linha
for c in range(0,3):# aqui direciona para a coluna
#matriz[l][c] = int(input(f'Digite um valor: ')) se eu quiser digitar valores
matriz[l][c] = aleatorio# para test
print('-='*30)
for l in range(0,3):
for c in range(0,3):
print(f'{matriz[l][c]:^6}', end = '')
print()
| false |
c42d98a322b0062c2c2e66fc1f00645174de5d88 | igoradriano/curso_python_bemol | /Aula_22/aula_22-funcao-lambda.py | 742 | 4.25 | 4 | # Funcoes anonimas
soma = lambda a,b : a + b
mult = lambda a,b,c : (a+b)*c
print((lambda a,b: a - b)(3,44)) # Neste caso nem preciso declar nome, nem chamá-la, ele ja executa
# Usando a funcao criada
c = soma(1,2)
print(c)
print(soma(1,2))
print(mult(1,2,3))
# Usando funcoes como parâmetro da funcao lambda
r = lambda x,func: x + func(x) # r assume uma lambda que recebe um numero e uma funcao, onde essa funcao recebe x como argumento e soma-se ao valor do proprio x ou seja: x + f(x)
res =r(22,lambda x:x*x) # agora passo o valor de x e uma nova funcao lambda que recebe x e multiplica por x
print("res: ",res) # printamos res
# Ex2:
a = lambda x,y,func:x + func(x,y)
result = a(22,10,lambda x,y:x*y*2)
print('Res:', result) | false |
7c918ccd80ec7fd3c45d8233a12a62bd423c7937 | msflyee/Learn_python | /code/Chapter4_operations on a list.py | 1,062 | 4.28125 | 4 | # Chapter4-operations on a list
magicians = ['Alice','David','Liuqian'];
for magician in magicians: #define 'magician'
print(magician + '\t');
for value in range(1,5): #define value
print(value);
numbers = list(range(1,6));
print(numbers);
even_numbers = list(range(2,11,2)); #打印偶数,函数range()的第三个参数为 步数
print(even_numbers);
squares = [];
for value in range(1,6):
squares.append(value ** 2);
print(squares);
list = [4,3,2,1];
for value in list:
squares.pop(value);
print(squares);
squares = [value ** 2 for value in range(1,11)];
print(squares);
list = [];
for value in range(1,1000001):
list.append(value);
print(min(list));
print(max(list));
print(sum(list));
players = ['Charles','Martina','Florence','Eli'];
print(players[0:3]);
print(players[:3]);
print(players[2:]);
print(players[-3:]);
for player in players[-3:]:
print(player);
_players = players[:];
print(_players);
print(players);
players.append('Karry');
print(_players);
print(players);
#copyright by Karry Yee in WuHan,China.
| true |
733f3343ec96f97ef4af38c87accc5cda0324999 | AndrewNik/python_course | /less7/task2.py | 936 | 4.1875 | 4 | # 2. Отсортируйте по возрастанию методом слияния одномерный вещественный массив, заданный случайными числами на
# промежутке [0; 50). Выведите на экран исходный и отсортированный массивы.
import random
def merge_sort(arr):
def merge(left, right):
result = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result += left[i:] + right[j:]
return result
if len(arr) < 2:
return arr
else:
l_side = arr[:len(arr) // 2]
r_side = arr[len(arr) // 2:]
return merge(merge_sort(l_side), merge_sort(r_side))
array = [i for i in range(0, 50)]
random.shuffle(array)
print(f'Исх. массив: {array}\nОтсортированный: {merge_sort(array)}')
| false |
30808f5fb665d31421e878ace60502afebf33836 | ShaneRandell/Midterm_001 | /midterm Part 4.py | 867 | 4.1875 | 4 | ## Midterm Exam Part 4
import csv # imports the csv library
file = open("book.csv", "a") # Opening a file called book.csv for appending
title = input("enter a title: ") # asking the user to enter a title
author = input("Enter author: ") # asking the user to enter a author
year = input("Enter the year it was released: ") # askign the user to enter year book was published
newrecord = title + "," + author + "," + year + "\n" # creating a string to combine all the entered information
file.write(str(newrecord)) # writing to the file all the information the user inputted
file.close() # closing the file
file = open("Book.csv", "r") # opening the file for reading
for row in file: # for loop with the condition to print all the rows in the file
print(row) # printing the contents of rows in the file
file.close() # closing the file
| true |
065aff05e0876ed0cedeea555109f6147a9d3219 | Venkatesh147/60-Python-projects | /60 Python projects/BMI Calculator.py | 572 | 4.28125 | 4 | Height=float(input("Enter your height in centimeters: "))
Weight=float(input("Enter your weight in kg: "))
Height=Height/100
BMI=Weight/(Height*Height)
print("your Body Mass Index is: ", BMI)
if(BMI>0):
if (BMI<=16):
print("you are severly underweight")
elif (BMI<=18.5):
print("you are underweight")
elif (BMI<=25):
print("you are healthy")
elif (BMI<=30):
print("you are overweight")
else: print("you are severely overweight")
else:("enter valid detalis")
| true |
2b654bfaf67cefdbdff9a1b4b61d4d80af3da5ff | CodecoolBP20172/pbwp-3rd-si-code-comprehension-frnczdvd | /comprehension.py | 1,948 | 4.34375 | 4 | # This program picks a random number between 1-20 and the user has to guess it under 6 times
import random # Import Python's built-in random function
guessesTaken = 0 # Assign a variable to 0
print('Hello! What is your name?') # Display a given output message
myName = input() # Ask for user input
number = random.randint(1, 20) # Assign a variable to a random number between 1 and 20
print('Well, ' + myName + ', I am thinking of a number between 1 and 20.') # Display a given output message, including a variable that contains the user's name
while guessesTaken < 6: # A loop that runs until user has given input 6 times or less
print('Take a guess.') # Display a given output message
guess = input() # Ask for user input
guess = int(guess) # Convert user input to integer
guessesTaken += 1 # A variable that count user inputs
if guess < number: # If users input is lower than the variable number
print('Your guess is too low.') # Display a given output message
if guess > number: # If users input is higher than the variable number
print('Your guess is too high.') # Display a given output message
if guess == number: # If users input equals the variable number
break # Stop the loop
if guess == number: # If users input equals the variable number
guessesTaken = str(guessesTaken) # Convert the variable that counts the number of user inputs from integer to string
print('Good job, ' + myName + '! You guessed my number in ' + guessesTaken + ' guesses!') # Display a given output message, including a variable that contains the user's name and the number of guesses.
if guess != number: # If user's input doesn't equals the variable number
number = str(number) # Convert the variable that had to be guessed from integer to string
print('Nope. The number I was thinking of was ' + number) # Display a given output message containing the number that had to be guessed
| true |
f97c7326e6be4786e1fda3a5c4a55c61aa6c6f3c | KLKln/Module11 | /employee1.py | 2,382 | 4.53125 | 5 | """
Program: employee.py
Author: Kelly Klein
Last date modified: 7/4/2020
This program will create a class called employee allowing the user to
access information about an employee
"""
import datetime
class Employee:
def __init__(self, lname, fname, address, phone, start_date, salary):
"""
use reST style.
:param last_name: employee's last name
:param first_name: employee's first name
:param address: employees address
:param phone_number: employee's phone number
:param start_date: date employee started
:param salary: double to indicate salary
:return:
"""
self.last_name = lname
#last_name: string
self.first_name = fname
#first_name: string
self.address = address
#address: string
self.phone = phone
#phone_number: string
self.start_date = start_date
#start_date: datetime
self.salary = salary
#salary: double
def display(self):
"""
use reST style.
:param last_name: employee's last name
:param first_name: employee's first name
:param address: employees address
:param phone_number: employee's phone number
:param start_date: date employee started working
:param salary: employee's yearly salary or hourly wage
:return:
"""
print(self.first_name + ' ' + self.last_name)
print(self.address)
print(self.phone)
if self.salaried is False:
print('Hourly Employee:', self.salary)
else:
print('Salaried Employee:', self.salary)
def __str__(self):
str(self.first_name + self.last_name + self.address + self.phone + self.start_date, self.salary)
def __repr__(self):
repr(self.first_name + self.last_name + self.address + self.phone + self.start_date + self.salary)
if __name__ == '__main__':
s_date = datetime.datetime(2019, 5, 17)
employee1 = Employee('Klein', 'Kelly', '42 Fake st\nCoralville, IA',
'319-377-2760', True, s_date, '$65000.00')
print(employee1.display())
s_date = datetime.datetime(2020, 1, 20)
employee2 = Employee('Lauper', 'Cyndi', '45 Elm St\nIowa City, IA',
'319-345-8998', False, s_date,'$35.00 an hour')
print(employee2.display())
| true |
6ba6176c13121443a781646914751b1430766e51 | RaHuL342319/Integration-of-sqlite-with-python3 | /query.py | 813 | 4.375 | 4 | import sqlite3
# to connect to an existing database.
# If the database does not exist,
# then it will be created and finally a database object will be returned.
conn = sqlite3.connect('test.db')
print("Opened database successfully")
# SELECTING WHOLE TABLE
cursor = conn.execute(
"SELECT * from Movies")
for row in cursor:
print("Name:", row[0])
print("Actor:", row[1])
print("Actress:", row[2])
print("Director:", row[3])
print("Year_Of_Release:", row[4])
print()
# querying based on actor name
cursor = conn.execute(
"SELECT * FROM Movies WHERE Actor='Shiddarth Malhotra'")
for row in cursor:
print("Name:", row[0])
print("Actor:", row[1])
print("Actress:", row[2])
print("Director:", row[3])
print("Year_Of_Release:", row[4])
print()
| true |
ae3dfe81639e3c295061a8b173dde8303632fd41 | holbertra/Python-fundamentals | /dictionary.py | 1,201 | 4.3125 | 4 | # Dictionaries
# dict
my_dictionary = {
"key" : "value",
"key2" : 78
}
product = {
"id" : 2345872425,
"description": "A yellow submarone",
"price" : 9.99,
"weight" : 9001,
"depart" : "grocery",
"aisle" : 3,
"shelf" : "B"
}
#print(product["price"])
location = (product["aisle"], product["shelf"])
#print(location)
#print(product.get("quanity")) # use .get when unknown or unsure it exists
product["aisle"] = 4
product["department"] = "guy's grocery games"
# for key in product:
# print(product[key])
# A list of the values
# print(product.values())
# print(product.keys())
# product["whatever"] = "the value"
product.update({"whatever": "the value"})
# Challenge
you = {}
data = [ ("name", "Rich") , ("age", 55), ("class", "Python") ]
for x in data:
you.update({ x[0]: x[1] }) # .update() to add to dictionary, note the syntax
print(you)
# Question: Does update.insert() also work? Probably not a dict is UNORDERED
# Question: How do you retrieve some value given a key?
for k, v, in data:
you[k] = v
you.update(data) # 1 line solution
print(you)
print(f'Your age is { you["age"]}')
| true |
27c43829d72a2e43b5ca4f1d6d54031bfdd10138 | axayjha/algorithms | /diagonal_traverse.py | 886 | 4.21875 | 4 | """
https://leetcode.com/problems/diagonal-traverse/
Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal
order as shown in the below image.
Example:
Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,4,7,5,3,6,8,9]
Explanation:
Note:
The total number of elements of the given matrix will not exceed 10,000.
"""
class Solution:
def findDiagonalOrder(self, matrix: List[List[int]]) -> List[int]:
from collections import defaultdict
ans = []
d = defaultdict(list)
for i in range(len(matrix)):
for j in range(len(matrix[0])):
d[i+j].append((i, j, matrix[i][j]))
flip = True
for i in sorted(d.keys()):
for j in sorted(d[i], reverse=flip):
ans.append(j[2])
flip = not flip
return ans
| true |
edff4979701065d3a63aa5b1c7312a8389989d0b | shaduk/MOOCs | /UdacityCS101/app/days.py | 1,144 | 4.34375 | 4 | def nextDay(year, month, day):
"""Simple version: assume every month has 30 days"""
if day < 30:
return year, month, day + 1
else:
if month == 12:
return year + 1, 1, 1
else:
return year, month + 1, 1
def daysBetweenDates(year1, month1, day1, year2, month2, day2):
"""Returns the number of days between year1/month1/day1
and year2/month2/day2. Assumes inputs are valid dates
in Gregorian calendar, and the first date is not after
the second."""
c=0
while(year1,month1,day1 != year2,month2,day2):
print year1,month1,day1
year1,month1,day1=nextDay(year1,month1,day1)
c = c+1
# YOUR CODE HERE!
return c
def test():
test_cases = [((2012,9,30,2012,10,30),30),
((2012,1,1,2013,1,1),360),
((2012,9,1,2012,9,4),3)]
for (args, answer) in test_cases:
result = daysBetweenDates(*args)
if result != answer:
print "Test with data:", args, "failed"
else:
print "Test case passed!"
test()
| true |
2aa27e73539e9ef7766fcf5ee480679d7b4fe2e2 | shaduk/MOOCs | /edx-CS101/myLog.py | 1,063 | 4.375 | 4 | '''Write a simple procedure, myLog(x, b), that computes the logarithm of a number x relative to a base b. For example, if x = 16 and b = 2, then the result is 4 - because 24=16. If x = 15 and b = 3, then the result is 2 - because 32 is the largest power of 3 less than 15.
In other words, myLog should return the largest power of b such that b to that power is still less than or equal to x.
x and b are both positive integers; b is an integer greater than or equal to 2. Your function should return an integer answer.
Do not use Python's log functions; instead, please use an iterative or recursive solution to this problem that uses simple arithmatic operators and conditional testing.
Note: You will only get ten checks. Use these judiciously.
'''
def myLog(x, b):
'''
x: a positive integer
b: a positive integer; b >= 2
returns: log_b(x), or, the logarithm of x relative to a base b.
'''
# Your Code Here
ans = 0
while(ans<x):
if b**(ans+1)>x and b**(ans)<=x:
return ans
ans = ans + 1 | true |
e1b9ba8875c43b15ba0e68c7f9e1d4842af94de8 | sashokbg/python-exercises | /fibonacci/fibonacci.py | 516 | 4.125 | 4 | import argparse
def main():
args, number = parseArgs()
fibonacci(number)
def parseArgs():
parser = argparse.ArgumentParser()
parser.add_argument('number', help='Calculate the fibonacci sequence to the n-th element', type = int)
args = parser.parse_args()
return args, args.number
def fibonacci(element):
el1 = 1
el2 = 1
tmp = 0
for i in range(element):
print(el1)
tmp = el1 + el2
el1 = el2
el2 = tmp
if __name__ == '__main__':
main();
| false |
69e0dd90a8cb90dab50b81eb9949364244187e45 | Luncode/Python-Learn | /dict.py | 489 | 4.40625 | 4 | print('学习:Python-dict')
#定义字典列表
d = {'Bob':95,'Lisa':96,'Luncode':100}
#修改key的值
d['Bob'] = 99
#检查key是否在列表中
print('Lisa' in d)
#输出对应key的value
print(d['Bob'])
#删除列表中的key和value
d.pop('Lisa')
#输出列表
print(d)
#小结
d = {'Michael': 95,'Bob': 75,'Tracy': 85}
print('d[\'Michael\'] =', d['Michael'])
print('d[\'Bob\'] =', d['Bob'])
print('d[\'Tracy\'] =', d['Tracy'])
print('d.get(\'Thomas\', -1) =', d.get('Thomas', -1))
| false |
41411ad71ab27f75e0771dbadac75de58b9bb3dc | sol83/python-simple_programs_7 | /Lists/get_first.py | 467 | 4.34375 | 4 | """
Get first element
Fill out the function get_first_element(lst) which takes in a list lst as a parameter and prints the first element in the list. The list is guaranteed to be non-empty.
You can change the items in the SAMPLE_LIST list to test your code!
"""
SAMPLE_LIST = [1, 2, 3, 'a', 'b', 'c']
def get_first_element(lst):
# write your code below!
print(lst[0])
def main():
get_first_element(SAMPLE_LIST)
if __name__ == "__main__":
main()
| true |
0bed91b6da6b75ca360119fe10bd8c6507c16080 | patricia-faustino/AprofundandoEmPython | /manipulandoStrings02.py | 676 | 4.125 | 4 | #TUDO EM MAIÚSCULO
print("acarajé com camarão".upper())
#tudo em minúsculo
print("acarajé com camarão".lower())
#Inicial maiúscula
print("acarajé com camarão".capitalize())
#Quantas vezes o parametro aparece, count(parametro)
print("acarajé com camarão".count("é"))
#Troca um item por outro, replace(old, new)
print("acarajé com camarão".replace("com","sem"))
#Informa qual posição o parametro se encontra, caso não encontre o parametro,
# retorna -1
print("acarajé com camarão".find("é"))
print("acarajé com camarão".find("z"))
## Retorna o numero de items em um objetos
melhorAperitivo = "acarajé com camarão"
print(len(melhorAperitivo)) | false |
5298e43d2497174ebf8477e9adede2f9c008fc67 | TSG405/SOLO_LEARN | /PYTHON-3 (CORE)/Fibonacci.py | 659 | 4.21875 | 4 | '''
@Coded by TSG, 2021
Problem:
The Fibonacci sequence is one of the most famous formulas in mathematics.
Each number in the sequence is the sum of the two numbers that precede it.
For example, here is the Fibonacci sequence for 10 numbers, starting from 0: 0,1,1,2,3,5,8,13,21,34.
Write a program to take N (variable num in code template) positive numbers as input, and recursively calculate and output the first N numbers of the Fibonacci sequence (starting from 0).
Sample Input
6
Sample Output
0
1
1
2
3
5
'''
#your code goes here
def fibonacci(n):
a,b=0,1
for i in range(n):
print(a)
a,b=b,(a+b)
fibonacci(int(input()))
| true |
6dd541d14a70d5d0654da10db9074c0999507725 | kumarritik87/Python-Codes | /factorial.py | 217 | 4.21875 | 4 | #program to find factorial of given number using while loop:-
n = int(input("Enter the no to find factorial\n"))
temp = n
f = 1
while(temp>0):
f = f*temp
temp = temp-1
print('factorial of ',n,'is', f)
| true |
de6c458f37b0512d53d4f87baa84115af4cc235c | infinitumodu/CPU-temps | /tableMaker.py | 1,787 | 4.21875 | 4 | #! /usr/bin/env python3
def makeXtable(data):
"""
Notes:
This function takes the data set and returns a list of times
Args:
data: a list with each element containing a time and a list of the core tempatures at that time
Yields:
a list of times
"""
xTable = []
for temp in data:
xTable.append(temp[0])
return xTable
def makeYtable(data, core):
"""
Notes:
This function takes the data set and a core number and returns a list of tempetures for the given core
Args:
data: a list with each element containing a time and a list of the core tempatures at that time
core: 0-indexed core number
Yields:
a list of tempetures
"""
y = []
for temp in data:
y.append(temp[1][core])
return y
def makeXmatrix(data):
"""
Notes:
This functions takes the data set and returns a list in which
each element contains a list [1, temp].
Args:
data: a list with each element containing a time and a list of the core tempatures at that time
Yields:
a matrix in nested list form
"""
xMatrix = []
for temp in data:
xMatrix.append([1, temp[0]])
return xMatrix
def makeYmatrix(data, core):
"""
Notes:
Nearly identical to the makeYtable function but returns a list or lists
to allow for use in matrix maniplations
Args:
data: a list with each element containing a time and a list of the core tempatures at that time
core: 0-indexed core number
Yields:
a list of tempetures, where each element is a list
"""
y = []
for temp in data:
y.append([temp[1][core]])
return y
| true |
f9e7b9f34a6456884c149fca05ae63188b08ac7e | EliseevaIN/python_lesson_3 | /text_L3.py | 1,584 | 4.1875 | 4 | #Считать текст из файла и выполнить последовательность действий:
print('1) методами строк очистить текст от знаков препинания;')
print()
f = open('text.txt', encoding='utf-8')
text = f.read()
str = text
symbol_list = [' ','.',',','?','!','-','–','—',"'",'"','«','»',':',';','(',')','\n']
for a in range(len(symbol_list)):
str = str.replace(symbol_list[a],' ')
print(str)
print()
print('2) сформировать list со словами (split);')
print()
text_list = str.split()
print(text_list)
print()
print('3) привести все слова к нижнему регистру (map);')
print()
text_list = list(map(lambda x: x.lower(),text_list))
print(text_list)
print()
print('4) получить из list пункта 3 dict, ключами которого являются слова, а значениями их количество появлений в тексте;')
print()
text_dict = {a:text_list.count(a) for a in text_list}
print(text_dict)
print()
print('5) вывести 5 наиболее часто встречающихся слов (sort), вывести количество разных слов в тексте (set).')
print()
sort_list = list(text_dict.items())
sort_list.sort(key = lambda i: i[1],reverse = True)
print('5 наиболее часто встречающихся слов:')
print(sort_list[:5])
text_set = set(text_list)
print('Количество разных слов в тексте:')
print(len(text_set)) | false |
d8275b0bbc9be8dbf86bd2657ab2a7c4e3768c02 | jack-alexander-ie/data-structures-algos | /Topics/3. Basic Algorithms/1. Basic Algorithms/binary_search_first_last_indexes.py | 2,635 | 4.125 | 4 | def recursive_binary_search(target, source, left=0):
if len(source) == 0:
return None
center = (len(source)-1) // 2
if source[center] == target:
return center + left
elif source[center] < target:
return recursive_binary_search(target, source[center+1:], left+center+1)
else:
return recursive_binary_search(target, source[:center], left)
def first_and_last_index(arr, number):
"""
Given a sorted array that may have duplicate values, use binary
search to find the first and last indexes of a given value.
Args:
arr(list): Sorted array (or Python list) that may have duplicate values
number(int): Value to search for in the array
Returns:
a list containing the first and last indexes of the given value
"""
if len(arr) == 1: # Check to see if array has more than 1 element
if arr[0] == number:
return [0, 0]
else:
return [-1, -1]
rec_index = recursive_binary_search(number, arr) # Recursive call to find if element is in a list
if not rec_index:
return [-1, -1]
start_index, end_index = rec_index, rec_index + 1
if end_index == len(arr):
end_index -= 1
indexes = [start_index, end_index]
# Find start index
while arr[start_index] == number:
if start_index == 0:
break
if arr[start_index - 1] == number:
start_index -= 1
else:
break
# Find end index
while arr[end_index] == number:
if end_index == len(arr):
break
if end_index + 1 == len(arr):
break
if arr[end_index + 1] == number:
end_index += 1
else:
break
return [start_index, end_index]
def test_function(test_case):
input_list = test_case[0]
number = test_case[1]
solution = test_case[2]
output = first_and_last_index(input_list, number)
if output == solution:
print("Pass")
else:
print("Fail")
input_list = [1]
number = 1
solution = [0, 0]
test_case_1 = [input_list, number, solution]
test_function(test_case_1)
input_list = [0, 1, 2, 3, 3, 3, 3, 4, 5, 6]
number = 3
solution = [3, 6]
test_case_2 = [input_list, number, solution]
test_function(test_case_2)
input_list = [0, 1, 2, 3, 4, 5]
number = 5
solution = [5, 5]
test_case_3 = [input_list, number, solution]
test_function(test_case_3)
input_list = [0, 1, 2, 3, 4, 5]
number = 6
solution = [-1, -1]
test_case_4 = [input_list, number, solution]
test_function(test_case_4)
| true |
d2fdddb9967037869d65f92edf0a93c4a1717c6f | jack-alexander-ie/data-structures-algos | /Topics/2. Data Structures/Recursion/recursion.py | 2,728 | 4.6875 | 5 |
def sum_integers(n):
"""
Each function waits on the function it called to complete.
e.g. sum_integers(5)
The function sum_integers(1) will return 1, then feedback:
sum_integers(2) returns 2 + 1
sum_integers(3) returns 3 + 3
sum_integers(4) returns 4 + 6
sum_integers(5) returns 5 + 10
"""
# Base Case
if n == 1:
return 1
return n + sum_integers(n - 1)
# Works
# print(sum_integers(5))
# Doesn't work
# print(sum_integers(1000))
"""
Python has a limit on the depth of recursion to prevent a stack overflow. However, some compilers will turn
tail-recursive functions into an iterative loop to prevent recursion from using up the stack. Since Python's
compiler doesn't do this, watch out for this limit.
Tail-recursive functions are functions in which all recursive calls are tail calls and hence do not build up
any deferred operations.
Each call to factorial generates a new stack frame. The creation and destruction of these stack frames is what
makes the recursive factorial slower than its iterative counterpart.
"""
def power(n):
"""
Each function waits on the function it called to complete.
e.g. 2^5
The function power_of_2(0) will return 1:
1 returned from power_of_2(0), power_of_2(1) returns 2∗1
2 returned from power_of_2(1), power_of_2(2) returns 2∗2
4 returned from power_of_2(1), power_of_2(2) returns 2∗4
8 returned from power_of_2(1), power_of_2(2) returns 2∗8
16 returned from power_of_2(4), power_of_2(5) returns 2∗16
"""
if n == 0:
return 1
return 2 * power(n - 1)
# Works
# print(power(5))
# Causes max recursion depth error
# print(power(1000))
def factorial(n):
if n == 0 or n == 1:
return 1
previous = factorial(n-1)
return n * previous
# print(factorial(5))
"""
Slicing Arrays
"""
# Not particularly time or space efficient
def sum_array(array):
# Base Case - when down to it's last element
if len(array) == 1:
return array[0]
# Recursive case - keep burrowing
return array[0] + sum_array(array[1:])
# print(sum_array([1, 2, 3, 4, 5, 6]))
def sum_array_index(array, index):
"""
Instead of slicing, pass the index for the element needed for addition.
"""
# Base Case - when the end of the array is reached
if len(array) - 1 == index:
return array[index]
# Recursive Case - Same array passed in each time but index is incremented to grab values
return array[index] + sum_array_index(array, index + 1)
print(sum_array_index([1, 2, 3, 4, 5, 6], 0))
| true |
92d1e98c5ee646d5d8e9811c609af686208cb983 | abhijitmk/Rock-paper-scissors-spock-lizard-game | /rock paper scissors spock lizard game.py | 2,191 | 4.1875 | 4 | # Rock-paper-scissors-lizard-Spock template
# The key idea of this program is to equate the strings
# "rock", "paper", "scissors", "lizard", "Spock" to numbers
# as follows:
#
# 0 - rock
# 1 - Spock
# 2 - paper
# 3 - lizard
# 4 - scissors
import random
# helper functions
def name_to_number(name):
if(name=="rock"):
return 0
elif(name=="Spock"):
return 1
elif(name=="paper"):
return 2
elif(name=="lizard"):
return 3
elif(name=="scissors"):
return 4
# convert name to number using if/elif/else
def number_to_name(number):
if(number==0):
return "rock"
elif(number==1):
return "Spock"
elif(number==2):
return "paper"
elif(number==3):
return "lizard"
elif(number==4):
return "scissors"
# convert number to a name using if/elif/else
def rpsls(player_choice):
# print a blank line to separate consecutive games
print ""
# print out the message for the player's choice
print "Player chooses",player_choice
# convert the player's choice to player_number using the function name_to_number()
player_value = name_to_number(player_choice)
# compute random guess for comp_number using random.randrange()
computer_value = random.randrange(0,5)
# convert comp_number to comp_choice using the function number_to_name()
computer_name = number_to_name(computer_value)
# print out the message for computer's choice
print "Computer chooses",computer_name
# compute difference of comp_number and player_number modulo five
difference = (player_value-computer_value)%5
if(difference==1) or (difference==2):
return "Player wins!"
elif(difference==3) or (difference==4):
return "Computer wins!"
else:
return "Player and computer tie!"
# use if/elif/else to determine winner, print winner message
# test your code - THESE CALLS MUST BE PRESENT IN YOUR SUBMITTED CODE
print rpsls("rock")
print rpsls("Spock")
print rpsls("paper")
print rpsls("lizard")
print rpsls("scissors")
| true |
7904febc4341aa06bb4beeefcaad7dc856296da9 | codpro880/project_euler | /python/problem_9.py | 836 | 4.40625 | 4 | """
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
"""
import math
def main():
for possible_triple in generate_possible_triples():
a, b, c = possible_triple
if a + b + c == 1000 and is_pythagorean_triple(a, b, c):
print(a * b * c)
def generate_possible_triples():
""" Just make sure we satisfy a < b < c """
for c in range(1001):
for b in range(c):
for a in range(b):
yield a, b, c
def is_pythagorean_triple(a, b, c):
return a**2 + b**2 == c**2 and is_perfect_square(a**2 + b**2)
def is_perfect_square(x):
return math.sqrt(x) == int(math.sqrt(x))
main() | false |
2022ee151003dadfd3e1a55b23644e0b37ebe16c | liwei86521/Design-Patterns-Py | /结构型模式/结构型模式-适配器模式.py | 1,393 | 4.125 | 4 | # -*- coding:utf-8 -*-
#适配器模式:由于系统调用方式的原因,需要把不同类里面的方法(名字不一样),用同样的方式来调用
class Bird:
def fly(self):
print('bird is flying ...')
class Dog:
def bark(self):
print('dog is barking ...')
class People:
def speak(self):
print('people is speaking ...')
class Adapter:
def __init__(self, clz_name, method):
self.clz_name = clz_name
self.__dict__.update(method) # *****
#self.__dict__ {'clz_name': <__main__.Bird object at 0x000>, 'test': <bound method Bird.fly of <__main__.Bird object at 0x000>>}
# print("self.__dict__ ",self.__dict__)
def test_fun():
dog = Dog()
bird = Bird()
people = People()
objects = []
# dd = dict(test="123") # dd --> {'test': '123'}
# dd2 = dict("test" = "123") # 报错
objects.append(Adapter(bird, dict(test=bird.fly)))
objects.append(Adapter(dog, dict(test=dog.bark)))
objects.append(Adapter(people, dict(test=people.speak)))
for object in objects:
object.test()
# Adapter(dog, dict(tes1t=dog.bark)).tes1t()
# Adapter(bird, dict(tes2t=bird.fly)).tes2t()
# Adapter(people, dict(tes3t=people.speak)).tes3t()
test_fun()
"""
bird is flying ...
dog is barking ...
people is speaking ...
"""
| false |
0a3caa0649b0442ab39a9d4baebce376191a4767 | jeevan-221710/AIML2020 | /1-06-2020assignment.py | 994 | 4.15625 | 4 | #password picker
import string
from random import *
print("Welcome password Picker!!!!")
adj = ["Excellet","Very Good","Good","Bad","Poor"]
noun = ["jeevan","sai","narra","anaconda","jupyter"]
digits = string.digits
spl_char = string.punctuation
Welcome password Picker!!!!
while True:
password = choice(adj) + choice(noun) + choice(digits) + choice(spl_char)
print("Your Password is : ",password)
print("Do you want to generate New password? ")
response = input("Enter yes for New password and No for Not generating the password: ")
if response in ["NO","no","No","nO"]:
break
elif response in ["Yes","yes"]:
continue
else:
print("Enter Either Yes or No")
Your Password is : Excelletjeevan5^
Do you want to generate New password?
Enter yes for New password and No for Not generating the password: yes
Your Password is : Poorsai4!
Do you want to generate New password?
Enter yes for New password and No for Not generating the password: no
| true |
f820b900bce0f1a3de25fca50a91cf8a8a23eab9 | MLameg/computeCones | /computeCones.py | 811 | 4.375 | 4 | import math
print("This program calculates the surface area and volume of a cone.")
r = float(input("Enter the radius of the cone (in feet): "))
h = float(input("Enter the height of the cone (in feet): "))
print("The numbers you entered have been rounded to 2 decimal digits.\nRadius = "
+str(round(r,2))+ " feet & Height = " +str(round(h,2))+ " feet.")
def cone_surface_area(r, h):
sa1 = math.pi * (pow(r,2))
sa2 = (pow(r,2) + pow(h,2) )
sa3 = (math.pi * r) * math.sqrt(sa2)
final = sa1 + sa3
print("The surface area of the cone is " +str(round(final,2))+ " feet.")
def cone_volume(r,h):
v1 = ( math.pi * (pow(r,2)) * h)
final = v1 / 3
print("The volume of the cone is " +str(round(final,2))+ " feet.")
cone_surface_area(r,h)
cone_volume(r,h)
| true |
1ca49521e467baac5b5022196920c0302e112f4d | Tha-Ohis/demo_virtual | /Hello.py | 619 | 4.15625 | 4 |
name=input("Enter your name: ")
print("Hello" ,name)
# # x=4
# # y=3
# # z=10
# # k=15
# # if x ==y:
# # print (x)
# # elif y > z:
# # print(y)
# # elif k > z:
# # print(k)
# # else:
# # print(z)
# # Johns_age=20
# # Wicks_age=25
# # pauls_age=23
# # if Johns_age>Wicks_age:
# # print("John is older")
# # elif Johns_age ==Wicks_age and pauls_age ==Wicks_age:
# # print("Same")
# # else:
# # print ("Wick is Older")
def my_function(name, age):
print("Welcome" +name+ "you are" +age+ "yrs old")
name=input("Enter your name:")
age=input("Enter your age:")
my_function(name, age)
| false |
4b69f0783a133a08f34e2dc0a1190df3340dc0f1 | Tha-Ohis/demo_virtual | /Functions/Using Funcs to guess highest number.py | 400 | 4.15625 | 4 |
def highest_number(first, second, third):
if first > second and first > third:
print(f"{first}is the highest number")
elif second > first and second > third:
print(f"{second} is the highest number")
elif third > first and third > second:
print(f"{third} is the highest number")
else:
print("Two or more numbers are equal" )
highest_number(4,55,7)
| true |
81634c60ec9ab4a5d9c75c7de1eada0e8ec45865 | Tha-Ohis/demo_virtual | /Program that checks the hrs worked in a day and displays the wage.py | 631 | 4.25 | 4 | # #Write a program that accepts the name, hours worked a day, and displays the wage of the person
name=input("Enter your Name: ")
hrs=float(input("Enter the No of Hours Worked in a day: "))
rate=20*hrs
wage=(f"You've earned {rate}$")
print(wage)
# #Write a program that takes in the sides of a rectangle and displays its area and perimeter
name=input("Enter your name: ")
length=int(input("Enter the Length of a rectangle: "))
width=int(input("Enter the width of a rectangle: "))
area=length*width
print(f"The area of the rectangle is:{area}")
perimeter=(2*length + 2*width)
print(f"The perimeter of the rectangle is:{perimeter}") | true |
fee363dc717bbae969d71338fd0756e7ddc577a6 | niefy/LeetCodeExam | /explore_medium/sorting_and_searching/SortColors.py | 1,256 | 4.25 | 4 | """
https://leetcode-cn.com/explore/interview/card/top-interview-questions-medium/50/sorting-and-searching/96/
题目:颜色分类
给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。
此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。
注意:
不能使用代码库中的排序函数来解决这道题。
示例:
输入: [2,0,2,1,1,0]
输出: [0,0,1,1,2,2]
进阶:
一个直观的解决方案是使用计数排序的两趟扫描算法。
首先,迭代计算出0、1 和 2 元素的个数,然后按照0、1、2的排序,重写当前数组。
你能想出一个仅使用常数空间的一趟扫描算法吗?
@author Niefy
@date 2018-12-12
"""
class Solution:
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
count=[0,0,0]
for k in nums:
count[k]+=1
nums[:]=[0]*count[0]+[1]*count[1]+[2]*count[2]
#测试代码
t=Solution()
nums1=[0,1]
t.sortColors(nums1)
print(nums1)
nums2=[2,0,2,1,1,0]
t.sortColors(nums2)
print(nums2)
| false |
a0b3d022d89f844f0c0c0e577a64b17b64518869 | xvrlad/Python-Stuff | /Lab01A - Q10.py | 294 | 4.125 | 4 | prompt = "Enter a word: "
string = input(prompt)
letter_list = list(string)
letter_list.sort()
new_dict = {}
for letters in letter_list:
if letters not in new_dict:
new_dict[letters] = ord(letters)
for letters, asciis in new_dict.items():
print("{}:{}".format(letters,asciis))
| true |
72f6ecdabe68de3f216b47c50f029dbb20d634cb | KrisNguyen135/PythonSecurityEC | /PythonRefresher/01-control-flow/loops.py | 829 | 4.5625 | 5 | #%% While loops check for the conditions at each step.
x = 1
while x < 10:
print(x)
x += 1
print('Loop finished.')
#%% For loops are used to iterate through a sequence of elements.
a = [1, 2, 3]
for item in a:
print(item)
print()
#%% range(n) returns an iterator from 0 to (n - 1).
for index in range(len(a)):
print(index, a[index])
#%% One can loop through the keys in a dictionary in a for loop.
dict = {'a': 1, 'b': 2, 'c': 3}
for key in dict:
print(key, dict[key])
print()
#%% enumerate() returns the individual elements and their corresponding index
# in pairs in a list.
for index, value in enumerate(a):
print(index, value)
print()
#%% zip() returns the individual elements of two given lists in pairs.
b = [2, 3, 4]
print(a)
print(b)
print()
for a_i, b_i in zip(a, b):
print(a_i, b_i)
| true |
d36fe85647e5b761c392d510b0227c48a40b6d38 | faryar48/practice_bradfield | /python-practice/learn_python_the_hard_way/ex08.py | 2,230 | 4.5 | 4 | def break_words(stuff):
"""THis function will break up words for us."""
words = stuff.split(' ')
return words
def sort_words(words):
"""Sorts the words."""
return sorted(words)
def print_first_word(words):
"""Prints the first word after popping it off."""
word = words.pop(0)
print word
def print_last_word(words):
"""Prints the last words after popping it off."""
word = words.pop(-1)
print word
def sort_sentence(sentence):
"""Takes in a full sentence and returns the sorted words."""
words = break_words(sentence)
return sort_words(words)
def print_first_and_last(sentence):
"""Prints the first and last words of the sentence."""
words = break_words(sentence)
print_first_word(words)
print_last_word(words)
def print_first_and_last_sorted(sentence):
"""Sorts the words then prints the first and last one."""
words = sort_sentence(sentence)
print_first_word(words)
print_last_word(words)
# In this exercise we're going to interact with your ex25.py file inside the python interpreter you used periodically to do calculations. You run python from the terminal like this:
# $ python
# Python 2.7.1 (r271:86832, Jun 16 2011, 16:59:05)
# [GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
# Type "help", "copyright", "credits" or "license" for more information.
# >>>
# import ex25
# sentence = "All good things come to those who wait."
# words = ex25.break_words(sentence)
# words
# sorted_words = ex25.sort_words(words)
# sorted_words
# ex25.print_first_word(words)
# ex25.print_last_word(words)
# words
# ex25.print_first_word(sorted_words)
# ex25.print_last_word(sorted_words)
# sorted_words
# sorted_words = ex25.sort_sentence(sentence)
# sorted_words
# ex25.print_first_and_last(sentence)
# ex25.print_first_and_last_sorted(sentence)
# When should I print instead of return in a function?
# The return from a function gives the line of code that called the function a result. You can think of a function as taking input through its arguments, and returning output through return. The print is completely unrelated to this, and only deals with printing output to the terminal.
| true |
fbfa8a3040fc10f13a593a4b4bc2661ccac37a81 | farzanakhareem/Python-program | /fibonocci.py | 411 | 4.46875 | 4 | # Python program to display the Fibonacci sequence
def recursive_fibo(n):
if n <= 1:
return n
else:
return(recursive_fibo(n-1) + recursive_fibo(n-2))
nterms =int(input("enter the value: "))
# check if the number of terms is valid
if nterms <= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(recursive_fibo(i))
| false |
44f1516db4a25076cf141b193ebbe1f6e46bced2 | erickbgc/Python-intro | /strings.py | 1,113 | 4.25 | 4 | #Formas de operar con un string
myStr = 'Hola Mundo tarados'
print('respuesta: ' + myStr) #Otras fornas de
print(f'respuesta: {myStr}') #concatenar
print('respuesta: {0}'.format(myStr))
"""
-dir sirve para saber todo
lo que se pueda hacer con una string
"""
# print(dir(myStr))
#El print es solo para mostrarlo en pantalla,
#realmente solo ocupamos myStr.EQUIS()
# print(myStr.upper())
# print(myStr.lower())
# print(myStr.swapcase())
# print(myStr.capitalize())
# Tambien podemos poner otro metodo despues de aplicar
# el metodo anterior.
# Estos se llaman, 'metodos encadenados'
# print(myStr.replace('Hola', 'Adios').upper())
# print(myStr.count('o'))
# print(myStr.count(' '))
# Para 'startswith' tiene que concordar con la string
# Utiliza operacion booleana
# print(myStr.startswith('Hola'))
# print(myStr.endswith('Hola'))
# print(myStr.split('o'))
# print(myStr.find(' '))
# len() -con esto sabemos la longitud de nuestra string
# print(len(myStr))
# print(myStr.index('a'))
# print(myStr.isnumeric())
# print(myStr.isalpha())
# print(myStr[5])
# print(myStr[-4])
| false |
4bb152b990e86c9032072f399e94817fa140cf83 | Littlemansmg/pyClass | /Week 2 Assn/Project 4/4-2.py | 343 | 4.1875 | 4 | # created by Scott "LittlemanSMG" Goes on 11/05/2019
def miles_to_feet(miles):
feet = miles * 1520
return int(feet)
def main():
miles_input = input("How many miles did you walk?: ")
miles_input = float(miles_input)
print("You walked {} feet.".format(miles_to_feet(miles_input)))
if __name__ == "__main__":
main()
| false |
c119cf284f9e9afe49e906b8f4b1ff771eee66c9 | ddh/codewars | /python/range_extraction.py | 1,817 | 4.625 | 5 | """
A format for expressing an ordered list of integers is to use a comma separated list of either
individual integers
or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. The range includes all integers in the interval including both endpoints. It is not considered a range unless it spans at least 3 numbers. For example ("12, 13, 15-17")
Complete the solution so that it takes a list of integers in increasing order and returns a correctly formatted string in the range format.
Example:
solution([-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20])
# returns "-6,-3-1,3-5,7-11,14,15,17-20"
"""
# idea:
# save current_index
# if in range mode
# is next number consecutive
# # No? then exit range mode and append to string current number and append running string into array
# If not in range mode
# # Check if possible range exist (three numbers)
# # If possible range exists, turn on range mode and store 'currentnumber + -'
# Else append current number
def solution(args):
extracted_nums = []
range_mode = False
range_string = None
for i, num in enumerate(args):
if range_mode:
# Break out of range mode if on last index or if next number is not contiguous
if i == len(args) - 1 or args[i + 1] != num + 1:
range_mode = False
extracted_nums.append(f'{range_string}{str(num)}')
else:
# Toggle range mode if there's two numbers ahead and they are contiguous
if i < len(args) - 2 and args[i + 2] - num == 2:
range_mode = True
range_string = str(f'{num}-')
else:
extracted_nums.append(str(num))
return ','.join(extracted_nums)
# Driver
print(solution([-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20])) | true |
14390a2ae3b6ad53a988c321de9df62ad7110e00 | ddh/codewars | /python/basic_mathematical_operations.py | 1,478 | 4.34375 | 4 | """
Your task is to create a function that does four basic mathematical operations.
The function should take three arguments - operation(string/char), value1(number), value2(number).
The function should return result of numbers after applying the chosen operation.
Examples
basic_op('+', 4, 7) # Output: 11
basic_op('-', 15, 18) # Output: -3
basic_op('*', 5, 5) # Output: 25
basic_op('/', 49, 7) # Output: 7
"""
def basic_op(operator, value1, value2):
# code here
if operator == '+':
return value1 + value2
if operator == '-':
return value1 - value2
if operator == '*':
return value1 * value2
if operator == '/':
return value1 / value2
# driver
print(basic_op('+', 4, 7)) # Output: 11
print(basic_op('-', 15, 18)) # Output: -3
print(basic_op('*', 5, 5)) # Output: 25
print(basic_op('/', 49, 7)) # Output: 7
# Try doing this with only using addition: sum or +
def basic_op2(operator, value1, value2):
if operator == '+':
return value1 + value2
if operator == '-':
return value1 + -value2
if operator == '*':
return sum([value1 for n in range(value2)])
if operator == '/':
count = 0
while value1 != 0:
value1 += -value2
count += 1
return count
# driver
print(basic_op2('+', 4, 7)) # Output: 11
print(basic_op2('-', 15, 18)) # Output: -3
print(basic_op2('*', 5, 5)) # Output: 25
print(basic_op2('/', 49, 7)) # Output: 7 | true |
160c7cb9ab9719c4d0573ce90bb4c9e70ba1ca9b | junyechen/PAT-Advanced-Level-Practice | /1108 Finding Average.py | 2,573 | 4.34375 | 4 | """
The basic task is simple: given N real numbers, you are supposed to calculate their average. But what makes it complicated is that some of the input numbers might not be legal. A legal input is a real number in [−1000,1000] and is accurate up to no more than 2 decimal places. When you calculate the average, those illegal numbers must not be counted in.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤100). Then N numbers are given in the next line, separated by one space.
Output Specification:
For each illegal input number, print in a line ERROR: X is not a legal number where X is the input. Then finally print in a line the result: The average of K numbers is Y where K is the number of legal inputs and Y is their average, accurate to 2 decimal places. In case the average cannot be calculated, output Undefined instead of Y. In case K is only 1, output The average of 1 number is Y instead.
Sample Input 1:
7
5 -3.2 aaa 9999 2.3.4 7.123 2.35
Sample Output 1:
ERROR: aaa is not a legal number
ERROR: 9999 is not a legal number
ERROR: 2.3.4 is not a legal number
ERROR: 7.123 is not a legal number
The average of 3 numbers is 1.38
Sample Input 2:
2
aaa -9999
Sample Output 2:
ERROR: aaa is not a legal number
ERROR: -9999 is not a legal number
The average of 0 numbers is Undefined
"""
#########################################
"""
非常简单,利用异常机制
"""
#########################################
N = int(input())
number = input().split()
total, amount = 0, 0
for i in range(N):
try:
number_int = int(number[i])
if -1000 <= number_int <= 1000:
total += number_int
amount += 1
else:
print("ERROR: %s is not a legal number" % number[i])
except:
try:
number_float = float(number[i])
number_split = number[i].split('.')
if len(number_split[1]) > 2:
print("ERROR: %s is not a legal number" % number[i])
else:
if -1000 <= number_float <= 1000:
total += number_float
amount += 1
else:
print("ERROR: %s is not a legal number" % number[i])
except:
print("ERROR: %s is not a legal number" % number[i])
if amount == 0:
print("The average of 0 numbers is Undefined")
elif amount == 1:
print("The average of 1 number is %.2f" % total)
else:
print("The average of %d numbers is %.2f" % (amount, total/amount))
| true |
57b09375d75919214cd994056c2b4013bde55e90 | hrishigadkari/Hackerrank | /staircase.py | 394 | 4.15625 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the staircase function below.
def staircase(n):
for i in range(0,n):
for j in range(0,n-1-i):
print(" ",end="")
for j in range(0,i+1):
print("#", end ="")
print(end="\n")
if __name__ == '__main__':
n = int(input())
staircase(n)
| false |
7ac060f0eaedadd5c18d3dce33afa776639f45f2 | TranD2020/Backup | /lists.py | 1,315 | 4.34375 | 4 | # Make a list
myClasses = ["Algebra", "English", "World History"]
print(myClasses)
# add an item to the list
# append or insert
# append will add to the back of the list
myClasses.append("Coding")
print(myClasses)
favClass = input("What is your favorite class? ")
myClasses.append(favClass)
print(myClasses)
# insert
myClasses.insert(3, "Art")
print(myClasses)
# overwrite
myClasses[4] = "Science"
print(myClasses)
# remove list items
# remove, pop
# remove will remove a specific item
myClasses.remove("Science")
print(myClasses)
# myClasses.remove("Lunch")
# pop will remove the item at a specific index
myClasses.pop() # erases the last item
print(myClasses)
myClasses.pop(1)
print(myClasses)
# len - it returns the length of a list
print("myClasses is " + str(len(myClasses)) + " items long")
print(myClasses[len(myClasses) - 1])
# loop through a list
count = 1
for aClass in myClasses:
print("Item " + str(count) + " is " + aClass)
count = count + 1
numbers = [1, 23, 47, 65, 89, 32, 54, 76]
# challenge: loop through the list add the numbers and print the sum
total = 0
for aNum in numbers:
total += aNum
print(total)
myClasses.append("cooking")
#.append("cooking")
if "cooking" in myClasses:
print("Have fun cooking")
else:
print("Ok then")
| true |
aa5d7c78bc0e77b5ad660b713b65b918ae20707d | TranD2020/Backup | /practice3.py | 393 | 4.375 | 4 | print("Hello, this is the Custom Calendar.")
day = input("What is today(monday/tuesday/wednesday/thursday/friday/saturday/sunday): ")
if day == "monday":
print("It's Monday, the weekend is over")
elif day == "friday":
print("It's Friday, the weekend is close")
elif day == "saturday" or "sunday":
print("It's the weekend, time to relax")
else:
print("Its not the weekend yet") | true |
a795152079fe503c87516ab5b753c0c33c504c73 | gouri21/c97 | /c97.py | 491 | 4.25 | 4 | import random
print("number guessing game")
number = random.randint(1,9)
chances = 0
print("guess a number between 1 and 9")
while chances<5:
guess = int(input("enter your guess"))
if guess == number:
print("congratulations you won!")
break
elif guess<number:
print("guess a number higher than that",guess)
else:
print("guess a number lower than that",guess)
chances +=1
if not chances<5:
print("you lose and the number is",number)
| true |
e0883ed37e79623f17ea2eaae85cc49b05e012ea | BigPPython/Name | /name.py | 1,110 | 4.125 | 4 | # Code: 1
# Create a program that takes a string name input,
# and prints the name right after.
# Make sure to include a salutation.
import sys
a = '''**********************************
*WHAT IS YOUR SEXUAL ORIENTATION?*
*TYPE *
*M FOR MALE *
*F FOR FEMALE *
**********************************'''
print(a) # prints string a
sex = str(input()) # user input
s =''
if sex in ['M', 'm']: # Conditional statement for question above
s = 'Mr.'
elif sex in ['F', 'f']:
b = ''' ******************
*ARE YOU MARRIED?*
*TYPE *
*YES OR NO *
******************'''
print(b)
m = str(input())
if m in ['y', 'Y', 'yes', 'Yes', 'YES']: # accepts all yes like answer
s = 'Mrs '
elif m in ['n', 'N', 'no', 'No', 'NO']: # accepts all no like answers
s = 'Ms '
else:
print("PLEASE TRY AGAIN")
sys.exit()
else:
print("PLEASE TRY AGAIN")
sys.exit()
print('Insert name here:')
name = str(input())
print('Hello, '+ s + name) # prints final result
sys.exit()
| true |
5cf92bdd9fbd1820297c63dcb370a5d7b3bb1129 | SKosztolanyi/Python-exercises | /11_For loop simple universal form.py | 345 | 4.25 | 4 | greeting = 'Hello!'
count = 0
# This is universal python for loop function form
# The "letter" is <identifier> and "greeting" is <sequence>
# the "in" is crucial. "letter" can be changed for any word and the function still works
for letter in greeting:
count += 1
if count % 2 == 0:
print letter
print letter
print 'done' | true |
11cea43282d93c8ff11abe1bd833275be18744c6 | SKosztolanyi/Python-exercises | /88_Tuples_basics.py | 1,136 | 4.6875 | 5 | # Tuples are non-changable lists, we can iterate through them
# Tuples are immutable, but lists are mutable.
# String is also immutable - once created, it's content cannot be changed
# We cannot sort, append or reverse a tuple
# We can only count or index a tuple
# The main advantage of a tuple is, they are more efficient
# We can use tuples when we make temporary variables
# The items() method in a dictionary returns a list of (key, value) tuples
# We can sort dictionaries by sorting tuples in dictionary
# Method dict.sort() sorts by keys - the values don't even get looked at.
d = { "b":2, "a":10, "c":18}
t = d.items()
print t
t.sort()
print t
t2 = sorted(d.items()) # this is more direct method
print t2
# It is possible to sort a dictionary by values when I iterate through a list of values
c = { "b":2, "a":10, "c":18, "d":-16, "e": 21}
print c
tmp = list()
for k, v in c.items():
tmp.append( (v, k) ) # reversing keys and values
print tmp
tmp.sort(reverse = True)
print tmp
#short verion:
d = { "b":2, "a":10, "c":18, "d":-16, "e": 21}
print sorted( [ (v, k) for k, v in d.items() ] )
# sorted by value in one line | true |
d0fc126abdd1251d5c7555870ec36b49798c8936 | SKosztolanyi/Python-exercises | /33_Defining factorials functions iterativela and recursively.py | 374 | 4.15625 | 4 | # Recursive and iterative versions of factorial function
def factI(n):
'''
Iterative way
assume that n is an int>0, returns n!
'''
res = 1
while n >1:
res = res*n
n-=1
return res
def factR(n):
'''
Recursive way
assume that n is an int>0, returns n!
'''
if n == 1:
return n
return n*factR(n-1) | true |
2827c8423400bfe3d5c7992fd80d1a8d321dbd9f | pmmorris3/Code-Wars-Solutions | /5-kyu/valid-parentheses/python/solution.py | 471 | 4.25 | 4 | def valid_parentheses(string):
bool = False
open = 0
if len(string) == 0:
return True
for x in string:
if x == "(":
if bool == False and open == 0:
bool = True
open += 1
if x == ")" and bool == True:
if open - 1 == 0:
bool = False
open -= 1
elif x == ")" and (bool == False or open == 0):
return False
return open == 0 | true |
bff81845806f726c9ebf0c35c407076314d711ff | borodasan/python-stady | /duel/1duel/1duel.py | 483 | 4.4375 | 4 | def p(p):
for i in range(0,5,2): #The range() function defaults to increment the sequence by 1,
#however it is possible to specify the increment
#value by adding a third parameter: range(0, 5, 2)
#Assignment operators are used to assign values to variables:
p+=i #p += i --> p = p + i
p-=2 #p -= 2 --> p = p - 2
print(p)
p(2)
print("\nExample Range")
for x in range (0,5,2):
print(x)
| true |
a67e31b47c7be597942229d2f9046e4b7dc4e283 | borodasan/python-stady | /python-collections-arrays/set.py | 1,504 | 4.65625 | 5 | #A set is a collection which is unordered and unindexed.
#In Python sets are written with curly brackets.
print("A set is a collection which is")
print("unordered and unindexed".upper())
print("In Python sets are written with curly brackets.")
#Create a Set
print("Create a Set:")
thisset = {"apple", "banana", "cherry"}
print(thisset)
print("Sets are unordered, so the items will appear in a random order.")
print("You cannot access items in a set by referring to an index,")
print("since sets are unordered the items has no index.")
print("But you can loop through the set items using a")
print("for".upper())
print("loop,")
print("or ask if a specified value is present")
print("in".upper())
print("a set, by using the in keyword.")
print("Loop through the set, and print the values:")
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
print("Check if \"banana\" is present in the set:")
thisset = {"apple", "banana", "cherry"}
print("banana" in thisset)
print("To add one item to a set use the add() method.")
print("To add more than one item to a set use the update() method.")
print("Add an item to a set, using the add() method:")
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)
print("Add multiple items to a set, using the update() method:")
thisset = {"apple", "banana", "cherry"}
thisset.update(["orange", "mango", "grapes"])
print(thisset)
thisset = {"apple", "banana", "cherry"}
print(thisset)
x = thisset.pop()
print(x)
print(thisset)
| true |
423736de6e6515f77cec66aefb7941ba34c623ae | shane806/201_Live | /13. More Lists/live.py | 297 | 4.15625 | 4 | matrix = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 1, 2, 3],
[4, 5, 6, 7]]
def create_new_2d_list(height, width):
pass
def main():
# how do I get at the 9?
# how do I loop through the third row?
# how do I loop through the second column?
pass
main()
| true |
5158eedff805fe1a02c30ccc26fbe4027407d813 | untalinfo/holbertonschool-higher_level_programming | /0x0B-python-input_output/100-append_after.py | 570 | 4.125 | 4 | #!/usr/bin/python3
"""
Module
"""
def append_after(filename="", search_string="", new_string=""):
"""
Inserts a line of text to a file
Args:
filename (str, optional)
search_string (str, optional) Defaults to "".
new_string (str, optional) Defaults to "".
"""
with open(filename, encoding="UTF8") as f:
string = ""
for line in f:
string += line
if search_string in line:
string += new_string
with open(filename, "w", encoding="UTF8") as f:
f.write(string)
| true |
85eb2ffc8676179e4c6f23062f20a19e0d0a1906 | HATIMj/MyPythonProblems | /Divisor.py | 1,138 | 4.125 | 4 | #DIVISOR OR NOT
try: #trying the below inputs
n=int(input("Enter the total number of apples:--"))#Taking an input of number of apples
mn=int(input("Enter the minimum no. of students:--")) #Taking the input of minimum number of students
mx=int(input("Enter the maximum no. of students:--")) #Taking the input of maximumn number of students
except ValueError: # if there is no integer in an input it will print the below message and exit the program
print("Please Enter only integers")
exit() #Exiting the python file
if mn==mx:
if n%mn==0:print(f"This is not a range. {mn} is a divisor of {n}") #If mn>=mx then it is not a range
else:print(f"This is not a range. {mn} is not a divisor of {n}")
elif mn>mx:
print("This is not a range.")
else:
for i in range(mn,mx+1): #Looping in range
if n%i==0:print(f"{i} is a divisor of {n}") #Condition to check if it is a divisor
elif n%i!=0:print(f"{i} is not a divisor of {n}") #Condition to check if it is not a divisor
else:pass #else pass
| true |
ef953085648ad000470656586143e2cefd242470 | pratyushmb/Prat_Python_Repo | /W3Schools/tuples.py | 525 | 4.40625 | 4 | myTuple = ("a", "b", "c")
print(myTuple)
print(myTuple[1])
print(myTuple[-1])
print(myTuple[1:2])
# change tuple value though its unchangable
myList = list(myTuple)
myList[1] = "change"
myTuple = tuple(myList)
print(myTuple)
# iterate thru tuple: need to verify
for x in myTuple:
print(x)
if "change" in myTuple:
print("yes this exists!")
# one item tuple, remember comma
oneItemTuple = ("hi",)
print(oneItemTuple)
print(type(oneItemTuple))
# tuple constructor
newTuple = tuple(("a", "b", "c"))
print(newTuple)
| false |
6ea2887ac7d1679ca5663d773c288bbfc38b40cf | emmanuelnyach/python_basics | /algo.py | 818 | 4.25 | 4 | # num1 = input('enter first number: ')
# num2 = input('enter second number: ')
#
# sum = float(num1) + float(num2)
#
# print('the sum of {} and {} is {}'.format(num1, num2, sum))
# finding the largest num in three
#
# a = 8
# b = 4
# c = 6
#
# if (a>b) and (a>c):
# largest=a
# elif (b>a) and (b>c):
# largest=b
# else:
# largest=c
#
# print(largest, " is the largest ")
# sum of natural numbers upto num
# num = 6
#
# if num < 0:
# print('enter positive numbers!')
# else:
# sum = 0
#
# while(num>0):
# sum += num
# num -= 1
# print("the sum is ", sum)
num = int(input('enter number: '))
factorial = 1
if num < 0:
print('sorry, factorial does not exist!')
elif num == 0:
print('the factorial of 0 is 1')
else:
for i in range(1, )
| true |
b3c8b121c0559b7b11c070f102ecd971f7eb28fd | noyonict/Number-conversion-in-Python-3 | /decimal_to_binary.py | 324 | 4.25 | 4 | # Convert Decimal number to Binary Number
def dec_to_bin(dec_num):
"""Convert Decimal Number dec_num to Binary Number"""
bin_num = 0
power = 0
while dec_num > 0:
bin_num += 10 ** power * (dec_num % 2)
dec_num //= 2
power += 1
return bin_num
print(dec_to_bin(46))
| false |
03d5fa4ff4dece6cb4e00d200257353e66ce478d | elementbound/jamk-script-programming | /week 4/listsum.py | 738 | 4.125 | 4 | # 4-3) list calculation with type detection
#
# calculate sum and average of elements in the list
# ignore all values in the list that are not numbers
#
# initializing the list with the following values
#
# list = [1,2,3,4,5,6,7,8,9,20,30, "aa", "bee", 11, "test", 51, 63]
def is_int(val):
try:
val = int(val)
return True
except ValueError:
return False
def main():
# Initialize list
values = [1,2,3,4,5,6,7,8,9,20,30, "aa", "bee", 11, "test", 51, 63]
# Throw out non-integer values
values = [x for x in values if is_int(x)]
# Display results
print('Sum {0}/{1} and average {2}'.format(sum(values), len(values), sum(values)/len(values)))
if __name__ == '__main__':
main()
| true |
bb510d0b1d3e9b30af489969971b3702c03eaf25 | Steven-Chavez/self-study | /python/introduction/numbers.py | 848 | 4.28125 | 4 | # Author: Steven Chavez
# Email: steven@stevenscode.com
# Date: 9/4/2017
# File: numbers.py
''' Expression is used like most other languages.
you are able to use the operators +, -, *, and /
like you would normally use them. You can also group
the expressions with parentheses ()'''
# addition, subtraction, multiplication
1 + 1 # = 2
4 - 2 # = 2
1 * 2 # = 2
# division always returns a floating point number
# whole numbers are type int decimals (5.3, 3.0) are floats
6 / 5 # = 1.2
# equations using parentheses grouping
(2 + 5) * (40-35) # = 35
# floor division (//)
11 / 2 # = 5.5 normal division
11 // 2 # = 5 floor division gets rid of the fraction
# modulus operator (%) returns the remainder of the division
11 % 2 # = 1
11 % 10 # = 1
23 % 6 # = 5
# power calculations using the (**) operator
3 ** 2 # 3 squared = 9
7 ** 5 # 7 to the power of 5 = 16807 | true |
7fb4ede2dbd7ba97c78af7fa5cedcef8fcbf7baf | rakesh0180/PythonPracties | /TupleEx.py | 506 | 4.21875 | 4 | items = [
("p1", 4),
("p2", 2),
("p3", 5)
]
# def sort_item(item):
# return item[1]
# print(item.sort(key=sort_item))
# print(item)
# using lambada we avoid above two statement
items.sort(key=lambda item: item[1])
print(items)
# map
x = list(map(lambda item: item[1], items))
print("map", x)
# filter
y = list(filter(lambda item: item[1] >= 3, items))
print("filter", y)
# list comphersion
# it is used inside of lambda
filter = [item[1] for item in items]
print("filter", filter)
| true |
7d1d9a1997ec0ad4df02b524784e424cd8a31d95 | devcybiko/DataVizClass | /Week3/RockPaperScissors.py | 812 | 4.125 | 4 | import random
while True:
options = ["r", "p", "s"]
winning_combinations = ["rs", "sp", "pr"]
### for rock, paper, scissors, lizard, spock...
# options = ["r", "p", "s", "l", "x"]
# winning_combinations = ["sp", "pr", "rl", "lx", "xs", "sl", "lp", "px", "xr", "rs"]
user_choice = input(options)
computer_choice = random.choice(options);
if user_choice not in options:
print("bad choice")
continue ### go to top of the while loop
combo = user_choice + computer_choice
if user_choice == computer_choice:
print(f"it's a draw: you both picked {user_choice}\n")
elif combo in winning_combinations:
print(f"You won! {user_choice} beats {computer_choice}\n")
else:
print(f"You lost! {user_choice} loses to {computer_choice}\n")
| true |
62e75902fa73c4b3cf3c0efbbeff4e928cb80119 | BENLINB/Practice-assignment-for-Visual-Studio | /Generate username.py | 536 | 4.125 | 4 | #Problem2
#writing programm that would prompt the username in the format Domain Name-Username.
print("#######################################")
print("WELCOME TO DBS CONSOLE")
print("#######################################")
#asking the user to input his credentials
student=input("enter username")
index= student.index("\\") #preparing an index
student_id=student[:index]
student_name= student[index:][1:]
#printing the result as the seprate combination
print("Domain",student_id)
print("Username",student_name)
| true |
599ecf8e936096c23c02615562f20d5eaf8a2b0e | prince5609/Leet_Code | /Max_Deapth_Binary_Tree.py | 579 | 4.15625 | 4 | # Given the root of a binary tree, return its maximum depth. A binary tree's maximum depth is the number of nodes
# along the longest path from the root node down to the farthest leaf node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def max_depth_tree(root):
return get_depth(root, 0)
def get_depth(node, max_depth):
if node is None:
return max_depth
else:
return max(get_depth(node.left, max_depth + 1), get_depth(node.right, max_depth + 1))
| true |
a0d4f9f823847403700707ce540fa1b6e7aef386 | Nitin-K-1999/Python_script | /Sample Script 1.py | 504 | 4.34375 | 4 | # A list of cricket team is given below. Print the number of possible matches between each of them. Also print each possible match in the format team1 vs team2.
team_list = ['CSK','RCB','Sun Risers','Deccan Chargers','Mumbai Indians']
matches = []
for index in range(len(team_list)) :
for team in team_list[index+1:] :
matches.append('{} vs {}'.format(team_list[index],team))
print('The number of possible matches is',len(matches))
print('They are :')
for match in matches :
print(match)
| true |
9550534f45044d9b5ee3c3cf3543b39fc2d123b6 | Sudhanshu277/python | /list.py | 373 | 4.21875 | 4 | # crete a list using []
a = [1, 3, 4,5,6,"pninfosys"] #index 0 start
print(a)
#access using index using a[0] , a[1]
print(a[2])
#change the value of list using
a[0] = 40
print(a)
#we can crete a list with items of different types
c = ["pnifosys" , 12,False,7.5]
print(c)
#list slicing
pn = ["vikas" , "ram" , "rohan" , "sam" , "divya" ,45]
print(pn[0:4])
print(pn(-4:)) | false |
8978220700fcf7ed48d7b0840bebd70696ee3fd8 | VRamazing/UCSanDiego-Specialization | /Assignment 2/fibonacci/fibonacci.py | 359 | 4.15625 | 4 | # Uses python3
# Task. Given an integer n, find the nth Fibonacci number F n .
# Input Format. The input consists of a single integer n.
# Constraints. 0 ≤ n ≤ 45.
def calc_fib(n):
if n==0:
return 0
elif n==1:
return 1
else:
arr=[1,1]
for i in range(2,n):
arr.append(arr[i-1]+arr[i-2])
return arr[n-1]
n = int(input())
print(calc_fib(n))
| true |
077db2a0f5904ba96886cc827b25c8d384e7e1b7 | VRamazing/UCSanDiego-Specialization | /Assignment 3/greedy_algorithms_starter_files/fractional_knapsack/fractional_knapsack.py | 2,169 | 4.15625 | 4 | # Uses python3
import sys
# Task. The goal of this code problem is to implement an algorithm for the fractional knapsack problem.
# Input Format. The first line of the input contains the number n of items and the capacity W of a knapsack.
# The next n lines define the values and weights of the items. The i-th line contains integers v i and w i
#—the value and the weight of i-th item, respectively.
# Constraints : 1 ≤ n ≤ 10 3 , 0 ≤ W ≤ 2 · 10 6 ; 0 ≤ v i ≤ 2 · 10 6 , 0 < w i ≤ 2 · 10 6 for all 1 ≤ i ≤ n.
# All the numbers are integers.
# Output Format : Output the maximal value of fractions of items that fit into the knapsack. The absolute
# value of the difference between the answer of your program and the optimal value should be at most
# 10 −3 . To ensure this, output your answer with at least four digits after the decimal point (otherwise
# your answer, while being computed correctly, can turn out to be wrong because of rounding issues
def get_optimal_value(capacity, weights, values):
value = 0.
valDensity=[]
# Frst Step calculate value density ie list containing ratio of weight per unit weight and sort it in ascending order.
for i in range(len(weights)):
valDensity.append(values[i]/weights[i])
backup=valDensity.copy() #Store Density in backup variable before sorting.
if len(weights) > 1:
valDensity.sort(reverse=True)
#Second Step - Start from element of max value density and try to fit it whole in capacity and if it doesn't take a fraction of it.
totalValue=0
for i in valDensity:
index=backup.index(i)
weight=weights[index]
value=values[index]
if capacity//weight >= 1:
capacity -= weight
totalValue += value
else:
if capacity==0:
break
totalValue += value*capacity/weight
capacity = 0
return totalValue
if __name__ == "__main__":
data = list(map(int, sys.stdin.read().split()))
n, capacity = data[0:2]
values = data[2:(2 * n + 2):2]
weights = data[3:(2 * n + 2):2]
opt_value = get_optimal_value(capacity, weights, values)
print("{:0.5f}".format(opt_value))
| true |
620323ff5e0c51b2c619e132e57523c07f206efc | ifpb-cz-ads/pw1-2020-2-ac04-team-ricardoweligton | /atividade_4_02/questao_13.py | 590 | 4.28125 | 4 | """
13) Escreva um programa que leia números inteiros do teclado. O programa
deve ler os números até que o usuário digite 0 (zero). No final da
execução, exiba a quantidade de números digitados, assim como a soma e
a média aritmética.
"""
print("\n--------- Questao 13 --------- \n")
n = 0
x = 0
soma = 0
while True:
n = int(input("Informe um número inteiro: "))
if n == 0:
break
x += 1
soma += n
media = 0
if x > 0:
media = soma / x
print(f"\nForam digitados {x} números, a soma deles é igual a {soma} e a média é igual a {media}")
| false |
cbeb6a4b06cd9f36bf351c269ca71de0793e2081 | ktandon91/DataStructures | /3. DyPro/rod_price.py | 1,021 | 4.28125 | 4 | """
Given a rod of length n inches and an array of prices that contains prices of all pieces of size smaller than n.
Determine the maximum value obtainable by cutting up the rod and selling the pieces.
For example, if length of the rod is 8 and the values of different pieces are given as following,
then the maximum obtainable value is 22 (by cutting in two pieces of lengths 2 and 6)
length | 1 2 3 4 5 6 7 8
--------------------------------------------
price | 1 5 8 9 10 17 17 20
"""
list2 = [
[1,1],
[2,5],
[3,8],
[4,9],
[5,10],
[6,17],
[7,17],
[8,20]
]
# list2 = [
#
# [1,5],
# [2,5],
# [3,7]
# ]
def recursive_cost(length_of_list):
#Base Case
if length_of_list == 0 :
return 0
cost = list2[length_of_list-1][1] + list2[len(list2)-length_of_list-1][1]
return max(cost,recursive_cost(length_of_list-1))
length_of_list = len(list2)
print(recursive_cost(length_of_list)) | true |
82234bc9ffaa3acb0a0bb64d040ec8e249789414 | iamshubhamsalunkhe/Python | /basics/Continueandbreak.py | 336 | 4.4375 | 4 | #continue is used to skip a iteration and jump back to other iteration
"""
for i in range(1,11,1):
if(i==5):
continue
print(i)
"""
'''
##break is used to break a iteration or stop a iteration at specific point
for i in range(1,11,1):
if(i==5):
continue
if(i==8):
break
print(i)
'''
| true |
d54773b3f32729d8076b34ada3d07c1be629e2b3 | standrewscollege2018/2020-year-13-python-classwork-OmriKepes | /classes and objects python.py | 1,650 | 4.625 | 5 | ''' This program demonstrates how to use classes and objects.'''
class Enemy:
''' The enemy class has life, name, and funcations that do something.'''
def __init__(self, name, life):
'''This funcation runs on instantiation and sets up all attributes.'''
self._life = life
self._name = name
#add the new enemy object to the enemy_list list
enemy_list.append(self)
def get_name(self):
'''This funcation returns the name of the enemy.'''
return(self._name)
def get_life(self):
'''This funcation returns the amount of life remaining.'''
return self._life
def attack(self):
'''This funcation substracts 1 from the object's health.'''
print("Ouch!")
self._life -= 1
def add(self):
print("Increased health!")
self._life+=1
def show_all():
'''This funcation displays details of all enemies in enemy_list.'''
for enemy in enemy_list:
print(enemy.get_name())
def life_check():
'''This funcation asks the user for an integar, and then returns the names of all enemies who have at least that much life left.'''
check = int(input("Enter a number: "))
for enemy in enemy_list:
if enemy.get_life()>= check:
print(enemy.get_name())
def create_enemy():
'''This funcation creates a new enemy with a name and life.'''
new_name = input("Enter new name: ")
new_life = int(input("Enter new life: "))
Enemy(new_name, new_life)
enemy_list.append(new_name, new_life)
# The enemy_list stores all the enemy objects
enemy_list = []
create_enemy()
life_check()
| true |
4873d8070a2d54482d0ea387eb1c901cfba8ef9e | Will-is-Coding/exercism-python | /pangram/pangram.py | 503 | 4.21875 | 4 | import re
def is_pangram(posPangram):
"""Checks if a string is a pangram"""
lenOfAlphabet = 26
"""Use regular expression to remove all non-alphabetic characters"""
pattern = re.compile('[^a-zA-Z]')
"""Put into a set to remove all duplicate letters"""
posPangram = set(pattern.sub('', posPangram).lower())
if len(posPangram) == lenOfAlphabet:
alpha = set('abcdefghijklmnopqrstuvwxyz')
return set(posPangram).issubset(alpha)
else:
return False
| true |
c0593fc5b9d1f0c56ff1039dd16fa37039fd869b | rpinnola47/PYTHON | /CLASES Fdla/clase listas.py | 1,008 | 4.125 | 4 | """
estrucutura de datos:
listas: puede estar conformada por varios elementos, que estan organizados en "fila de cajitas"
cada cajita tiene un solo valor. cada posicion tiene UN SOLO VALOR A LA VEZ pero todas esta agrupadas en una misma variable
*cada caja tiene su indice(arranca desde cero)
"""
#creando lista
pino=[4,6,3,9,7]
print(pino)#mostrar por pantalla
#seleccionar uno determinado, imprimir uno determnado
print(pino[2])
#agregar valores, uso NOMBRELISTA.APPEND(VALOR)
pino.append(5)
print(pino)
#agregar varios valores a una lista, mas de un solo valor
pino.extend([5,3,6])
print(pino)
#sacar un valor de la lista, desde un indice
pino.remove(4)
print(pino)
#contar los elementos de una lista
cantidad=len(pino)
print(cantidad)
# tambien se puede directamente print(len(pino))
#contar el ultimo indice, el maximo
cantidad=(len(pino))-1
print(cantidad)
#para imprimir el ultimo valor, primero saco el indice max
print(pino[(len(pino)-1)])
| false |
23eb4288c74348e898b5e987f8755ebf2cc2db62 | Liam-Pigott/python_crash_course | /11-Advanced_Python_Modules/defaultdict.py | 769 | 4.15625 | 4 | from collections import defaultdict
# defaultdict is a dictionary-like object which provides all methods provided by a dictionary but takes a first argument (default_factory)
# as a default data type for the dictionary. Using defaultdict is faster than doing the same using dict.set_default method.
# A defaultdict will never raise a KeyError. Any key that does not exist gets the value returned by the default factory.
d = {'k1': 1}
print(d['k1']) # 1
#print(d['k2']) # KeyError
d = defaultdict(object)
print(d['one']) # <object object at 0x006F6600>
for item in d:
print(item)
d = defaultdict(lambda : 0)
print(d['one']) # automatically assign 0 using above lambda
d['two'] = 2
print(d) # defaultdict(<function <lambda> at 0x006A7FA0>, {'one': 0, 'two': 2}) | true |
aad7fec002bf6717bb2a7e6389c964ec6344cd4a | Liam-Pigott/python_crash_course | /02-Statements/control_flow.py | 1,768 | 4.15625 | 4 | # if, elif and else
if True:
print("It's True")
else:
print("False")
loc = 'Bank'
if loc == 'Work':
print('Time to work')
elif loc == 'Bank':
print('Money maker')
else:
print("I don't know")
name = 'Liam'
if name == 'Liam':
print("Hello Liam")
elif name == 'Dan':
print('Hi Dan')
else:
print("What's your name?")
# For Loops
mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for num in mylist:
print(num)
for num in mylist:
if (num % 2 == 0):
print(f'Even number: {num}')
else:
print('Odd number: {}'.format(num))
list_sum = 0
for num in mylist:
list_sum = list_sum + num
print(f'The total sum of mylist is {list_sum}')
my_string = 'Hello world'
for letter in my_string:
print(letter)
for _ in my_string:
print('_ is used when there isn\'t any intention to use a variable in the for loop')
mylist = [(1, 2), (3, 4), (5, 6), (7, 8)]
print(len(mylist))
for item in mylist:
print(item)
# tuple unpacking
for a, b in mylist:
print(a)
print(b)
d = {'k1': 1, 'k2': 2, 'k3': 3}
for item in d:
print(item) # only prints keys
for key, value in d.items():
print(value) # prints values
# While loops
x = 0
while x < 5:
print(x)
x += 1
else:
print('x is not less than 5')
# break: breaks out of current enclosing loop
# continue: goes to the top of the closest loop
# pass: does nothing
x = [1, 2, 3]
for item in x:
pass # good as a placeholder to code later and avoid syntax errors
my_string = 'Liam'
for letter in my_string:
if letter == 'a':
continue
print(letter)
my_string = 'Liam'
for letter in my_string:
if letter == 'a':
break
print(letter)
x = 5
while x < 5:
if x == 2:
break
print(x)
x += 1 | true |
6f2d440071bdacdb59adc4409561dfb6b63683d3 | ksannedhi/practice-python-exercises | /Ex11.py | 618 | 4.34375 | 4 | '''Ask the user for a number and determine whether the number is prime or not. (For those who have forgotten, a prime number is a number that has no divisors.).
You can (and should!) use your answer from Exercise 4 to help you. Take this opportunity to practice using functions.'''
def find_prime_or_not(num):
divisors = list(range(1,num+1))
div_list = [div for div in divisors if num%div == 0]
if len(div_list) == 2:
result = "Prime"
else:
result = "Not prime"
return result
user_input = int(input("Please enter a number: "))
print(find_prime_or_not(user_input))
| true |
bbe653b8a4f428b0c7abc5ede7939455abdf2a06 | ksannedhi/practice-python-exercises | /Ex15.py | 532 | 4.4375 | 4 | '''Write a program (using functions!) that asks the user for a long string containing multiple words.
Print back to the user the same string, except with the words in backwards order. For example, say I type the string:
My name is Michele
Then I would see the string:
Michele is name My'''
def reverse_words(input_text):
words = input_text.split()
rev_words = words[::-1]
return " ".join(rev_words)
user_input_text = input("Type something: ")
print(f'Reversed output: {reverse_words(user_input_text)}')
| true |
993033a674b3d7a44cc8aacb6f9910d84c8b4531 | pzinz/sep_practice | /22_HarvardX_w01_03.py | 2,199 | 4.25 | 4 | # Static typing mean that the type checking is performed during compile time
# dynamic typing means that the type checking is performed at run time
# Varible, objects and references
# x = 3 ; Python will first create the object 3 and then create the variable X and then finally reference x -> 3
# list defined as followed
l1 = [2,3,4]
print(type(l1))
l2 = l1
print(type(l2))
l1[0] = 24
print(l1)
print(l2)
# Each object in python has a type, value and identity
L = [1,2,3]
M = [1,2,3]
print(L == M)
print(L is M) # Check whether L is the same object as M
# Above will return False
print('ID of L is:', id(L))
print("ID of M", id(M))
print(id(L) == id(M))
# Mutuable objects can be identical in contents yet be different objects
M = list(L)
print(M is L)
M = L[:]
print(M)
aa = 3
bb = aa
bb = bb - 1
print(aa)
LL = [2,3,4]
M1 = LL
M2 = LL[:]
print(M1 is M2)
# COPIES
# shallow copy
# deep copy
import copy
a = [1,[2]]
b = copy.copy(a)
c = copy.deepcopy(a)
print(b is c)
print(b is a)
print("----------")
print(True or False)
if False:
print("False")
elif True:
print("True")
else:
print("Finally")
print("============")
for x in range(10):
print(x)
age = {}
print(type(age))
age = dict()
print(type(age))
age = {"Tim": 29, "Jim": 31, "Pam": 27, "Sam": 39}
age["Tom"] = 50
age["Nick"] = 33
names = age.keys()
print(names)
print(age)
for name in names:
print(name)
print(age.keys())
for name in age.keys():
print(name,age[name])
for name in sorted(age,reverse=True):
print(name,age[name])
bears = {"Grizzly":"angry", "Brown":"friendly", "Polar":"friendly"}
for bear in bears:
if(bears[bear] == "friendly"):
print("Hello, "+bear+" bear!")
else:
print("odd")
print("====")
n = 100
number_of_times = 0
while n >= 1:
n //= 2
number_of_times += 1
print(number_of_times)
is_prime = True
for i in range(2,n):
if n%i == 0:
print(i)
print(is_prime)
numbers = range(10)
squares = []
for num in numbers:
square = num **2
squares.append(square)
print(squares)
squares2 = [number ** 2 for number in numbers]
print(squares2)
for i in range(10):
print(i)
sum(x for x in range(1,10) if x % 2)
print(sum2) | true |
ec68888812b15838438f33bcb97c68e3dac62ba2 | malekhnovich/PycharmProjects | /Chapter5_executing_control/Chapter6_dictionaries/tuple_example.py | 1,336 | 4.59375 | 5 | '''
IF DICTIONARY KEYS MUST BE TYPE IMMUTABLE WHILE LIST TYPE IS MUTABLE
YOU CAN USE A TUPLE
TUPLE CONTAINS A SEQUENCE OF VALUES SEPERATED BY COMMAS AND ENCLOSED IN PARENTHESIS(()) INSTEAD OF BRACKETS([])
'''
#THIS IS A TUPLE BECAUSE THE PARENTHESIS ARE ROUND RATHER THAN SQUARE
#SQUARE PARENTHESIS WOULD BE A LIST
#THE DIFFERENCE BETWEEN THE TWO IS A TUPLE IS IMMUTABLE WHILE A LIST IS MUTABLE
#THIS MEANS THAT A TUPLE'S CONTENTS CAN NOT BE MODIFIED WHILE A LISTS CONTENTS CAN BE MODIFIED
days=('Mo','Tu','We')
print(days)
print(days[0])
#SINCE TUPLES ARE IMMUTABLE THEY CAN BE USED AS KEYS FOR DICTIONARIES
#EXAMPLE OF USING TUPLES FOR THE KEYS IN DICTIONARY CALLED PHONEBOOK
phonebook={('Jason','Bay'):'25',
('David','Wright'):'22',
('Josh','Thole'):'23'}
print(phonebook[(('Jason','Bay'))])
print(phonebook.items())
#IF WE WANTED A ONE ITEM TUPLE WE WOULDNT BE ABLE TO JUST PUT ONE ELEMENT IN THE ROUND PARENTHESIS(())
#THIS IS BECAUSE THE COMPUTER WILL THINK IT IS A STRING OR ANOTHER INSTANCE THAT IS NOT A TUPLE
#IN ORDER TO GET A ONE ITEM TUPLE WE CAN PUT IN OUR SINGLE ITEM FOLLOWED BY A COMMA(,)
day2=('Mo',)#THIS IS THE PROPER EXECUTION OF A ONE ITEM TUPLE
day3=('Mo')#THIS IS THE INCORRECT EXECUTION OF A ONE ITEM TUPLE BECAUSE THE COMPUTER THINKS IT IS A STRING
print(type(day2))
print(type(day3)) | true |
b42ace7c28ad5224af073ba6703128d6f80bfae5 | ses1142000/python-30-days-internship | /day 10 py internship.py | 1,313 | 4.3125 | 4 | Python 3.9.0 (tags/v3.9.0:9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> import re
>>> string = "a-zA-Z0-9"
>>> if re.findall(r'/w',string):
print("the string contains a set of char")
else:
print("the string does not contains a set of char")
the string does not contains a set of char
>>>
>>>
>>> import re
>>> pattern=re.compile('a.?b')
>>> match='aaabcd'
>>> if re.search(pattern,match):
print("found a match")
else:
print("match not found")
found a match
>>>
>>>
>>> import re
>>> test_number = "internship python program"
>>> res = len(re.findall(r'/w+',test_number))
>>> print("check the number at the end of the word is:"+str(res))
check the number at the end of the word is:0
>>>
>>>
>>> import re
>>> results= re.finditer(r"([0-9]{1,3})","exercises number 1,12,13 and 260 are important")
>>> print("number of length 1 to 3")
number of length 1 to 3
>>>
>>> for n in results:
print(n.group(0))
1
12
13
260
>>>
>>>
>>> import re
>>> def match(text):
pattern = '[A-Z]+$'
if re.search(pattern,text):
return('match')
else:
return('match not found')
>>> print(match("ABCDEF"))
match
>>> print(match("GEEKS"))
match
>>> | true |
9e90c8c11d9352283cd731aec48de88038b64f88 | JanusClockwork/LearnPy | /Py3Lessons/python_ex05.py | 1,597 | 4.125 | 4 | name = 'Janus Clockwork' #according to my computer lol
age = 26
height = 65 #inches. Also, why is height spelled like that. I before E except after C? My ass.
weight = 114 #lbs. also I AM GROWIIINNNG
eyes = 'gray' #'Murrican spelling
teeth = 'messed up'
hair = 'brown'
favePet = 'cats'
faveAnime = 'Yowamushi Pedal'
faveBand = 'Radioactive Chicken Heads'
print ("Let's talk about %s." % name)
print ("She's %d inches tall." % height)
print ("That's %d centimeters." % (height * 2.54))
print ("She's %d pounds and still gets knocked over by the wind." % weight)
print ("It's true. That really happened before.")
print ("She's got %s eyes and %s hair." % (eyes, hair))
print ("Her teeth are %s and she drinks too much coffee." % teeth)
print ("%s's favorite pets are %s." % (name, favePet))
print ("Her favorite anime is %r and favorite band is %r." % (faveAnime, faveBand))
#according to the book, this line is tricky... CHALLENGE ACCEPTED
print ("If I add %d, %d, and %d I get %d." % (age, height, weight, age + height + weight))
#for some reason when I place "%r like that, it adds a space and some single quotes... I wonder why.
#oh, it's cuz %r adds those single quotes. Like, it's meant to place quotes.
#oohh okay:
#s – strings
#d – decimal integers (base-10)
#f – floating point display
#c – character
#b – binary
#o – octal
#x – hexadecimal with lowercase letters after 9
#X – hexadecimal with uppercase letters after 9
#e – exponent notation
#and I'm gonna guess r - literal translation with single quotes
#also Python doesn't belive in comment blocks. Why. Y U liek dis. | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.