blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
15c852d2d567f3334eb8c3dea00bf41cc1fa38e8
|
Zantosko/digitalcrafts-03-2021
|
/week_1/day5/fibonacci_sequence.py
| 755
| 4.34375
| 4
|
# Fibonacci Sequence
sequence_up_to = int(input("Enter number > "))
# Inital values of the Fibacci Sequence
num1, num2 = 0, 1
# Sets intial count at 0
count = 0
if sequence_up_to <= 0:
print("Error endter positive numbers or greater than 0")
elif sequence_up_to == 1:
print(f"fib sequence for {sequence_up_to}")
print(sequence_up_to)
else:
# Iterates continously until counter is greater than the number that the user inputs
while count < sequence_up_to:
print(num1)
# Holds sum of initial values
added_nums = num1 + num2
# Reassign second value to first value
num1 = num2
# Reassign first value to second value
num2 = added_nums
# Increment counter
count += 1
| true
|
fb9f602648821d0c95ceaa030e7b358d58f2c68f
|
sergey-igoshin/pythone_start_dz2
|
/task_2_3.py
| 975
| 4.375
| 4
|
"""
Пользователь вводит месяц в виде целого числа от 1 до 12. Сообщить, к какому времени года относится месяц
(зима, весна, лето, осень). Напишите решения через list и dict.
"""
seasons_list = ['зима', 'весна', 'лето', 'осень']
seasons_dict = {0: 'зима', 1: 'весна', 2: 'лето', 3: 'осень'}
month = int(input("Введите месяц в виде целого числа от 1 до 12: "))
if 1 <= month <= 2 or month == 12:
print(seasons_dict.get(0))
print(seasons_list[0])
elif 3 <= month <= 5:
print(seasons_dict.get(1))
print(seasons_list[1])
elif 6 <= month <= 8:
print(seasons_dict.get(2))
print(seasons_list[2])
elif 9 <= month <= 11:
print(seasons_dict.get(3))
print(seasons_list[3])
else:
print("Такого месяца не существует")
| false
|
e6e3fb65e165ec1b9e9f584539499c22d545d2f2
|
nelsonje/nltk-hadoop
|
/word_freq_map.py
| 628
| 4.21875
| 4
|
#!/usr/bin/env python
from __future__ import print_function
import sys
def map_word_frequency(input=sys.stdin, output=sys.stdout):
"""
(file_name) (file_contents) --> (word file_name) (1)
maps file contents to words for use in a word count reducer. For each
word in the document, a new key-value pair is emitted with a value of 1.
"""
template = '{} {}\t{}'
for line in input:
file_name, words = line.strip().split('\t')
for word in words.strip().split():
print(template.format(word, file_name, 1), file=output)
if __name__ == '__main__':
map_word_frequency()
| true
|
3ff26ff968410c3f06031903aa2035a1f5e33105
|
ebrandiao/fundamentos_de_python_TP1
|
/calculo_fatorial.py
| 837
| 4.3125
| 4
|
"""3. Escreva uma função em Python que calcule o fatorial de um dado número N usando um for.
O fatorial de N=0 é um. O fatorial de N é (para N > 0): N x (N-1) x (N-2) x … x 3 x 2 x 1.
Por exemplo, para N=5 o fatorial é: 5 x 4 x 3 x 2 x 1 = 120.
Se N for negativo, exiba uma mensagem indicando que não é possível calcular seu fatorial.
"""
def calculo_fatorial():
print("Esse programa calcula fatorial de um número fornecido pelo usuário!!")
num = int(input("Informe um número para calcular a fatorial dele: "))
fatorial = 1
for i in range(num):
if num <= 0:
print("Não é possível calular seu fatorial")
else:
fatorial = num * (num - 1)
print(f"O fatorial do número {num} x {num-1} é: {fatorial}")
calculo_fatorial()
| false
|
29d58758c33b74d57e58aed9c8f84b8c157415da
|
alison99/python
|
/function.py
| 358
| 4.25
| 4
|
def print_multiples(n):
i=1
output=""
while i <= 6:
output += str(n*i) + "\t"
i += 1
print(output)
#function called print_multiples
#while loop looks similar
#printing happens here IN the function
#print_multiples(3)
def print_square():
return [n**2 for n in range(10)]
#for n in range(10): print n
print print_square()
| false
|
011f04127eee015c03781e4e720188933b55c993
|
Zurubabel/Python
|
/Aula8_TrabalhandoComVetores.py
| 555
| 4.34375
| 4
|
# Aula 8 - Trabalhando com arrays
# Cachaça, coxinha, isqueiro, cigarro, ficha da sinuca (produtos)
produtos = ["Cachaça", "Coxinha", "Isqueiro", "Cigarro", "Ficha da Sinuca"]
# Endereçamento
# produtos[0] = "Pingado"
# produtos[5] = "Pingado"
# Funções
# append - Insiro um elemento no final do vetor
# produtos.append("Pingado")
# produtos.remove(produtos[0]) Remove o elemento do vetor
# produtos.pop(0) - Retorna o valor do index e remove tal elemento do vetor
# bebida = produtos[0]
bebida = produtos.pop(0)
print(bebida)
print(produtos)
| false
|
c7c27bb22d9516753f2e10af5f119b245fe9948f
|
jamesfallon99/CA117
|
/week03/numcomps_031.py
| 1,150
| 4.15625
| 4
|
#!/usr/bin/env python3
import sys
def three(N):
return [n for n in range(1, N + 1) if n % 3 == 0]
def squares(N):
return[n ** 2 for n in range(1, N + 1) if n % 3 == 0]
def double(N):
return[n * 2 for n in range(1, N + 1) if n % 4 == 0]
def three_or_four(N):
return[n for n in range(1, N + 1) if n % 3 == 0 or n % 4 == 0]
def three_and_four(N):
return[n for n in range(1, N + 1) if n % 3 == 0 and n % 4 == 0]
def replaced(N):
return["X" if n % 3 == 0 else n for n in range(1, N + 1)]
def prime(N):
return[n for n in range(1, N + 1) if n == 2 or n == 3 or n == 5 or n == 7 or (n > 1 and n % 2 != 0 and n % 3 != 0 and n % 5 != 0 and n % 7 != 0)]
def main():
N = int(sys.argv[1])
print("Multiples of 3: {}".format(three(N)))
print("Multiples of 3 squared: {}".format(squares(N)))
print("Multiples of 4 doubled: {}".format(double(N)))
print("Multiples of 3 or 4: {}".format(three_or_four(N)))
print("Multiples of 3 and 4: {}".format(three_and_four(N)))
print("Multiples of 3 replaced: {}".format(replaced(N)))
print("Primes: {}".format(prime(N)))
if __name__ == '__main__':
main()
| false
|
b8eb07e732f80f4303e5020aecb26f7711e93d1d
|
PederBG/sorting_algorithms
|
/InsertionSort.py
| 510
| 4.25
| 4
|
""" Sorting the list by iterating upwards and moving each element back in the list until it's sorted with respect on
the elements that comes before.
RUNTIME: Best: Ω(n), Average: Θ(n^2), Worst: O(n^2) """
def InsertionSort(A):
for i in range(1, len(A)):
key = A[i]
j = i - 1
while j > -1 and A[j] > key:
A[j + 1] = A[j]
j = j - 1
A[j + 1] = key
# ---------------------------------------
"""
l = [4, 3, 2, 6, 1]
InsertionSort(l)
print(l)
"""
| true
|
04715d6ba832e058a54c07f454e90218cb1c4650
|
quynhanh299/abcd
|
/baiconrua.py
| 324
| 4.21875
| 4
|
# from turtle import*
# shape("turtle")
# for i in range (3):
# forward(200)
# left(90)
# forward(200)
# left(90)
# forward(200)
# left(90)
# forward(200)
# left(90)
# mainloop()
# # bai tap ve 9 hinh tron
from turtle import*
shape("turtle")
for i in range (9):
circle(40)
right(40)
| false
|
708c3f290a705b46dc828a704a3d4e2a431fee51
|
zadadam/algorithms-python
|
/sort/bubble.py
| 1,066
| 4.125
| 4
|
import unittest
def bubble_sort(list):
"""Sort list using Bubble Sort algorithm
Arguments:
list {integer} -- Unsorted list
Returns:
list {integer} -- Sorted list
"""
swap=True
test ="It is a bad code";
while swap:
swap = False
for n in range(len(list) - 1 ):
if list[n] > list[n+1]:
current = list[n]
list[n] = list[n + 1]
list[n + 1] = current
swap = True
return list
class TestBubbleSort(unittest.TestCase):
def test_sort(self):
self.assertListEqual(bubble_sort([1, 1]), [1, 1])
self.assertListEqual(bubble_sort([1, 2]), [1, 2])
self.assertListEqual(bubble_sort([1, 2]), [1, 2])
self.assertListEqual(bubble_sort([2, 1]), [1, 2])
self.assertListEqual(bubble_sort([6, 3, 9, 1, 43]), [1, 3, 6, 9, 43])
self.assertListEqual(bubble_sort([14, 46, 43, 27, 57, 41, 45, 21, 70]), [14, 21, 27, 41, 43, 45, 46, 57, 70])
if __name__ == '__main__':
unittest.main()
| true
|
109ec4c8b4316cc46479ab9cfe93f2fe7a9f817d
|
vishul/Python-Basics
|
/openfile.py
| 500
| 4.53125
| 5
|
# this program opens a file and prints its content on terminal.
#files name is entered as a command line argument to the program.
#this line is needed so we can use command line arguments in our program.
from sys import argv
#the first command line argument i.e program call is saved in name and the
#second CLA is stored in filename this is the name of the file to be opened
name,filename=argv
txt=open(filename)
#everything inside the file is printed on the terminal.
print txt.read()
txt.close()
| true
|
2e3924cd0819ea47b3d5081e4d24647a31ea19fa
|
bsextion/CodingPractice_Py
|
/MS/Fast Slow Pointer/rearrange_linkedlist.py
| 1,332
| 4.15625
| 4
|
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def print_list(self):
temp = self
while temp is not None:
print(str(temp.value) + " ", end='')
temp = temp.next
print()
def reorder(head):
middle = find_middle(head)
reversed_middle = reverse_middle(middle)
ptr_head = head
head = head.next
while(head):
pass
#while reverse_middle
#temp to hold the next values: ptr_head.next
#ptr.head = middle
#ptr.head.next = temp
#reverse_middle = reverse_middle.next
#have a pointer pointing to the middle of the list
#reverse the second half of the linked list using recursion
#start from the begininng, place after node, move the node to the next
# TODO: Write your code here
return
def reverse_middle(head):
if head is None or head.next is None:
return head
p = reverse_middle(head.next)
head.next.next = head
head.next = None
return p
def find_middle(head):
slow_pointer = head
fast_pointer = head
while fast_pointer:
slow_pointer = slow_pointer.next
fast_pointer = fast_pointer.next.next
return slow_pointer
head = Node(2)
head.next = Node(4)
head.next.next = Node(6)
head.next.next.next = Node(8)
head.next.next.next.next = Node(10)
head.next.next.next.next.next = Node(12)
reorder(head)
| true
|
4c5761f987c88512f2b4f0a3240f71ae39f10101
|
bsextion/CodingPractice_Py
|
/Google/L1/challenge.py
| 1,215
| 4.34375
| 4
|
# Due to the nature of the space station's outer paneling, all of its solar panels must be squares.
# Fortunately, you have one very large and flat area of solar material, a pair of industrial-strength scissors,
# and enough MegaCorp Solar Tape(TM) to piece together any excess panel material into more squares.
# For example, if you had a total area of 12 square yards of solar material, you would be able to make one
# 3x3 square panel (with a total area of 9). That would leave 3 square yards, so you can turn those into
# three 1x1 square solar panels.
# Write a function solution(area) that takes as its input a single unit of measure representing the total
# area of solar panels you have (between 1 and 1000000 inclusive) and returns a list of the areas of the
# largest squares you could make out of those panels, starting with the largest squares first.
# So, following the example above, solution(12) would return [9, 1, 1, 1].
# highest square root that doesn't go over, remaining would then find the highest
def solution(area):
arr = []
while area > 0:
sqrtRound = int(area ** 0.5)
sqrtRound *= sqrtRound
arr.append(sqrtRound)
area -= sqrtRound
return arr
| true
|
8513c30cfd6b8fc19b6bd992e27bbd8e04160ad7
|
wandershow/Python
|
/ex059.py
| 1,237
| 4.21875
| 4
|
# crie um programa que leia dois numeros e mostre um menu na tela
#[1] somar
#[2] multiplicar
#[3] maior
#[4] novos numeros
#[5] sair do programa
#seu programa devera realizar a operação solicitada em cada caso
n1 = int(input('Digite o 1º numero: '))
n2 = int(input('Digite o 2º numero: '))
opcao = 0
while opcao != 5:
print('='*150)
print('''[1] somar
[2] multiplicar
[3] maior
[4] novos numeros
[5] sair do programa''')
print('=' * 150)
opcao = int(input('Escolha sua opção: '))
print('=' * 150)
if opcao == 1:
r = n1 + n2
print('A soma de {} + {} = {}'.format(n1, n2, r))
elif opcao == 2:
r = n1 * n2
print('A multiplicação de {} x {} é = {}'.format(n1, n2, r))
elif opcao == 3:
if n1 > n2:
print('{} é o maior'.format(n1))
elif n1 < n2:
print('{} é o maior'.format(n2))
else:
print('São iguais')
elif opcao == 4:
print('Digite novos numeros!')
n1 = int(input('Digite o 1º numero: '))
n2 = int(input('Digite o 2º numero: '))
elif opcao == 5:
print('SAINDO')
else:
print('Opção Invalida!! Tente novamente')
print('')
print('Você saiu!')
| false
|
314e30531c946c80ffbe95d6b5aa36eb93dbf972
|
wandershow/Python
|
/ex075.py
| 1,490
| 4.125
| 4
|
'''Desenvolva um programa que leia 4 valores do teclado e guarde os em uma tupla e mostre
quantas vezes apareceu o valor 9
Em que posição foi digitado o valor 3 pela primeira vez
Quais foram os numeros pares
'''
cont = 0
pos = 0
par = 0
numero = (int(input('Digite um numero: ')), int(input('Digite outro numero: ')), int(input('Digite mais um numero: ')),
int(input('Digite o ultimo numero: ')))
for c in range(0, len(numero)):
if numero[c] == 9:
cont += 1
if numero[c] == 3 and pos == 0:
pos = c + 1
if numero[c] % 2 == 0:
par += 1
print(f'Voce digitou os numeros {numero}')
if cont == 0:
print('o valor 9 nao apareceu nenhuma vez')
else:
print(f'o valor 9 apareceu {cont} vezes')
if pos > 0:
print(f'o valor 3 apareceu na {pos}º posição')
else:
print('o valor 3 não apareceu nenhuma vez')
if par > 0:
print(f'Tem {par} numeros par')
else:
print('Não tem nenhum numero par...')
'''Soluçao guanabara'''
numero = (int(input('Digite um numero: ')), int(input('Digite outro numero: ')), int(input('Digite mais um numero: ')),
int(input('Digite o ultimo numero: ')))
print(f'Voce digitou os numeros {numero}')
print(f'o valor 9 apareceu {numero.count(9)} vezes')
if 3 in numero:
print(f'o valor 3 apareceu na {numero.index(3)+1}º posição')
else:
print('o valor 3 foi digitado nenhuma vez')
print('Os valores pares digitados foram ', end='')
for n in numero:
if n % 2 == 0:
print(n, end=' ')
| false
|
31f6f4032e451f0e784c6c4a7ce5d7a6090bd438
|
Lalesh-code/PythonLearn
|
/String Operation.py
| 1,739
| 4.15625
| 4
|
name = 'Lalesh'
print(name)
name = "Garud"
print(name)
name = str("Welcome")
print(name)
#id function to get the memory location ID:
name1="welcome"
name2="python"
print(id(name1)) # 16157312
print(id(name2)) # 16157376
name3 = name2 + "my area"
print(id(name3)) # 15764880
# Operations on Strings: + for addition and * for multiply
str1 = "Welcome"
print(str1+" to Python") # Welcome to Python
str2 = 'Welcome'
print(str2*3) # WelcomeWelcomeWelcome
# Slicing or Indexing String operator:
str1 = "Welcome" # 0,1,2,3,4,5,6 - Welcome
print(str1[1:5]) # elco
print(str1[0:5]) # Welco
print(str1[:6]) # Welcom
print(str1[4:]) # ome
# ord(), chr(), len(), max(), min(), in and not in functions:
print(ord ('Z')) # A = 65, Z = 90
print(chr (65)) # 90 = Z, 65 = A
print(len(str1)) # 7
print(max(str1)) # o
print(min(str1)) # W
str2 = "Python"
print("com" in str2) # false
print("thon" in str2) # true
print("com" not in str2) # true
print("thon" not in str2) # false
# Compare Strings: (>,<,<=, >=, ==, !=)
print("tim" == "tie") # false
print("free" != "freedom") # true
print("man" >= "can") # true
print("son" <= "moon") # false
print("arrow" > "borrow") # false
print("teeth" < "tee") # false
print("abc" > "") # true
# Iterating strings:
str = "Python"
for i in str:
print(str) # Python displayed 6 times as per 6 Python characters
print(i) # P y t h o n - 6 characters displayed
s= "Welcome to python"
print(s.isalnum()) # false
print("Welcome".isalpha()) # true
print("2020".isdigit()) # true
print(s.islower()) # false
print("WELCOME".isupper()) # true
print(s.endswith("thon")) # true
print(s.startswith("ome")) # false
print(s.find("thon")) #13
print(s.rfind("come")) #3
print(s.count("o")) #3
| false
|
a32fa47fe2f8e571a862e53e89d76ab67efebc21
|
Lalesh-code/PythonLearn
|
/Oops_Encapsulation.py
| 1,484
| 4.4375
| 4
|
# Encapsulation: this restrict the access to methods and variables. This can prevent the data from being get modified accidently or by security point of view. This is achived by using the private methods and variables.
# Private methods denoted by "__" sign.
# Public methods can be accessed from anywhere but Private methods is accessed only in their classes & methods.
class MyClass():
__a=100 # valiable a is defined here as private denoted as '__'
def display(self):
print(self.__a) # passed here the same __a variable private one.
obj=MyClass()
obj.display() # O/p = 100
# print(MyClass.__a) # __a private variable outsie of class cannot be accesed. AttributeError: type object 'MyClass' has no attribute '__a'
class MyClass():
def __display1(self): # Private Method
print("This is first display method")
def display2(self): # Public Method
print("This is second display method")
self.__display1()
obje=MyClass()
obje.display2() # only public method is accessed here. display1 private method cannot be.
# We can access private variables outside of class indiretly using methods:
class MyClass():
__empid=101 # Private variable
def getempid(self,eid):
self.__empid = eid # method to get the getempid.
def dispempid(self):
print(self.__empid) # method to get the dispempid.
obj=MyClass()
obj.getempid(105) # 105
obj.dispempid() # 101
| true
|
b9104f7316d95eaa733bbbd4926726472855046e
|
emma-rose22/practice_problems
|
/HR_arrays1.py
| 247
| 4.125
| 4
|
'''You are given a space separated list of nine integers. Your task is to convert this list into a 3x3 NumPy array.'''
import numpy as np
nums = input().split()
nums = [int(i) for i in nums]
nums = np.array(nums)
nums.shape = (3, 3)
print(nums)
| true
|
33ba46d849eec7e9d1021641558606a24904b40a
|
qimanchen/Algorithm_Python
|
/python_interview_program/合并两个有序序列.py
| 779
| 4.1875
| 4
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
合并两个有序列表
"""
def recursion_merge_sort(l1, l2, tmp):
"""
:param l2: list
:param l1: list
:param tmp: sorted list
:return: list
"""
if len(l1) == 0 or len(l2) == 0:
tmp.extend(l1)
tmp.extend(l2)
return tmp
else:
if l1[0] < l2[0]:
tmp.append(l1[0])
del l1[0]
else:
tmp.append(l2[0])
del l2[0]
return recursion_merge_sort(l1, l2, tmp)
def _recursion_merge_sort(l1, l2):
"""
执行函数
"""
return recursion_merge_sort(l1, l2, [])
# 循环算法
def loop_merge_sort(l1, l2):
"""
"""
tmp = []
while len(l1) > 0 and len(l2) > 0:
if l1[0] < l2[0]:
tmp.append(l1[0])
del l1[0]
else:
tmp.append(l2[0])
del l2[0]
tmp.extend(l1)
tmp.extend(l2)
return tmp
| false
|
4239aaee9e02cf22c29b61d6e60efabf702abcb5
|
asiapiorko/Introduction-to-Computer-Science-and-Programming-Using-Python
|
/Unit 1 Exercise 1.py
| 1,616
| 4.1875
| 4
|
"""
In this problem you'll be given a chance to practice writing some for loops.
1. Convert the following code into code that uses a for loop.
prints 2
prints 4
prints 6
prints 8
prints 10
prints Goodbye!
"""
# First soultion
for count in range(2,11,2):
print(count)
print("Goodbye!")
# First solution improved
newlist = print([count for count in range(2,11,2)])
print("Goodbye!")
# Second soultion
for count in range(10):
if count != 0 and count % 2 == 0:
print(count)
print("Goodbye!")
# Second solution - improvement
newlist = [count for count in range(10) if count != 0 and count % 2 == 0 ]
print(newlist)
print("Goodbye!")
"""
2. Convert the following code into code that uses a for loop.
prints Hello!
prints 10
prints 8
prints 6
prints 4
prints 2
"""
# First solution
print("Hello!")
for count in range(10,0,-2):
print(count)
# First solution improvement
print("Hello!")
newlist = [count for count in range(10,0,-2)]
print(newlist)
"""
3. Write a for loop that sums the values 1 through end, inclusive. end is a variable that we define for you. So, for example, if we define end to be 6, your code should print out the result:
21
which is 1 + 2 + 3 + 4 + 5 + 6.
"""
# First solution
def sum_values():
number = int(input("Define a number: "))
end = 0
for number in range(number+1):
end += number
return end
# Another solution
def sum_values(end):
total = end
for next in range(end):
total += next
return total
| true
|
84fce63f043d3b48c019739dce5d9a58df6c0198
|
arcstarusa/prime
|
/StartOutPy4/CH7 Lists and Tuples/drop_lowest_score/main.py
| 678
| 4.21875
| 4
|
# This program gets a series of test scores and
# calculates the average of the scores with the
# lowest score dropped. 7-12
def main():
# Get the test scores from the user.
scores = get_scores()
# Get the total of the test scores.
total = get_total(scores)
# Get the lowest test scores.
lowest = min(scores)
# Subtract the lowest score from the total.
total -= lowest
# Calculate the average. Note that we divide
# by 1 less that the number of scores because
# the lowest score was dropped.
average = total / (len(scores) -1)
# Display the average.
print('The average, with the lowest score dropped', 'is:', average)
| true
|
18c597902f1fa9e14de3506f2cce0d357af647b0
|
arcstarusa/prime
|
/StartOutPy4/CH12 Recursion/fibonacci.py
| 457
| 4.125
| 4
|
# This program uses recursion to print numbers from the Fibonacci series.
def main():
print('The first 10 numberss in the ')
print('Fibonacci series are:')
for number in range(1,11):
print(fib(number))
# The fib function returns returns the nth number
# in the Fibonacci series.
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n -1) + fib(n -2)
# Call the main function.
main()
| true
|
1684ed5ced8288e821c464db286a72f0c1098b0a
|
arcstarusa/prime
|
/StartOutPy4/CH8 Strings/validate_password.py
| 420
| 4.15625
| 4
|
# This program gets a password from the user and validates it. 8-7
import login1
def main():
# Get a password from the user.
password = input('Enter your password: ')
# Validate the password.
while not login1.valid_password(password):
print('That password is not valid.')
password = input('Enter your password: ')
print('That is valid password.')
# Call the main function.
main()
| true
|
46cba8a43cb65ece9a372e4c99c46b987d88dbd7
|
LesterAGarciaA97/OnlineCourses
|
/08. Coursera/01. Python for everybody/Module 1/Week 06/Code/4.6Functions.py
| 1,004
| 4.4375
| 4
|
#4.6 Write a program to prompt the user for hours and rate per hour using input to compute gross pay. Pay should be the normal rate for hours up to 40 and
#time-and-a-half for the hourly rate for all hours worked above 40 hours. Put the logic to do the computation of pay in a function called computepay() and use
#the function to do the computation. The function should return a value. Use 45 hours and a rate of 10.50 per hour to test the program (the pay should be 498.75).
#You should use input to read a string and float() to convert the string to a number. Do not worry about error checking the user input unless you want to - you
#can assume the user types numbers properly. Do not name your variable sum or use the sum() function.
def computepay(h,r):
if h > 40:
p = 1.5 * r * (h - 40) + (40 *r)
else:
p = h * r
return p
hrs = input("Enter Hours:")
hr = float(hrs)
rphrs = input("Enter rate per hour:")
rphr = float(rphrs)
p = computepay(hr,rphr)
print("Pay",p)
| true
|
b40fd2dab0c7eebf9690850182ef28e0e4da062a
|
rishabhshellac/Sorting
|
/bubblesort.py
| 585
| 4.3125
| 4
|
# Bubble Sort
"""Comparing current element with adjacent element
Repeatedly swapping the adjacent elements if they are in wrong order."""
def bubblesort(arr):
for i in range(len(arr)):
for j in range(len(arr)-1):
if(arr[j] > arr[j+1]):
temp = arr[j]
arr[j] = arr[j+1]
arr[j+1] = temp
for i in range(len(arr)):
print(arr[i], end=" ")
print()
arr = [5, 1, 4, 2, 8]
bubblesort(arr)
print("Sorted List: ")
for i in range(len(arr)):
print(arr[i], end=" ")
| false
|
f8662d63b37d01fbbd154eb27cac1ec4efada389
|
luckeyRook/python_study
|
/応用編/32.最小値・最大値の取得/TEST32.py
| 1,241
| 4.21875
| 4
|
#32.最小値・最大値の取得
#min
print(min([10,20,30,5,3]))
print(min('Z','A','J','w'))
#max
print(max([10,20,30,5,3]))
print(max('Z','A','J','w'))
#key引数
def key_func(n):
return int(n)
l=[2,3,4,'111']
print(min(l,key=key_func))
print(max(l,key=key_func))
print('========================================-')
def key_func2(n):
return str(n)
l=[2,3,4,'111']
print(min(l,key=key_func2))
print(max(l,key=key_func2))
print('========================================-')
l=[2,3,4,'111']
print(min(l,key=int))
print(max(l,key=int))
print(min(l,key=str))
print(max(l,key=str))
print('========================================-')
def key_func3(n):
return n[2]
#code/name/score
l=[(1,'pyhton',100),(2,'ruby',80),(3,'Perl',40)]
print(min(l,key=key_func3))
print(max(l,key=key_func3))
#クラスで行う場合
def key_func4(n):
return n.score
class TestClass:
def __init__(self,code,name,score):
self.code=code
self.name=name
self.score=score
def __str__(self):
return '({},{},{})'.format(self.code,self.name,self.score)
l=[
TestClass(1,'pyhton',100),
TestClass(2,'ruby',80),
TestClass(3,'Perl',40)
]
print(min(l,key=key_func4))
print(max(l,key=key_func4))
| false
|
0a4c4d4a80d0bd67456336c3e81b9259cac4bb4d
|
luckeyRook/python_study
|
/応用編/28.内包表記/TEST28.py
| 1,407
| 4.1875
| 4
|
#28.内包表記
#リストの内包表記
comp_list=[i for i in range(10)]
print(comp_list)
#以下のコードと同じ
comp_list=[]
for i in range(10):
comp_list.append(i)
print(comp_list)
#本来は3行必要な処理を一行にできる
comp_list=[str(i*i) for i in range(10)]
print(comp_list)
print('=================================')
#ディクショナリの内包表記
comp_dict={str(i):i*i for i in range(10)}
print(comp_dict)
#以下のコードと同じ
comp_dict={}
for i in range(10):
comp_dict[str(i)]=i*i
print(comp_dict)
print('=================================')
#セットの内包表記
comp_set={str(i*i) for i in range(10)}
print(comp_set)
#以下のコードと同じ
comp_set=set()
for i in range(10):
comp_set.add(str(i*i))
print(comp_set)
print('=================================')
#forのネスト
comp_list_1=[i *ii for i in range(1,10) for ii in range(1,10)]
print(comp_list_1)
#以下のコードと同じ
comp_list_1=[]
for i in range(1,10):
for ii in range(1,10):
comp_list_1.append(i*ii)
print(comp_list_1)
print('=================================')
#ifとの併用
comp_list_2=[i for i in range(10) if i % 2 ==1 ]
print(comp_list_2)
#以下のコードと同じ
comp_list_2=[]
for i in range(10):
if i %2 == 1:
comp_list_2.append(i)
print(comp_list_2)
#タプルの内包表記
gen=(i for i in range(10))
print(gen)
| false
|
6cb09e7a8ff19cabb2a5b2218c1fbf3b994ffa5e
|
Kilatsat/deckr
|
/webapp/engine/card_set.py
| 2,455
| 4.125
| 4
|
"""
This module contains the CardSet class.
"""
from engine.card import Card
def create_card_from_dict(card_def):
"""
This is a simple function that will make a card from a dictionary of
attributes.
"""
card = Card()
for attribute in card_def:
setattr(card, attribute, card_def[attribute])
return card
class CardSet(object):
"""
A card set is simply a set of cards. This could be anything from
52 playing cards to every magic card created. These can be loaded
from a configuration file or defined via python.
"""
def __init__(self):
self.cards = {}
def load_from_list(self, card_list):
"""
This function takes in a list of dicts and uses that to create the card
set. If any card definition in the list does not have a name, it will be
considered an invalid card definition and will not be included in the
card set. This will add to anything that is currently in the card set.
A card added to the card set will overwrite any card already in the card
set with the same name.
"""
for card_def in card_list:
card_name = card_def.get('name', None)
if card_name is not None:
self.cards[card_name] = card_def
def all_cards(self):
"""
Return a list of all the cards for this card set.
"""
return self.cards.values()
def create(self, card_name, number=1):
"""
Create an instance of the card with card_name. If number == 1 then this
will return a single instance. Otherwise this returns a list of cards
each of which is a copy of the card_name. If there is no card with
card_name in the card set, then an error will be thrown.
"""
card_name = self.cards.get(card_name, None)
if card_name is None:
raise ValueError("Unable to get card {0}".format(card_name))
if number == 1:
return create_card_from_dict(card_name)
elif number > 1:
return [create_card_from_dict(card_name) for _ in range(number)]
else:
return []
def create_set(self):
"""
Create a single instance of every card in this set. This will return a
list which contains a Card object for every card in this set.
"""
return [create_card_from_dict(self.cards[x]) for x in self.cards]
| true
|
965f4117268913264e21e1924052bbb50c95712d
|
junawaneshivani/Python
|
/ML with Python/numpy_crash_course.py
| 1,139
| 4.25
| 4
|
import numpy as np
# define an 1d array
my_list_1 = [1, 2, 3]
my_array_1 = np.array(my_list_1)
print(my_array_1, my_array_1.shape)
# define a 2d array
my_list_2 = [[1, 2, 3], [4, 5, 6]]
my_array_2 = np.array(my_list_2)
print(my_array_2, my_array_2.shape)
print("First row: {}".format(my_array_2[0]))
print("Last row: {}".format(my_array_2[-1]))
print("Specific row and col: {}".format(my_array_2[0, 2]))
print("Whole col: {}".format(my_array_2[:, 2]))
# Arithmetic
print("Addition: {}".format(my_array_1 + my_array_2))
print("Subtraction: {}".format(my_array_1 - my_array_2))
print("Multiplication: {}".format(my_array_1 * my_array_2))
print("Division: {}".format(my_array_1 / my_array_2))
# Snippet from Machine learning mastery with python book
'''
It is a great idea to become familiar with the broader SciPy ecosystem and for that I would
recommend the SciPy Lecture Notes listed below. I think the NumPy documentation is excellent
(and deep) but you probably don't need it unless you are doing something exotic.
SciPy Lecture Notes.
http://www.scipy-lectures.org/
NumPy User Guide.
http://docs.scipy.org/doc/numpy/user/
'''
| false
|
b1b68e288109b0b05c8b8f2217f7e95a6f744e34
|
luola63702168/leetcode
|
/primary_algorithm/r_07_design_problem/rusi_01_shuffle_array.py
| 1,308
| 4.125
| 4
|
import copy
import random
# 打乱一个没有重复元素的数组。
#
# 示例:
#
# // 以数字集合 1, 2 和 3 初始化数组。
# int[] nums = {1,2,3};
# Solution solution = new Solution(nums);
# // 打乱数组 [1,2,3] 并返回结果。任何 [1,2,3]的排列返回的概率应该相同。
# solution.shuffle();
# // 重设数组到它的初始状态[1,2,3]。
# solution.reset();
# // 随机返回数组[1,2,3]打乱后的结果。
# solution.shuffle();
class Solution:
def __init__(self, nums):
self.nums = nums
self.reset_nums = copy.deepcopy(nums)
def reset(self):
"""
Resets the array to its original configuration and return it.
"""
return self.reset_nums
def shuffle(self):
"""
Returns a random shuffling of the array.
"""
length = len(self.nums)
for i in range(length):
index = random.randint(0, length - 1)
self.nums[i], self.nums[index] = self.nums[index], self.nums[i]
return self.nums
# Your Solution object will be instantiated and called as such:
nums = [1, 2, 3]
obj = Solution(nums)
param_1 = obj.reset()
print(param_1)
param_2 = obj.shuffle()
print(param_2)
# reversed() 反转函数
| false
|
22811f3d9c3624b15dc27517c1b8a98e652e3f3e
|
luola63702168/leetcode
|
/primary_algorithm/r_02_str/ll_02_整数反转.py
| 739
| 4.28125
| 4
|
def reverse(x):
str_ = str(x)
if x == 0:
return 0
elif x > 0:
x = int(str_[::-1])
else:
x = int('-' + str_[::-1].rstrip("-").rstrip("0"))
if -2 ** 31 < x < 2 ** 31 - 1:
return x
return 0
# str_= str(x)
# if x == 0 or x <= -2 ** 31 or x >= 2 ** 31-1 :
# return 0
# elif x > 0:
# if not str_.endswith("0"):
# return int(str_[::-1])
# else:
# return int(str_[::-1])
# else:
# return int('-' + str_[::-1].rstrip("-").rstrip("0"))
if __name__ == '__main__':
print(reverse(-123))
print(reverse(123))
print(reverse(120))
print(reverse(0))
print(reverse(-10))
| false
|
9f0a9465e1d2f2328088cc53093a61101005a17c
|
CaseyTM/day1Python
|
/tuples.py
| 1,320
| 4.34375
| 4
|
# arrays (lists) are mutable (changeable) but what if you do not want them to be so, enter a tuple, a constant array (list)
a_tuple = (1,3,8)
print a_tuple;
# can loop through them and treat them the same as a list in most cases
for number in a_tuple:
print number;
teams = ('falcons', 'hawks', 'atl_united', 'silverbacks');
for team in teams:
if team == 'hawks':
print 'Go Hawks!';
else:
print "It's basketball season";
team_a = 'falcons';
print team_a == 'falcons';
# comparison operators have same syntax as JS
team_b = 'braves';
condition_1 = team_a == 'falcons';
condition_2 = team_b == 'braves';
if condition_1 and condition_2:
print 'Hooray';
# python's version of indexOf is "in"
print 'hawks' in teams
if team == 'hawks':
print 'go hawks';
elif team == 'falcons':
print 'sad superbowl';
if 'hawks' in teams:
print 'go hawks';
if 'falcons in teams':
print 'go falcons';
# message = input("please enter your name");
height = raw_input("in inches, how tall are you?\n");
if(int(height) >= 42):
print "you are tall enough to go on the batman rollercoaster";
else:
print "maybe try the kiddie coaster";
current = 1;
# while (current < 10):
# print current;
# current += 1;
answer = "play"
while answer != "quit":
answer = raw_input("say quit to stop the game\n");
| true
|
921432c5dd48fa4ebfb7172bbafaaaefbd56bc8a
|
tingjianlau/my-leetcode
|
/88_merge_sorted_array/88_merge_sorted_array.py
| 1,592
| 4.1875
| 4
|
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
##########################################################################
# > File Name: 88_merge_sorted_array.py
# > Author: Tingjian Lau
# > Mail: tjliu@mail.ustc.edu.cn
# > Created Time: 2016/05/31
#########################################################################
class Solution(object):
# Runtime: 60 ms
def merge_1(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
p, q, idx = m - 1, n - 1, m + n - 1
while p >= 0 and q >= 0:
if nums1[p] > nums2[q]:
nums1[idx] = nums1[p]
p -= 1
else:
nums1[idx] = nums2[q]
q -= 1
idx -= 1
while q >= 0:
nums1[idx] = nums2[q]
idx -= 1
q -= 1
# 方法1的简略写法
# Runtime: 68 ms
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
while m > 0 and n > 0:
if nums1[m-1] > nums2[n-1]:
nums1[m + n - 1] = nums1[m-1]
m -= 1
else:
nums1[m + n - 1] = nums2[n-1]
n -= 1
if n>0:
nums1[:n] = nums2[:n]
| false
|
864b676fbc74522541658bec2bc88d3af97b4598
|
csojinb/6.001_psets
|
/ps1.3.py
| 1,208
| 4.3125
| 4
|
import math
STARTING_BALANCE = float(raw_input('Please give the starting balance: '))
INTEREST_RATE = float(raw_input('Please give the annual interest'
'rate (decimal): '))
MONTHLY_INTEREST_RATE = INTEREST_RATE/12
balance = STARTING_BALANCE
monthly_payment_lower_bound = STARTING_BALANCE/12
monthly_payment_upper_bound = (STARTING_BALANCE *
(1 + MONTHLY_INTEREST_RATE)**12)/12
while (monthly_payment_upper_bound - monthly_payment_lower_bound) > 0.01 \
or balance > 0:
monthly_payment = (monthly_payment_lower_bound +
monthly_payment_upper_bound)/2
balance = STARTING_BALANCE
for month in range(1,13):
interest = balance * MONTHLY_INTEREST_RATE
balance += interest - round(monthly_payment,2)
balance = round(balance,2)
if balance < 0:
break
if balance > 0:
monthly_payment_lower_bound = monthly_payment
else:
monthly_payment_upper_bound = monthly_payment
print 'Monthly payment to pay off debt in 1 year:', round(monthly_payment,2)
print 'Number of months needed: ', month
print 'Balance: ', balance
| true
|
ccb1ec3d8b7974b3ad05c38924c2856d2c5f01db
|
edenuis/Python
|
/Sorting Algorithms/mergeSortWithO(n)ExtraSpace.py
| 1,080
| 4.15625
| 4
|
#Merge sort
from math import ceil
def merge(numbers_1, numbers_2):
ptr_1 = 0
ptr_2 = 0
numbers = []
while ptr_1 < len(numbers_1) and ptr_2 < len(numbers_2):
if numbers_1[ptr_1] <= numbers_2[ptr_2]:
numbers.append(numbers_1[ptr_1])
ptr_1 += 1
else:
numbers.append(numbers_2[ptr_2])
ptr_2 += 1
if ptr_1 < len(numbers_1):
return numbers + numbers_1[ptr_1:]
elif ptr_2 < len(numbers_2):
return numbers + numbers_2[ptr_2:]
return numbers
def mergeSort(numbers):
if len(numbers) <= 1:
return numbers
size = ceil(len(numbers)/2)
numbers_1 = mergeSort(numbers[:size])
numbers_2 = mergeSort(numbers[size:])
numbers = merge(numbers_1, numbers_2)
return numbers
if __name__ == "__main__":
assert mergeSort([1,2,3,4,5]) == [1,2,3,4,5]
assert mergeSort([5,4,3,2,1]) == [1,2,3,4,5]
assert mergeSort([5,2,3,4,4,2,1]) == [1,2,2,3,4,4,5]
assert mergeSort([]) == []
assert mergeSort([-1,23,0,123,5,6,4,-12]) == [-12,-1,0,4,5,6,23,123]
| true
|
64fe2ed64c6fe5c801e88f8c1e266538f7d51d40
|
brodieberger/Control-Statements
|
/(H) Selection statement that breaks loops.py
| 345
| 4.25
| 4
|
x = input("Enter string: ")
#prompts the user to enter a string
y = input("Enter letter to break: ")
#Letter that will break the loop
for letter in x:
if letter == y:
break
print ('Current Letter:', letter)
#prints the string letter by letter until it reaches the letter that breaks the loop.
input ("Press Enter to Exit")
| true
|
0af5be1b677b7d0734e0bc071f03f74007bb960a
|
Chil625/FlaskPractice
|
/lec1/if_statements.py
| 1,039
| 4.15625
| 4
|
# should_continue = True
# if should_continue == True:
# print("Hello")
#
# people_we_know = ["John", "Anna", "Mary"]
# person = input("Enter the person you know: ")
#
# if person in people_we_know:
# print("You know {}!".format(person))
# else:
# print("You don't know {}!".format(person))
def who_do_you_know():
people_str = input("Let me know names you know, separated by a comma: ")
people_you_know = people_str.split(",")
# people_you_know_without_space = []
# for person in people_you_know:
# people_you_know_without_space.append(person.strip())
people_you_know_without_space = [person.strip() for person in people_you_know]
return people_you_know_without_space
def ask_user(known_people):
person = input("Enter the person you know: ")
if person in known_people:
print("You know {}!".format(person))
else:
print("You don't know {}...".format(person))
# print(who_do_you_know())
known_people = who_do_you_know()
print(known_people)
ask_user(known_people)
| false
|
2fd02e4ef529c04cb315456e58c2533f94ed4df6
|
austBrink/Tutoring
|
/python/Maria/targetGame.py
| 1,608
| 4.375
| 4
|
# Hit the Target Game
# 02/11/23
# Maria Harrison
import turtle
# named constants
SCREEN_WIDTH = 600
SCREEN_HEIGHT = 600
TARGET_LLEFT_X = 100
TARGET_LLEFT_Y = 250
TARGET_WIDTH = 25
FORCE_FACTOR = 30
PROJECTILE_SPEED = 1
NORTH = 90
SOUTH = 270
EAST = 0
WEST = 180
# Setup the window
turtle.setup(SCREEN_WIDTH, SCREEN_HEIGHT)
# Draw the target
turtle.hideturtle()
turtle.speed(0)
turtle.penup()
turtle.goto(TARGET_LLEFT_X, TARGET_LLEFT_Y)
turtle.pendown()
turtle.setheading(EAST)
turtle.forward(TARGET_WIDTH)
turtle.setheading(NORTH)
turtle.forward(TARGET_WIDTH)
turtle.setheading(WEST)
turtle.forward(TARGET_WIDTH)
turtle.setheading(SOUTH)
turtle.forward(TARGET_WIDTH)
turtle.penup()
# Center the turtle
turtle.goto(0, 0)
turtle.setheading(EAST)
turtle.showturtle()
turtle.speed(PROJECTILE_SPEED)
# Get the angle and force from the user
angle = float(input("Enter the projectile's angle: "))
force = float(input("Enter the launch force (1−10): "))
# Calculate the distance
distance = force * FORCE_FACTOR
# Set the heading
turtle.setheading(angle)
# Launch the projectile
turtle.pendown()
turtle.forward(distance)
# Did it hit the target?
tx = turtle.xcor()
ty = turtle.ycor()
sideA = TARGET_LLEFT_X
sideB = TARGET_LLEFT_X + TARGET_WIDTH
bottom = TARGET_LLEFT_Y
top = bottom + TARGET_WIDTH
if (tx >= sideA and
tx <= sideB and
tx >= bottom and
tx<= top):
print('Target hit!')
else:
print('You missed the target.')
if(ty < bottom and tx < sideB):
print('Hint: not enough force')
elif(ty > top):
print('Hint: too much force')
else:
print('Hint: check your angle')
| false
|
ed767807eae30530f1d4e121217585aff3bcea75
|
austBrink/Tutoring
|
/python/Maria/makedb.py
| 2,370
| 4.34375
| 4
|
import sqlite3
def main():
# Connect to the database.
conn = sqlite3.connect('cities.db')
# Get a database cursor.
cur = conn.cursor()
# Add the Cities table.
add_cities_table(cur)
# Add rows to the Cities table.
add_cities(cur)
# Commit the changes.
conn.commit()
# Display the cities.
display_cities(cur)
# Close the connection.
conn.close()
# The add_cities_table adds the Cities table to the database.
def add_cities_table(cur):
# If the table already exists, drop it.
cur.execute('DROP TABLE IF EXISTS Cities')
# Create the table.
cur.execute('''CREATE TABLE Cities (CityID INTEGER PRIMARY KEY NOT NULL,
CityName TEXT,
Population REAL)''')
# The add_cities function adds 20 rows to the Cities table.
def add_cities(cur):
cities_pop = [(1,'Tokyo',38001000),
(2,'Delhi',25703168),
(3,'Shanghai',23740778),
(4,'Sao Paulo',21066245),
(5,'Mumbai',21042538),
(6,'Mexico City',20998543),
(7,'Beijing',20383994),
(8,'Osaka',20237645),
(9,'Cairo',18771769),
(10,'New York',18593220),
(11,'Dhaka',17598228),
(12,'Karachi',16617644),
(13,'Buenos Aires',15180176),
(14,'Kolkata',14864919),
(15,'Istanbul',14163989),
(16,'Chongqing',13331579),
(17,'Lagos',13122829),
(18,'Manila',12946263),
(19,'Rio de Janeiro',12902306),
(20,'Guangzhou',12458130)]
for row in cities_pop:
cur.execute('''INSERT INTO Cities (CityID, CityName, Population)
VALUES (?, ?, ?)''', (row[0], row[1], row[2]))
# The display_cities function displays the contents of
# the Cities table.
def display_cities(cur):
print('Contents of cities.db/Cities table:')
cur.execute('SELECT * FROM Cities')
results = cur.fetchall()
for row in results:
print(f'{row[0]:<3}{row[1]:20}{row[2]:,.0f}')
# Execute the main function.
if __name__ == '__main__':
main()
| true
|
7626635b10874cd45ef572540d1347eeff90a00e
|
austBrink/Tutoring
|
/python/Maria/databasereader.py
| 1,258
| 4.40625
| 4
|
import sqlite3
conn = sqlite3.connect('cities.db')
# city id, city name, population
namesByPop = conn.execute('''
SELECT CityName FROM Cities ORDER BY Population
''')
for row in namesByPop:
print ("ID = ", row[0])
print ("CITY NAME = ", row[1])
print ("POPULATION = ", row[2] )
namesByPopDesc = conn.execute('''
SELECT CityName FROM Cities ORDER BY Population DESC
''')
for row in namesByPopDesc:
print ("ID = ", row[0])
print ("CITY NAME = ", row[1])
print ("POPULATION = ", row[2] )
namesSortedByNames = conn.execute('''
SELECT CityName FROM Cities ORDER BY CityName
''')
for row in namesSortedByNames:
print ("CITY NAME = ", row[0])
totalPopulationOfCities = conn.execute('''
SELECT SUM(Population) as populationSum FROM Cities
''')
for row in totalPopulationOfCities:
print("POPULATION SUM = ", row[0])
averagePopulation = conn.execute('''
SELECT ( SUM(Population) / COUNT(Population) ) as populationAverage FROM Cities
''')
getMaxPopulationCity = conn.execute('''
SELECT CityName FROM Cities WHERE Population = (SELECT MAX(Population) FROM Cities)
''')
getMinPopulationCity = conn.execute('''
SELECT CityName FROM Cities WHERE Population = (SELECT MIN(Population) FROM Cities)
''')
| false
|
bf639aca06615e7a8d84d9322024c17873504c00
|
austBrink/Tutoring
|
/python/Sanmi/averageRainfall.py
| 1,362
| 4.5
| 4
|
# Write a program that uses ( nested loops ) to collect data and calculate the average rainfall over a period of two years. The outer loop will iterate once for each year. The inner loop will iterate twelve times, once for each month. Each iteration of the inner loop will ask the user for the inches of rainfall for that month. After all iterations, the program should display the number of months, the total inches of rainfall, and the average rainfall per month for the entire period.
# review loops
NUMBER_OF_YEARS = 2
NUMBER_OF_MONTHS_IN_YEAR = 12
# array / list
months = ["Jan","Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
# containers or a structure
totalRainFall = []
# run a loop for two years..
for i in range(0, NUMBER_OF_YEARS):
print(f'DATA FOR YEAR {i + 1}')
for j in range(0, NUMBER_OF_MONTHS_IN_YEAR):
print(f'Enter the inches of rainfall for {months[j]}')
tempRainfallAmount = float(input())
totalRainFall.insert(len(totalRainFall),tempRainfallAmount)
totalMonths = NUMBER_OF_YEARS * NUMBER_OF_MONTHS_IN_YEAR
print(f'TOTAL NUMBER OF MONTHS: {totalMonths}')
rainfallTotal = 0
for n in range(0,len(totalRainFall)):
rainfallTotal = rainfallTotal + totalRainFall[n]
print(f'THE TOTAL RAINFALL WAS {rainfallTotal}')
print(f'THE AVERAGE RAINFALL PER MONTH IS {rainfallTotal / totalMonths}')
| true
|
c25780c144bbff40242092fbbe961a3b5e72c8e4
|
roshan1966/ParsingTextandHTML
|
/count_tags.py
| 862
| 4.125
| 4
|
# Ask the user for file name
filename = input("Enter the name of a HTML File: ")
def analyze_file(filename):
try:
with open (filename, "r", encoding="utf8") as txt_file:
file_contents = txt_file.read()
except FileNotFoundError:
print ("Sorry, the file named '" + filename + "' was not found")
else:
tags = []
openings = file_contents.split('<')
for opening in openings:
if len(opening) > 1:
if opening[0] != '/':
opening = opening.split('>')[0]
opening = opening.split(' ')[0]
tags.append('<' + opening + '>')
print ("Number of tags: " + str(len(tags)))
for i in range(len(tags)):
print (str(i+1) + ". " + str(tags[i]))
analyze_file(filename)
| true
|
374c16f971fc2238848a91d94d43293c592e6f03
|
udaybhaskar8/git-project
|
/functions/ex4.py
| 322
| 4.125
| 4
|
import math
# Calculate the square root of 16 and stores it in the variable a
a =math.sqrt(16)
# Calculate 3 to the power of 5 and stores it in the variable b
b = 3**5
b=math.pow(3, 5)
# Calculate area of circle with radius = 3.0 by making use of the math.pi constant and store it in the variable c
c = math.pi * (3**2)
| true
|
0536bf4d5ab562112a5971e9b517da0513f460dc
|
QWJ77/Python
|
/StudyPython/Python-函数的值传递和引用传递.py
| 950
| 4.1875
| 4
|
'''
值传递:传递过来的是一个数据的副本,修改副本对原件没有任何影响
引用传递:传递过来的是一个变量的地址,通过地址可以操作同一份文件
注:在Python中,只有引用传递
但是,如果数据类型是可变类型,则可以改变原件
如果数据类型是不可变类型,则不可以改变原件
可变数据类型:列表list和字典dict;
不可变数据类型:整型int、浮点型float、字符串型string和元组tuple。
'''
# 如果数据类型是不可变类型,则不可以改变原件
# def change(num):
# print(id(num))
# num=666
# print(id(num))
#
# b=10
# print(id(b)) #b和num id相同,说明b把它所指内存的唯一表示传给了num
# change(b)
# print(b)
# 如果数据类型是可变类型,则可以改变原件
def change(num):
print(id(num))
num.append(666)
print(id(num))
b=[1,2,3]
print(id(b))
change(b)
print(b)
| false
|
ec3c637f34938d142797ed51f4184c807455335f
|
QWJ77/Python
|
/StudyPython/Python列表-常用操作-增加.py
| 894
| 4.34375
| 4
|
'''
append 往列表里追加一个新元素,只追加一个元素
注意:会直接修改原列表!!!
'''
# nums=[1,2,3,4,5]
# print(nums)
# print(nums.append(5))
# print(nums)
'''
insert(index,object) 插入到index的前面
它会改变列表本身!!!
'''
# nums=[1,2,3,4,5]
# print(nums)
# print(nums.insert(0,5))
# print(nums)
'''
extend 往列表中。扩展另一个可迭代序列,把可迭代元素分解成每一个元素添加到列表
它会改变列表本身!!!
'''
nums=[1,2,3,4,5]
nums2=["a","b","c"]
# nums2="abcdefg"
print(nums.extend(nums2))
print(nums)
'''
乘法运算
不会改变列表本身!!!
'''
# nums=[1,2]
# print(nums*3)
# print([num *3 for num in nums])
# print(nums)
'''
加法运算
只能连接链表到另一个列表,不能追加字符串,此处与extend不同
不会改变列表本身!!!
'''
# n1=[1,2,3]
# n2=["a","b"]
# print(n1+n2)
# print(n1)
| false
|
890ae7b46c38ee2c77ea8b7d574f5998573efb34
|
Tech-nransom/dataStructuresAndAlgorithms_Python
|
/bubbleSort.py
| 460
| 4.4375
| 4
|
def bubbleSort(array,ascending=True):
for i in range(len(array)):
for j in range(i,len(array)):
if ascending:
if array[i] > array[j]:
array[i],array[j] = array[j],array[i]
else:
if array[i] < array[j]:
array[i],array[j] = array[j],array[i]
return array
# 9 2 5 1 3 7
if __name__ == '__main__':
array = []
for number in input("Enter The Array:").split():
array.append(int(number))
print(bubbleSort(array,ascending=False))
| false
|
9affcfc38a322081ef4afeb658aa97ec03f871ab
|
mckennec2014/cti110
|
/P3HW1_ColorMix_ChristianMcKenney.py
| 975
| 4.28125
| 4
|
# CTI-110
# P3HW1 - Color Mixer
# Christian McKenney
# 3/17/2020
#Step-1 Enter the first primary color
#Step-2 Check if it's valid
#Step-3 Enter the second primary color
#Step-4 Check if it's valid
#Step-5 Check for combinations of colors and display that color
# Get user input
color1 = input('Enter the first primary color: ')
if color1 == "red" or color1 == "blue" or color1 == "yellow":
color2 = input('Enter the second primary color: ')
if color2 == "red" or color2 == "blue" or color2 == "yellow":
if color1 == "red" and color2 == "blue":
print('These colors make purple')
if color1 == "red" and color2 == "yellow":
print('These colors make orange')
if color1 == "blue" and color2 == "yellow":
print('These colors make green')
else:
print('Invalid input')
else:
print('Invalid input')
| true
|
7008005de70aadea1bebd51d8a068272c7f7b6af
|
mckennec2014/cti110
|
/P5HW2_MathQuiz _ChristianMcKenney.py
| 2,012
| 4.375
| 4
|
# This program calculates addition and subtraction with random numbers
# 4/30/2020
# CTI-110 P5HW2 - Math Quiz
# Christian McKenney
#Step-1 Define the main and initialize the loop variable
#Step-2 Ask the user to enter a number from the menu
#Step-3 If the user enters the number 1, add the random numbers and
# display the addition problem
#Step-4 If the user enters the number 2, subtract the random numbers and
# display the subtraction problem
#Step-5 If the user enters 3, terminate the program
import random
def main():
# The loop variable
i = 0
while i != 1:
print('\nMAIN MENU\n')
print('--------------------')
print('1) Add Random Numbers')
print('2) Subtract Random Numbers')
print('3) Exit\n')
# Ask the user to pick which option
choice = int(input('Which would you like to do? '))
if choice == 1:
addRandom()
elif choice == 2:
subRandom()
elif choice == 3:
# The program will terminate
print('The program will terminate')
i = 1
else:
print('Not a valid option')
def addRandom():
randomnum1 = random.randrange(1,300)
randomnum2 = random.randrange(1,300)
answer = randomnum1 + randomnum2
print(' '+str(randomnum1)+'\n+ '+str(randomnum2))
guess = int(input('\nWhat is the answer? '))
if guess == answer:
print('Congratulations! you got it correct!')
elif guess != answer:
print(answer)
def subRandom():
randomnum1 = random.randrange(1,300)
randomnum2 = random.randrange(1,300)
answer = randomnum1 - randomnum2
print(' '+str(randomnum1)+'\n- '+str(randomnum2))
guess = int(input('\nWhat is the answer? '))
if guess == answer:
print('Congratulations! you got it correct!')
elif guess != answer:
print(answer)
main()
| true
|
7e3ff4cbf422f91773d66991a05720718ec42bd7
|
cs112/cs112.github.io
|
/recitation/rec8.py
| 1,585
| 4.1875
| 4
|
"""
IMPORTANT: Before you start this problem, make sure you fully understand the
wordSearch solution given in the course note.
Now solve this problem:
wordSearchWithIntegerWildCards
Here we will modify wordSearch so that we can include positive integers in the
board, like so (see board[1][1]):
board = [ [ 'p', 'i', 'g' ],
[ 's', 2, 'c' ],
]
When matching a word, a positive integer on the board matches exactly that many
letters in the word. So the board above contains the word "cow" starting from
[1,2] heading left, since the 2 matches "ow". It also contains the word "cows"
for the same reason. But it does not contain the word "co", since the 2 must
match exactly 2 letters. To make this work, of the three functions in our
wordSearch solution, the outer two do not have to change, but the innermost
one does. Rewrite the innermost function here so that it works as described.
Your function should return True if the word is in the wordSearch and False
otherwise.
"""
def wordSearch(board, word):
return 42 # place your solution here!
def testWordSearch():
print("Testing wordSearch()...", end="")
board = [ [ 'p', 'i', 'g' ],
[ 's', 2, 'c' ]
]
assert(wordSearch(board, "cow") == True)
assert(wordSearch(board, "cows") == True)
assert(wordSearch(board, "coat") == False)
assert(wordSearch(board, "pig") == True)
assert(wordSearch(board, "z") == False)
assert(wordSearch(board, "zz") == True)
print("Passed!")
# testWordSearch() # uncomment this line to test!
| true
|
63d2eda6cbc8cbfc8c992828adb506ffd7f5a075
|
cs112/cs112.github.io
|
/challenges/challenge_1.py
| 759
| 4.15625
| 4
|
################################################################################
# Challenge 1: largestDigit
# Find the largest digit in an integer
################################################################################
def largestDigit(n):
n = abs(n)
answer = 0
check =0
while n >0:
check = n%10
n //= 10
if check > answer:
answer = check
return answer
def testLargestDigit():
print("Testing largestDigit()...", end="")
assert(largestDigit(1) == 1)
assert(largestDigit(9233) == 9)
assert(largestDigit(187932) == 9)
assert(largestDigit(0) == 0)
assert(largestDigit(10) == 1)
assert(largestDigit(-1) == 1)
assert(largestDigit(-236351) == 6)
print("Passed!")
| true
|
ac1c189338811d43945c5e96f729085aaffe26d8
|
Halal-Appnotrix/Problem-Solving
|
/hackerrank/Problem-Solving/Algorithm/Implementation/Grading_Students.py
| 783
| 4.125
| 4
|
#
# The function is expected to return an INTEGER_ARRAY.
# The function accepts INTEGER_ARRAY grades as parameter.
#
def gradingStudents(grades):
grades_array = []
for grade in grades:
the_next_multiple_of_5 = (((grade // 5)+1)*5)
if grade < 38:
grades_array.append(grade)
elif (the_next_multiple_of_5 - grade) < 3:
grades_array.append(the_next_multiple_of_5)
else:
grades_array.append(grade)
return grades_array
if __name__ == '__main__':
grades_count = int(input().strip())
grades = []
for _ in range(grades_count):
grades_item = int(input().strip())
grades.append(grades_item)
result = gradingStudents(grades)
print('\n'.join(map(str, result)))
| true
|
b57b87613722928d3011f9bba5325e962765a403
|
matsalyshenkopavel/codewars_solutions
|
/Stop_gninnipS_My_sdroW!.py
| 833
| 4.125
| 4
|
"""Write a function that takes in a string of one or more words, and returns the same string,
but with all five or more letter words reversed (like the name of this kata).
Strings passed in will consist of only letters and spaces.
Spaces will be included only when more than one word is present."""
def spin_words(sentence):
sentence_list = sentence.split()
sentence_list = [x[::-1] if len(x) >= 5 else x for x in sentence_list]
return " ".join(sentence_list)
# spinWords("Hey fellow warriors") => "Hey wollef sroirraw"
# spinWords("This is a test") => "This is a test"
# spinWords("This is another test") => "This is rehtona test"
print(spin_words("Hey fellow warriors")) #"Hey wollef sroirraw"
print(spin_words("This is a test")) #"This is a test"
print(spin_words("This is another test")) #"This is rehtona test"
| true
|
ec032c38241a21a69ea74a412cc065b941fde566
|
eduardoorm/pythonExercises
|
/parte2/e10.py
| 407
| 4.125
| 4
|
# Escriba una función es_bisiesto() que determine si un año determinado es un año
# bisiesto.Un año bisiesto es divisible por 4, pero no por 100. También es divisible por 400
def es_bisiesto(anio):
if(anio%4==0 and anio%100!=0):
return True
return False
anio = int(input("Por favor ingrese un año"))
isbisiesto = es_bisiesto(anio)
print(f"el año {anio} ¿es bisiesto?:",isbisiesto )
| false
|
72ca893a64d68df62007a37b70a597fa7f11112f
|
gladguy/PyKids
|
/project.py
| 2,313
| 4.21875
| 4
|
print("Hi i am a turtle and I can draw many shapes")
import turtle
def circle(radius,bob):
bob.pendown()
bob.circle(radius)
bob.penup()
def star(bob):
bob.pendown()
for i in range(5):
bob.forward(100)
bob.right(144)
bob.penup()
def square(bob):
bob.pendown()
for i in range(4):
bob.forward(100)
bob.right(90)
bob.penup()
def pentagon(bob):
bob.pendown()
for i in range(5):
bob.forward(100)
bob.right(72)
bob.penup()
def hexagon(bob):
bob.pendown()
for i in range(6):
bob.forward(100)
bob.right(60)
bob.penup()
def octagon(bob):
bob.pendown()
for i in range(8):
bob.forward(100)
bob.right(45)
bob.penup()
def decagon(bob):
bob.pendown()
for i in range(8):
bob.forward(100)
bob.right(36)
bob.penup()
def tangentialcircle(bob):
bob.pendown()
for i in range(10):
bob.circle(10*i)
bob.penup()
def triangle(bob):
bob.pendown()
for i in range(2):
bob.forward(100)
bob.left(120)
bob.forward(100)
bob.penup()
pet=turtle.Turtle()
pet.shape("turtle")
screen=turtle.Screen()
screen.bgcolor("Red")
penSize=int(input("Enter the pen size of turtle"))
pet.pensize(penSize)
print("What shape you want turtle to draw?")
print("Click 1 for circle")
print("Click 2 for star")
print("Click 3 for square")
print("Click 4 for pentagon")
print("Click 5 for hexagon")
print("Click 6 for octagon")
print("Click 7 for decagon")
print("Click 8 for tangential circle")
print("Click 9 for triangle")
option=int(input("Enter the option:"))
if option in(1,2,3,4,5,6,7,8):
if (option==1):
sizeradius=int(input("Enter the radius size:"))
circle(sizeradius,pet)
elif(option==2):
star(pet)
elif(option==3):
square(pet)
elif(option==4):
pentagon(pet)
elif(option==5):
hexagon(pet)
elif(option==6):
octagon(pet)
elif(option==7):
decagon(pet)
elif(option==8):
tangentialcircle(pet)
elif(option==9):
triangle(pet)
else:
print("Please enter valid number")
| false
|
c8ba22783ac90fe69a8c3b86dab3a3fc8d905980
|
gladguy/PyKids
|
/Aamirah Fathima/Input_file.py
| 231
| 4.15625
| 4
|
print("My name is Aamirah what is your name?")
name = input("Enter your name!")
print(name)
print("My age is 10 ?")
age = input("Enter your age!")
print(age)
a = 6
if int(age) < a:
print("You are too young to drive!")
| false
|
e9183dc00682ac9e38bc8f01fd49f4b5f3c9fa37
|
Isha09/mit-intro-to-cs-python
|
/edx/week1/prob1.py
| 552
| 4.125
| 4
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 6 14:52:43 2017
@author: esha
Prog: Assume s is a string of lower case characters.
Write a program that counts up the number of vowels contained in the string s.
Valid vowels are: 'a', 'e', 'i', 'o', and 'u'.
For example, if s = 'azcbobobegghakl', your program should print: Number of vowels: 5
"""
s = str(input("Enter any string:"))
count = 0
for ch in s:
if(ch == 'a' or ch == 'e' or ch == 'i' or ch == 'o' or ch == 'u'):
count += 1
print('Number of vowels:',count)
| true
|
90fd58a60095a888058eb7788255886b6870056a
|
david778/python
|
/Point.py
| 1,233
| 4.4375
| 4
|
import math
class Point(object):
"""Represents a point in two-dimensional geometric coordinates"""
def __init__(self, x=0.0, y=0.0):
"""Initialize the position of a new point. The x and y coordinates
can be specified. If they are not, the point defaults to the origin."""
self.move(x, y)
def move(self, x, y):
"""Move the point to a new location in two-dimensional space."""
self.x = x
self.y = y
def reset(self):
"""Reset the point back to the geometric origin: 0, 0 """
self.move(0.0, 0.0)
def calculate_distance(self, other_point):
"""Calculate the distance from this point to a second point passed as a parameter.
This function uses the pythagorean theorem to calculate
the distance between the two points. The distance is returned as float."""
return math.sqrt((self.x - other_point.x) ** 2 + (self.y - other_point.y) ** 2)
# Creating instance objects
point_a = Point(2, -2)
point_b = Point(2, 2)
point_x = Point(0, 0)
point_y = Point(7, 1)
# distance entry a and b
distance_a = point_a.calculate_distance(point_b)
distance_b = point_x.calculate_distance(point_y)
print(distance_a)
print(distance_b)
| true
|
47c580cf46d2c83ebf1ca05601c7f4c05ea4d913
|
nitred/nr-common
|
/examples/mproc_example/mproc_async.py
| 1,442
| 4.15625
| 4
|
"""Simple example to use an async multiprocessing function."""
from common_python.mproc import mproc_async, mproc_func
# STEP - 1
# Define a function that is supposed to simulate a computationally intensive function.
# Add the `mproc_func` decorator to it in order to make it mproc compatible.
@mproc_func
def get_square(x):
"""Return square of a number after sleeping for a random time."""
import random
import time
time.sleep(random.random())
return x**2
# STEP - 2
# Create a list of list of argument for the `get_square` function.
# The length of the outer list determines the number of times the function is going to be called asynchronously.
# In this example, the length is 20. The final `iterof_iterof_args` will look like [[0], [1], [2] ...]
iterof_iterof_args = [[i] for i in range(20)]
# STEP -3
# Call the function 20 times using multiprocessing.
# We limit the number of processes to be 4 and at any time there will be a max of 4 results.
# The output is a generator of results.
results_gen = mproc_async(get_square,
iterof_iterof_args=iterof_iterof_args,
n_processes=4,
queue_size=4)
# STEP - 4
# Print the results.
# Each result looks like a tuple of (original_index, function_output)
for async_index, result in enumerate(results_gen):
call_index, func_output = result
print(async_index, call_index, func_output)
| true
|
d6fb8c780bc46b577df3beb95265bf6addd4d2e1
|
ronBP95/insertion_sort
|
/app.py
| 690
| 4.21875
| 4
|
def insertion_sort(arr):
operations = 0
for i in range(len(arr)):
num_we_are_on = arr[i]
j = i - 1
# do a check to see that we don't go out of range
while j >= 0 and arr[j] > num_we_are_on:
operations += 1
# this check will be good, because we won't check arr[-1]
# how can i scoot arr[j] up a place in our list
arr[j+1] = arr[j]
j -= 1
# where am i
j += 1
arr[j] = num_we_are_on
# ordered array
return arr, operations
test_arr = [3, 4, 5, 8, 2, 1, 4]
ordered_array, operations = insertion_sort(test_arr)
print(ordered_array, operations)
| true
|
7314f15c59cd41a095c2d6c9e12e824ff23f9dad
|
davidalanb/PA_home
|
/Py/dicts.py
| 1,188
| 4.4375
| 4
|
# make an empty dict
# use curly braces to distinguish from standard list
words = {}
# add an item to words
words[ 'python' ] = "A scary snake"
# print the whole thing
print( words )
# print one item by key
print( words[ 'python' ] )
# define another dict
words2 = { 'dictionary': 'a heavy book', \
'class': 'a group of students' }
# add all keys/items in words2 to words
words.update( words2 )
# add another key/item
words.update( { 'object': 'something'} )
#change a definition
words.update( { 'class': 'an echelon of society'} )
print( words )
# iterate with keys, 2 ways:
#for key in words.keys():
for key in words:
print( key, end='; ' )
print()
# iterate with values
for value in words.values():
print( value, end='; ' )
print()
# iterate with keys and values
for key, value in words.items():
print( key, ':', value, end='; ' )
print()
try:
print( words[ 'key' ] )
except Exception as e:
print( type(e) )
key = 'nasef'
# ask for permission
if key in words:
print( words[ key ] )
else:
print( 'key', key, 'not found' )
# ask for forgiveness
try:
print( words[ key ] )
except KeyError:
print( 'key',key,'not found' )
| true
|
aa5a664ccba0cd7dee9df189804cbcce0fd3e6d0
|
davidalanb/PA_home
|
/Py/ps4/lists.py
| 1,492
| 4.125
| 4
|
'''
Lists are mutable
'''
print( '----------- identical to string methods ---------------' )
# type-casting: make a list out of a string
s = "Benedetto"
ls = list(s)
# basics
print( ls )
print( len( ls ) )
print( ls[0], ls[-1] )
# one way to iterate
for letter in ls:
print( letter, end='.' )
print()
# 2nd way: iterate with index
for i in range( len(ls) ):
print( ls[i], end='-' )
print()
# getting slices
print( ls[0:4] )
print( ls[4:len(s)] )
print( '----------- add / remove ---------------' )
# setup
ls = [ "joe", "jane" ]
print( ls )
# a couple ways to append
ls.append( "rob" )
ls += [ "bill", "phoebe" ]
print( ls )
# insert at a given index
ls.insert( 2, "marcus" )
print( ls )
# pop removes and returns one element by index
name = ls.pop(2)
print( name, ls )
# del removes one of more elements by index[es]
outcasts = ls[2:4]
del( ls[2:4] )
print( outcasts, ls )
# remove a found element
ls.remove( 'phoebe' )
print( ls )
print( '--- alias & clone ---' )
ls1 = ['joe','bob']
ls2 = ls1 # make another reference to same list
ls2.remove( 'bob' ) # ls1 and ls2 refer to only one list
print( 'ls1: ', ls1 )
ls1 = ['joe','bob']
ls2 = ls1[:] # make a clone of ls1 called ls2
ls2.remove('bob') # modify ls2
print( 'ls1: ', ls1 ) # see that ls1 hasn't changed
print( 'ls2: ', ls2 )
print( '----------- sort --------------' )
ls = list("ngieaNDGNIEWSK, .,42764(*&^(*^@")
ls.sort()
for item in ls: print( item, end=' ')
| false
|
e3ebb85ecd24e1377c002063691b02ac2d6d12f8
|
Lschulzes/Python-practice
|
/ex033.py
| 610
| 4.1875
| 4
|
nums = int(input('Digite 3 números: '))
un = nums // 1 % 10
dez = nums // 10 % 10
cent = nums // 100 % 10
if un > dez:
if un > cent:
if cent < dez:
print(f'O maior número é {un} e o menor é {cent}')
else:
print(f'O maior número é {un} e o menor é {dez}')
else:
print(f'O maior número é {cent} e o menor é {dez}')
elif un > cent:
print(f'O maior número é {dez} e o menor é {cent}')
elif dez > cent:
print(f'O maior número é {dez} e o menor é {un}')
else:
print(f'O maior número é {cent} e o menor é {un}')
| false
|
8da467620d03b99b73ed7a1720a299a75266fdfc
|
Lschulzes/Python-practice
|
/ex009.py
| 309
| 4.1875
| 4
|
n = int(input('Digite um número inteiro: '))
n1 = n * 1
n2 = n * 2
n3 = n * 3
n4 = n * 4
n5 = n * 5
n6 = n * 6
n7 = n * 7
n8 = n * 8
n9 = n * 9
print(f'{n} * 1 = {n1}\n{n} * 2 = {n2}\n{n} * 3 = {n3}\n{n} * 4 = {n4}\n{n} * 5 = {n5}\n{n} * 6 = {n6}\n{n} * 7 = {n7}\n{n} * 8 = {n8}\n{n} * 9 = {n9}')
| false
|
06758f00f3b1ce885899102fe093651f6d0226b4
|
Lschulzes/Python-practice
|
/ex039.py
| 323
| 4.1875
| 4
|
ano = int(input('Qual o ano do seu nascimento? '))
idade = 2021 - ano
passou = idade - 18
falta = 18 - idade
if idade == 18:
print('Você deve se alistar neste ano!')
elif idade > 18:
print(f'Você deveria ter se alistado há {passou} anos!')
else:
print(f'Você deverá se alistar em {falta} anos!')
| false
|
73e023a3d2ca6364b71fe2f99f19415477ff4c46
|
amitjpatil23/simplePythonProgram
|
/MatrixMultiplication.py
| 598
| 4.15625
| 4
|
# Program to multiply two matrices using nested loops
# take a 3 by 3 matrix
A = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
# take a 3 by 4 matrix
B = [[100, 200, 300, 400],
[500, 600, 700, 800],
[900, 1000, 1100, 1200]]
result = [[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]]
# iterating by row of A
for i in range(len(A)):
# iterating by coloum by B
for j in range(len(B[0])):
# iterating by rows of B
for k in range(len(B)):
result[i][j] += A[i][k] * B[k][j]
for r in result:
print(r)
| false
|
f8f481911c4d3d8b79082899528af93978e92957
|
amitjpatil23/simplePythonProgram
|
/Atharva_35.py
| 620
| 4.25
| 4
|
# Simple program in python for checking for armstrong number
# Python program to check if the number is an Armstrong number or not
y='y'
while y == 'y': # while loop
# take input from the user
x = int(input("Enter a number: "))
sum = 0
temp = x
while temp > 0: #loop for checking armstrong number
digit = temp % 10
sum += digit ** 3
temp //= 10
if x == sum:
print(x,"is an Armstrong number")
else:
print(x,"is not an Armstrong number")
y=input("WNamt to continue?(y/n)") #Condition for multiple run
| true
|
0c8893cdaadd507fb071816a92dd52f2c8955d65
|
amitjpatil23/simplePythonProgram
|
/palindrome_and_armstrong_check.py
| 630
| 4.21875
| 4
|
def palindrome(inp):
if inp==inp[::-1]: #reverse the string and check
print("Yes, {} is palindrome ".format(inp))
else:
print("No, {} is not palindrome ".format(inp))
def armstrong(number):
num=number
length=len(str(num))
total=0
while num>0:
temp=num%10
total=total+(temp**length) #powering each digit with length of number and adding
num=num//10
if total==number:
print("{} is Armstrong number".format(number) )
else:
print("{} is not an Armstrong number".format(number) )
palindrome('qwerewq')
armstrong(407)
| true
|
e7c66be2e1a9bdc5d12081089678885933da93d4
|
SongYippee/leetcode
|
/String/字符串相乘.py
| 1,240
| 4.1875
| 4
|
# -*- coding: utf-8 -*-
# @Time : 2019/2/13 16:51
# @Author : Yippee Song
# @Software: PyCharm
'''
给定两个以字符串形式表示的非负整数 num1 和 num2,返回 num1 和 num2 的乘积,它们的乘积也表示为字符串形式。
示例 1:
输入: num1 = "2", num2 = "3"
输出: "6"
示例 2:
输入: num1 = "123", num2 = "456"
输出: "56088"
说明:
num1 和 num2 的长度小于110。
num1 和 num2 只包含数字 0-9。
num1 和 num2 均不以零开头,除非是数字 0 本身。
不能使用任何标准库的大数类型(比如 BigInteger)或直接将输入转换为整数来处理。
'''
class Solution(object):
def multiply(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
def str2num(str):
l = len(str)
if str == '0':
return 0
else:
total = 0
for i in range(l):
h = int(str[i])
total +=h*10**(l-i-1)
return total
return str(str2num(num1)*str2num(num2))
if __name__ == '__main__':
num1 = "123"
num2 = "456"
print num1+"*"+num2
print Solution().multiply(num1,num2)
| false
|
a26e88d420464e4c075984303274738ce61db468
|
SongYippee/leetcode
|
/LinkedList/86 分片链表.py
| 1,529
| 4.15625
| 4
|
# -*- coding: utf-8 -*-
# @Time : 1/14/20 10:17 PM
# @Author : Yippee Song
# @Software: PyCharm
'''
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
Example:
Input: head = 1->4->3->2->5->2, x = 3
Output: 1->2->2->4->3->5
'''
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def partition(self, head, x):
"""
:type head: ListNode
:type x: int
:rtype: ListNode
"""
first = None
firstTmp = None
second = None
secondTmp = None
tmp = head
while tmp:
nextNode = tmp.next
if tmp.val < x:
if not first:
first = tmp
firstTmp = first
else:
firstTmp.next = tmp
firstTmp = firstTmp.next
tmp.next = None
else:
if not second:
second = tmp
secondTmp = tmp
else:
secondTmp.next = tmp
secondTmp = secondTmp.next
tmp.next = None
tmp = nextNode
if firstTmp:
firstTmp.next = second
return first
else:
return second
| true
|
553d882e8e0f8e7588b69d8ea491e2b54ecf4689
|
SongYippee/leetcode
|
/String/翻转字符串里的单词.py
| 881
| 4.15625
| 4
|
# -*- coding: utf-8 -*-
# @Time : 2019/2/13 16:54
# @Author : Yippee Song
# @Software: PyCharm
'''
给定一个字符串,逐个翻转字符串中的每个单词。
示例:
输入: "the sky is blue",
输出: "blue is sky the".
说明:
无空格字符构成一个单词。
输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。
进阶: 请选用C语言的用户尝试使用 O(1) 空间复杂度的原地解法。
'''
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
s = s.strip()
data = [x for x in s.split() if x]
return " ".join(data[::-1])
if __name__ == '__main__':
s = "the sky is blue"
print Solution().reverseWords(s);
| false
|
04a19b417325d45e3b776f200eed3d80042a2159
|
uran001/Small_Projects
|
/Hot_Potato_Game/hot_potato_classic.py
| 1,236
| 4.125
| 4
|
# Note the import of the Queue class
from queue import ArrayQueue
def hot_potato(name_list, num):
"""
Hot potato simulator. While simulating, the name of the players eliminated should also be printed
(Note: you can print more information to see the game unfolding, for instance the list of
players to whom the hot potato is passed at each step...)
:param name_list: a list containing the name of the players, e.g. ["John", "James", "Alice"]
:param num: the counting constant (i.e., the length of each round of the game)
:return: the winner (that is, the last player standing after everybody else is eliminated)
"""
print("Game is started with players")
r = 1
n = 0
while 1:
if len(name_list) == 1:
return name_list[0]
print ("Round {0}".format(r))
print(name_list)
for x in range(len(name_list)):
n += 1
if n % num == 0:
print(name_list[x])
name_list.remove(name_list[x])
r += 1
if __name__ == '__main__':
name_list = ["Marco", "John", "Hoang", "Minji", "Hyunsuk", "Jiwoo"]
winner = hot_potato(name_list, 5)
print("...and the winner is: {0}".format(winner))
| true
|
474cc9eb3ba257339e9b726479cfa10f03c14e29
|
rbarrette1/Data-Structures
|
/LinkedList/LinkedList.py
| 2,055
| 4.21875
| 4
|
from Node import * # import Node class
head = "null" # first node of the linked list
class LinkedList():
def __init__(self):
self.head = None # set to None for the time being
# insert after a specific index
def insert_after_index(self, index, new_node):
node = self.head # get the first node
for i in range(index): # loop through by accessing the next node
node = node.next # move to the next node
if(i == index-1): # if at the desired index
new_node.next = node.next # set the next node of the new node to the node currently in its' place
node.next = new_node # set the next node of the node currently in its' place with the new node
# remove from a particular index
def remove_after_index(self, index):
print("Removing after index: " + str(index))
node = self.head
if(index == 0): # if removing the first node
self.head = node.next # set head to the next node
for i in range(index):
node_before = node # save previous node and current node to connect both
node = node.next
if(i == index-1): # when at the desired index
print("Connecting nodes: " + str(node_before.value) + " and " + str(node.next.value))
# connect the next node of the previous node with the next node of the current to delete the current node
node_before.next = node.next
# travel to a specific index
def traverse_to_node(self, index):
print("Traversing to: " + str(index))
node = self.head # get the first node
for i in range(index): # stop at index
node = node.next # move to the next node
# travel to the end of the linked list
def traverse_through_linkedlist(self):
print("Traversing...")
node = self.head # get the first node
while node is not None: # while the next node exists
print(node.value)
node = node.next # move to the next node
| true
|
642410d99d761e9565cd2829893d08bf901e7c7b
|
Johnscar44/code
|
/python/notes/elif.py
| 331
| 4.125
| 4
|
secret_num = "2"
guess = input("guess the number 1 - 3: ")
if guess.isdigit() == False:
print("answer can only be a digit")
elif guess == "1":
print("Too Low")
elif guess == "2":
print("You guessed it!")
elif guess == "3":
print("Too high")
else:
print("Guess not in rage 1 - 3")
print("please try again")
| true
|
a2b2da73552e61cc2a3fbae380186374984d0b0f
|
Johnscar44/code
|
/compsci/moon.py
| 1,207
| 4.1875
| 4
|
phase = "Full"
distance = 228000
date = 28
eclipse = True
# - Super Moon: the full moon occurs when the moon is at its closest approach to earth (less than 230,000km away).
# - Blue Moon: the second full moon in a calendar month. In other words, any full moon on the 29th, 30th, or 31st of a month.
# - Blood Moon: a lunar eclipse during a full moon.
if phase == "Full" and distance < 230000 and date >= 29 and eclipse == True:
print("Super Blue Blood Moon")
elif phase == "Full" and date <= 28 and distance < 230000 and eclipse == True:
print("Super Blood Moon")
elif phase == "Full" and date >= 29 and eclipse == True:
print("Blue Blood Moon")
elif phase == "Full" and distance < 230000 and date >= 29 and eclipse == False:
print("Super Blue Moon")
elif phase == "Full" and distance < 230000 and date <= 29 and eclipse == False:
print("Super Moon")
elif phase == "Full" and distance > 230000 and date <= 29 and eclipse == False:
print("Full Moon")
elif phase == "Full" and distance > 230000 and date <= 29 and eclipse == True:
print("Blood Moon")
elif phase == "Full" and distance > 230000 and date >= 29 and eclipse == False:
print("Blue Moon")
else:
print("Moon")
| true
|
6d2ddc65b018e810f4e4e6dc4424cc6025853faa
|
Johnscar44/code
|
/compsci/newloop.py
| 562
| 4.375
| 4
|
mystery_int_1 = 3
mystery_int_2 = 4
mystery_int_3 = 5
#Above are three values. Run a while loop until all three
#values are less than or equal to 0. Every time you change
#the value of the three variables, print out their new values
#all on the same line, separated by single spaces. For
#example, if their values were 3, 4, and 5 respectively, your
#code would print:
#2 3 4
#1 2 3
#0 1 2
#-1 0 1
#-2 -1 0
while mystery_int_1 > 0 and mystery_int_2 > 0 and mystery_int_3 > 0:
mystery_int_1 -= 1
print(mystery_int_1 , mystery_int_2 , mystery_int_3)
| true
|
570a915a233eee00cc23b34d7ce3cf2c78940d75
|
Johnscar44/code
|
/compsci/forloop.py
| 957
| 4.71875
| 5
|
#In the designated areas below, write the three for loops
#that are described. Do not change the print statements that
#are currently there.
print("First loop:")
for i in range(1 , 11):
print(i)
#Write a loop here that prints the numbers from 1 to 10,
#inclusive (meaning that it prints both 1 and 10, and all
#the numbers in between). Print each number on a separate
#line.
for i in range(-5 , 6):
print("Second loop:")
#Write a loop here that prints the numbers from -5 to 5,
#inclusive. Print each number on a separate line.
for i in range(1 , 21):
if i % 2 == 0:
print("Third loop:" , i)
#Write a loop here that prints the even numbers only from 1
#to 20, inclusive. Print each number on a separate line.
#
#Hint: There are two ways to do this. You can use the syntax
#for the range() function shown in the multiple-choice
#problem above, or you can use a conditional with a modulus
#operator to determine whether or not to print.
| true
|
1505e0d9e27d1b20670da4c4667fc9189fe151a5
|
Fernando23296/l_proy
|
/angle/ayuda_1.py
| 461
| 4.21875
| 4
|
from turtle import *
from math import *
import math
a = float(input("enter the value for a: "))
b = float(input("enter the value for b: "))
c = float(input("enter the value for c: "))
if (a + b >= c) and (b + c >= a) and (c + a >= b):
print("it's a triangle")
A = degrees(acos((b**2 + c**2 - a**2)/(2*b*c)))
B = degrees(acos((c**2 + a**2 - b**2)/(2*c*a)))
C = degrees(acos((a**2 + b**2 - c**2)/(2*a*b)))
else:
print("it's not a triangle")
| false
|
691d922adfbb58996dabc180a1073ef06afa000a
|
choprahetarth/AlgorithmsHackerRank01
|
/Python Hackerrank/oops3.py
| 827
| 4.25
| 4
|
# Credits - https://www.youtube.com/watch?v=JeznW_7DlB0&ab_channel=TechWithTim
# class instantiate
class dog:
def __init__(self,name,age):
self.referal = name
self.age = age
# getter methods are used to print
# the data present
def get_name(self):
return self.referal
def get_age(self):
return self.age
# these setter functions are
# added to modify the existing
# data, that is stored there
def set_age(self,age):
self.age=age
def set_name(self,name):
self.referal = name
d1 = dog("Snoop", 46)
d2 = dog("Dre", 48)
# print existing data
print(d1.get_age())
print(d1.get_name())
# modify data using getter methods
d1.set_age(52)
d1.set_name("Eminem")
# print the modified data
print(d1.get_age())
print(d1.get_name())
| true
|
5960a9e747851838f2823ab0b3b5027275d12b97
|
choprahetarth/AlgorithmsHackerRank01
|
/Old Practice/linkedList.py
| 1,093
| 4.46875
| 4
|
# A simple python implementation of linked lists
# Node Class
class Node:
# add an init function to start itself
def __init__(self,data):
self.data = data
self.next = None # initialize the linked list with null pointer
# Linked List Class
class linkedList:
# add an init function to initialize the head
def __init__(self):
self.head = None # initialize the head of the LL
# function that traverses the linked list
def traverse(headValue):
while(headValue!=None):
print(headValue.data)
headValue=headValue.next
# main function
if __name__ == '__main__':
# pehle initialize the linked list
linked_List = linkedList()
# then assign the first node to the head value
linked_List.head = Node(1)
# then make two more nodes
second = Node(2)
third = Node(3)
# then link the head's next value with the second node
linked_List.head.next = second
# then link the next of the second node with the third
second.next = third
# function to traverse a linked list
traverse(linked_List.head)
| true
|
b499e6ecc7e711bf74441b89fec4fcc49712b4a3
|
Mohini-2002/Python-lab
|
/Method(center,capitalize,count,encode,decode)/main.py
| 702
| 4.28125
| 4
|
#Capitalize (capital the first of a string and its type print)
ST1 = input("Enter a string :")
ST1 = ST1.capitalize()
print("After capitalize use : ", ST1, type(ST1))
#Center (fill the free space of a string and and its type print)
ST2 = input("ENter a string :")
ST2 = ST2.center(20, "#")
print("After center use :", ST2, type(ST2))
#Count (Count the st occurs in string and its type print)
ST3 = input("Enter a string :")
ST3 = ST3.count('O', 1, 10)
print(ST3, type(ST3))
#Encode
ST4 = input("Enter a string : ")
ST4 = ST4.encode("utf-8")
print(ST4, type(ST4))
#Decode
ST5 = input("Enter a string :")
ST5 = ST5.decode(encoding="UTF-8", erros='strict')
print(ST5, type(ST5))
| true
|
718d8989750b21513fff2c0eea78016432b90a4d
|
asimihsan/challenges
|
/epi/ch12/dictionary_word_hash.py
| 2,509
| 4.15625
| 4
|
#!/usr/bin/env python
# EPI Q12.1: design a hash function that is suitable for words in a
# dictionary.
#
# Let's assume all words are lower-case. Note that all the ASCII
# character codes are adjacent, and yet we want a function that
# uniformly distributes over the space of a 32 bit signed integer.
#
# We can't simply use a cryptographic hash function because these are
# unacceptably slow. We could use CRC32, and it might be decent, but
# what is more intuitive?
import operator
import string
class DictionaryWord(object):
__slots__ = ('value', 'primes')
primes = {'a': 2, 'b': 3, 'c': 5, 'd': 7, 'e': 11, 'f': 13, 'g': 17,
'h': 19, 'i': 23, 'j': 29, 'k': 31, 'l': 37, 'm': 41,
'n': 43, 'o': 47, 'p': 53, 'q': 59, 'r': 61, 's': 67,
't': 71, 'u': 73, 'v': 79, 'w': 83, 'x': 89, 'y': 97,
'z': 101}
def __init__(self, value):
self.value = value
def __hash__(self):
"""A hash function must be consistent with equals (any two
objects which are equal must have the same hash code). A
hash function should ideally uniformly distribute its output
as a signed integer; Python chops off the sign bit and
does the modulus into the dictionary for us.
"""
# With Douglas Adams on our side this takes longer than a
# minute. Ouch!
#return 42
# I know summing the chars is bad, but how bad? 19s!
#return sum(ord(x) for x in self.value)
# How about assigning a prime number per letter, then returning
# the product? Takes 3.5s.
#return reduce(operator.mul, (self.primes[x] for x in self.value))
# What about the product of chars? 3.4s! Better than primes!
#return reduce(operator.mul, (ord(x) for x in self.value))
# How about a Java hashCode approach? Sum chars but mult
# by Mersenne prime each time. 3.0s!
# Likely better because more peturbation on single char
# changes.
result = 17
for x in self.value:
result = 31 * result + ord(x)
return result
# With the system default it takes 2.2s
#return hash(self.value)
if __name__ == "__main__":
lookup = set()
with open("/usr/share/dict/words") as f_in:
lines = (line.strip() for line in f_in
if all(elem in string.ascii_lowercase for elem in line.strip()))
for line in lines:
lookup.add(DictionaryWord(line))
| true
|
70e759634d967837b0faed377ced9807c4a604f8
|
xct/aoc2019
|
/day1.py
| 920
| 4.125
| 4
|
#!/usr/bin/env python3
'''
https://adventofcode.com/2019/day/1
Fuel required to launch a given module is based on its mass.
Specifically, to find the fuel required for a module, take its mass, divide by three, round down, and subtract 2.
'''
data = []
with open('data/day1.txt','r') as f:
data = f.readlines()
# Part 1 (Fuel for the base mass)
sum1 = 0
for mass in data:
mass = int(mass)
fuel = mass//3 - 2
sum1 += fuel
print(f'Sum = {sum1}')
# That's the right answer! You are one gold star closer to rescuing Santa.
# Part 2 (Fuel for the fuel)
def get_fuel(mass):
fuel_sum = 0
remaining_mass = mass
while True:
fuel = remaining_mass//3 - 2
if fuel <= 0:
break
fuel_sum += fuel
remaining_mass = fuel
return fuel_sum
sum2 = 0
for mass in data:
mass = int(mass)
fuel = get_fuel(mass)
sum2 += fuel
print(f'Sum = {sum2}')
| true
|
3f26a0de9a124b493c1dc5734a2f9e9d30ef6114
|
vaishalibhayani/Python_example
|
/Python_Datatypes/sequence_types/dictionary/dictionary1.py
| 516
| 4.28125
| 4
|
emp={
'course_name':'python',
'course_duration':'3 Months',
'course_sir':'brijesh'
}
print(emp)
print(type(emp))
emp1={1:"vaishali",2:"dhaval",3:"sunil"}
print(emp1)
print(type(emp1))
#access value using key
print("first name inside of the dictionary:" +emp1[2])
#access value using key
print("first name inside the dictionary:" +emp1[3])
## fetch or show only keys of dictionary
print(emp1.keys())
# fetch or show only Value of dictionary
print(emp1.values())
| true
|
0d392a51311a1da24c84669dc57a50610bccb111
|
Daroso-96/estudiando-python
|
/index.py
| 1,168
| 4.1875
| 4
|
if 5 > 3:
print('5 es mayor que 3')
x = 5
y = 'Sashita feliz'
#print(x,y)
email = 'sashita@feliz.com'
#print(email)
inicio = 'Hola'
final = 'mundo'
#print(inicio + final)
palabra = 'Hola mundo'
oracion = "Hola mundo con comillas dobles"
lista = [1,2,3]
lista2 = lista.copy()
lista.append('Sashita feliz jugando ')
print(lista, lista2.count(5))
print(len(lista))
lista.pop()
lista.reverse()
lista.sort()
tupla = ('Hola', 'mundo', 'somos', 'tuplas')
listaDeTupla = list(tupla)
listaDeTupla.append('Sashita')
print(listaDeTupla)
rango = range(6)
#print(rango)
diccionario = {
"nombre": "Sashita",
"raza ": "Weimaraner",
"edad" : 1
}
diccionario['nombre'] = 'Lucerito'
#print(len(diccionario))
diccionario['Ladra'] = 'si'
#diccionario.popitem()
copiaPerrito = diccionario.copy()
del diccionario['Ladra']
#print(diccionario)
diccionario.pop('edad')
#print(diccionario, copiaPerrito)
perritos = {
"sashita" : {
"nombre": "sashita",
"edad": 1
},
"lucerito" : {
"nombre": "lucerito",
"edad" : 2
}
}
print(perritos)
gatitos = dict(nombre = "Agatha" , edad = 1)
print(gatitos)
verdadero = True
falso = False
print(verdadero, falso)
| false
|
52c255ca2ffcc9b42da2427997bcfa6b539127d2
|
NaveenSingh4u/python-learning
|
/basic/python-oops/python-other-concept/generator-ex4.py
| 1,121
| 4.21875
| 4
|
# Generators are useful in
# 1. To implement countdown
# 2. To generate first n number
# 3. To generate fibonacci series
import random
import time
def fib():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
for n in fib():
if n > 1000:
break
print(n)
names = ['sunny', 'bunny', 'chinmayee', 'vinny']
subjects = ['Python', 'Java', 'Blockchain']
def people_list(num):
results = []
for i in range(num):
person = {
'id': i,
'name': random.choice(names),
'subject': random.choice(subjects)
}
results.append(person)
return results
def generate_people_list(num):
for i in range(num):
person = {
'id': i,
'name': random.choice(names),
'subject': random.choice(subjects)
}
yield person
# See the performance difference between both approach.
t1 = time.clock()
people = people_list(10000)
t2 = time.clock()
print('Time taken : ', t2 - t1)
t1 = time.clock()
people = generate_people_list(10000)
t2 = time.clock()
print('Time taken : ', t2 - t1)
| true
|
bbb15cfc351270d4c09f884ac0e9debb4804aae5
|
NaveenSingh4u/python-learning
|
/basic/python-oops/book.py
| 920
| 4.125
| 4
|
class Book:
def __init__(self, pages):
self.pages = pages
def __str__(self):
return 'The number of pages: ' + str(self.pages)
def __add__(self, other):
total = self.pages + other.pages
b = Book(total)
return b
def __sub__(self, other):
total = self.pages - other.pages
b = Book(total)
return b
def __mul__(self, other):
total = self.pages * other.pages
b = Book(total)
return b
b1 = Book(100)
b2 = Book(200)
b3 = Book(700)
print('Add')
print(b1 + b2)
print(b1 + b3)
print('Sub')
print(b1 - b2)
print('Mul')
print(b1 * b2)
# Note : 1.whenever we are calling + operator then __add__() method will be called.
# 2. Whenever we're printing Book object reference then __str__() method will be called.
print("Printing multiple add ..")
print(b1 + b2 + b3)
print(" add with multiple")
print(b1 * b2 + b2 * b3)
| true
|
062f3ee72daa4387656af289b2ee3bef90e70a1f
|
NaveenSingh4u/python-learning
|
/basic/python-oops/outer.py
| 494
| 4.21875
| 4
|
class Outer:
def __init__(self):
print('Outer class object creation')
def m2(self):
print('Outer class method')
class Inner:
def __init__(self):
print('Inner class object creation')
def m1(self):
print('Inner class method')
# 1st way
o = Outer()
i = o.Inner()
i.m1()
#2nd way
i = Outer().Inner().m1()
#3rd way
Outer().Inner().m1()
# We can't call outer method from inner class object
# i.m2() --> Not possible
o.m2()
| false
|
c1a3ee82f1c10cc499283df4e4e95f00df71dc1b
|
Dhanshree-Sonar/Interview-Practice
|
/Guessing_game.py
| 808
| 4.3125
| 4
|
##Generate a random number between 1 and 9 (including 1 and 9). Ask the user to guess the number,
##then tell them whether they guessed too low, too high, or exactly right.
# Used random module to generate random number
import random
def guessing_game():
while True:
num = 0
while num not in range(1,10):
num = input('Enter number between 1 to 9:')
game_num = random.randint(1,9)
print 'Your Number: ' + str(num)
print 'Generated Number: ' + str(game_num)
if num == game_num:
return 'Congrats!! You guessed it right...'
elif abs(num - game_num) <= 2:
return 'You were so close!'
elif abs(num - game_num) >= 3:
return 'You were not close!'
result = guessing_game()
print result
| true
|
226843bbc68bab71fbe2cfb3416925baa898a273
|
simplex06/clarusway-aws-devops
|
/ozkan-aws-devops/python/coding-challenges/cc-003-find-the-largest-number/largest_number.py
| 270
| 4.25
| 4
|
# The largest Number of a list with 5 elements.
lst = list()
for i in range(5):
lst.append(int(input("Enter a number: ")))
largest_number = lst[0]
for j in lst:
if j > largest_number:
largest_number = j
print("The largest number: ", largest_number)
| true
|
b6baf7354123f5584dde6cb4b45b2647c5ef49f8
|
joaovicentefs/cursopymundo2
|
/exercicios/ex0037.py
| 805
| 4.34375
| 4
|
num = int(input('Digite um número interiro: '))
#Colocando três aspas simples no print é possível fazer múltiplas linhas
print('''Escolha uma das bases para conversão:
[ 1 ] converter para BINÁRIO
[ 2 ] converter para OCTAL
[ 3 ] converter para HEXADECIMAL''')
options = int(input('Sua opção: '))
'''Utilizado o conhecimento de fatiamento de string para ignorar
os dois primeiros dígitos que servem apenas para identificar qual a base numérica'''
if options == 1:
print('{} convertido para BINÁRIO é igual a {}'.format(num, bin(num)[2:]))
elif options == 2:
print('{} convertido para OCTAL é igual a {}'.format(num, oct(num)[2:]))
elif options == 3:
print('{} convertido para HEXADECIMAL é igual a {}'.format(num, hex(num)[2:]))
else:
print('Escolha uma opção de conversão válida!')
| false
|
b86d5d0f2b570cfad3678ce341c44af297399e32
|
N-eeraj/perfect_plan_b
|
/armstrong.py
| 343
| 4.15625
| 4
|
import read
num = str(read.Read(int, 'a number'))
sum = 0 #variable to add sum of numbers
for digit in num:
sum += int(digit) ** len(num) #calculating sum of number raised to length of number
if sum == int(num):
print(num, 'is an amstrong number') #printing true case
else :
print(num, 'is not an amstrong number') #printing false case
| true
|
4b20faae3875ba3a2164f691a4a32e61ca944a27
|
harishassan85/python-assignment-
|
/assignment3/question2.py
| 226
| 4.21875
| 4
|
# Write a program to check if there is any numeric value in list using for loop
mylist = ['1', 'Sheraz', '2', 'Arain', '3', '4']
for item in mylist:
mynewlist = [s for s in mylist if s.isdigit()]
print(mynewlist)
| true
|
df6c709986d91d8d96b4a67e1e20307e05a09521
|
albertsuwandhi/Python-for-NE
|
/Week2/Tuples.py
| 329
| 4.1875
| 4
|
#!/usr/bin/env python3
# Tuples are immutables
my_tuple = (1, 'whatever',0.5)
print("Type of my_tuples : ", type(my_tuple))
for i in my_tuple:
print(i)
#convert tuples to list
my_list = list(my_tuple)
print("Type of my_list : ", type(my_list))
for i in my_list:
print(i)
#list element can be changed
my_list[0] = 100
| false
|
07669066a5ce7a1561da978fc173c710f3ec7e3a
|
neonblueflame/upitdc-python
|
/homeworks/day2_business.py
| 1,836
| 4.21875
| 4
|
"""
Programming in Business. Mark, a businessman, would like to
purchase commodities necessary for his own sari-sari store.
He would like to determine what commodity is the cheapest one
for each type of products. You will help Mark by creating a
program that processes a list of 5 strings. The format will
be the name of the commodity plus its price (<name>-<price>).
Author: Sheena Dale Mariano
Date created: 20190830
"""
commodities = [
"Sensodyne-100, Close Up-150, Colgate-135",
"Safeguard-80, Protex-50, Kojic-135",
"Surf-280, Ariel-350, Tide-635",
"Clover-60, Piatos-20, Chippy-35",
"Jelly bean-60, Hany-20, Starr-35"
]
def get_price(commodity):
return int(commodity.split("-")[1])
def get_cheapest(commodities):
cheapest = commodities[1]
cheapest_price = get_price(commodities[1])
for item in commodities:
price = get_price(item)
if price <= cheapest_price:
cheapest_price = price
cheapest = item
return cheapest, cheapest_price
def get_cheapest_commodities(commodities):
commodity_arr = []
for commodity in commodities:
commodity_arr.append(commodity)
items_arr = []
for commodity in commodity_arr:
items_arr.append(commodity.split(", "))
total_price = 0
cheapest_commodities = []
for items in items_arr:
cheapest_item, cheapest_price = get_cheapest(items)
total_price += int(cheapest_price)
cheapest_commodities.append(cheapest_item)
return total_price, cheapest_commodities
############################################################
for commodity in commodities:
print(commodity)
print()
total, cheapest = get_cheapest_commodities(commodities)
print(f"Cheapest: { ', '.join(cheapest) }")
print(f"Total: { total }")
| true
|
cdc3ed9862e362dc21b899ef3b059a6a9889d6ee
|
RobSullivan/cookbook-recipes
|
/iterating_in_reverse.py
| 938
| 4.53125
| 5
|
# -*- coding: utf-8 -*-
"""
This is a quote from the book:
Reversed iteration only works if the object in question has a size
that can be determined or if the object implements
a __reversed__() special method. If neither of these can be
satisfied, you’ll have to convert the object into a list first.
Be aware that turning an iterable into a list could consume a
lot of memory if it’s large.
Defining a reversed iterator makes the code much more efficient,
as it’s no longer necessary to pull the data into a list and
iterate in reverse on the list.
"""
class Countdown:
def __init__(self, start):
self.start = start
#Forward iterator
def __iter__(self):
n = self.start
while n > 0:
yield n
n -= 1
#Reverse iterator
def __reversed__(self):
n = 1
while n <= self.start:
yield n
n += 1
if __name__ == '__main__':
c = Countdown(5)
for n in reversed(c):
print(n)
| true
|
b4ff9851641f8baea2c54f7dd16f206db16827de
|
isachard/console_text
|
/web.py
| 1,633
| 4.34375
| 4
|
"""Make a program that takes a user inputed website and turn it into console text.
Like if they were to take a blog post what would show up is the text on the post
Differents Links examples:
https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world
https://www.stereogum.com/2025831/frou-frou-reuniting-for-2019-tour/tour-dates/
https://medium.freecodecamp.org/dynamic-class-definition-in-python-3e6f7d20a381
"""
from scrapy import simple_get
from bs4 import BeautifulSoup
# Summary of the script:
# Basically, takes the url from the user
# checks if the url is valid (OK 200 response)
# then with the help of beautifulsoup library transform the url to a pretify html ready to extract specific content
# Because depending on the class, id and naming the content of the post may vary
# I provide a couple of examples and a simple method that checks commoms naming for the post content
# After finding the correct the specific tag the library will extract only the text wiht the '.text' call
if __name__ == '__main__':
def check_content_div(html):
if html.find(class_= "post_body"):
return html.find(class_= "post_body").text
if html.find(class_= "section-content"):
return html.find(class_= "section-content").text
if html.find(class_= "article-content clearfix"):
return html.find(class_= "article-content clearfix").text
url = input("Hello user enter your BlogPost: ")
raw_html = simple_get(url)
html = BeautifulSoup(raw_html, 'html.parser')
content = check_content_div(html)
print("\n" + content + "\n")
| true
|
d89df8cc1bffb63dd1f867650b54c55e141602ed
|
yuch7/CSC384-Artificial-Intelligence
|
/display_nonogram.py
| 2,535
| 4.125
| 4
|
from tkinter import Tk, Canvas
def create_board_canvas(board):
"""
Create a Tkinter Canvas for displaying a Nogogram solution.
Return an instance of Tk filled as a grid.
board: list of lists of {0, 1}
"""
canvas = Tk()
LARGER_SIZE = 600
# dynamically set the size of each square based on cols and rows
n_columns = len(board[0])
n_rows = len(board)
divide = max(n_columns, n_rows)
max_size = LARGER_SIZE / divide
canvas_width = max_size * n_columns
canvas_height = max_size * n_rows
# create the intiial canvas with rows and columns grid
canvas.canvas = Canvas(
canvas, width=canvas_width, height=canvas_height,
borderwidth=0, highlightthickness=0)
canvas.title("Nonogram Display")
canvas.canvas.pack(side="top", fill="both", expand="true")
canvas.rows = len(board)
canvas.columns = len(board[0])
canvas.cell_width = max_size
canvas.cell_height = max_size
canvas.rect = {}
canvas.oval = {}
insert_canvas_grid(canvas, board)
return canvas
def insert_canvas_grid(canvas, board):
"""
Insert black and white squares onto a canvas depending on the
values inside of the board. A value of 1 corresponds to a black
square, while a value of 0 corresponds to a white squre.
canvas: Tk object
board: list of lists of {0, 1}
"""
# generate the visual board by iterating over board
for column in range(len(board[0])):
for row in range(len(board)):
x1 = column * canvas.cell_width
y1 = row * canvas.cell_height
x2 = x1 + canvas.cell_width
y2 = y1 + canvas.cell_height
# set the tile to black if it's a solution tile
if board[row][column] == 1:
canvas.rect[row, column] = canvas.canvas.create_rectangle(
x1, y1, x2, y2, fill="black")
else:
canvas.rect[row, column] = canvas.canvas.create_rectangle(
x1, y1, x2, y2, fill="white")
def display_board(board):
"""
Takes in a final nonogram board, and creates the visual
representation of the board using NonogramDisplay.
A value of one inside of our nonogram representation
means that the associated tile is colored.
board: a list of lists (each list is a row)
example:
>>> display_board([[0, 1, 0],
[1, 1, 0],
[1, 0, 0]])
"""
app = create_board_canvas(board)
app.mainloop()
| true
|
9d7c458469e1303571f12dfa15fa71133c5d2355
|
suterm0/Assignment9
|
/Assignment10.py
| 1,439
| 4.34375
| 4
|
# Michael Suter
# Assignment 9 & 10 - checking to see if a string is the same reversable
# 3/31/20
def choice():
answer = int(input("1 to check for a palindrome, 2 to exit!>"))
while answer != 1 and 2:
choice()
if answer == 1:
punc_string = input("enter your string>")
return punc_string
else:
if answer == 2:
exit()
def punctuation_check(punc_string):
string = ''
if not punc_string.isalpha():
for char in punc_string:
if char.isalpha():
string += char
print(string)
return string
else:
string = punc_string
return string
def palindrome_check(string):
string = string.lower()
length = int(len(string)) # gets the number of characters in the string
if length == 0 or length == 1:
return print("This is a palindrome,", True)
elif string[0] != string[-1]: # if first [0] and last letter [`]are not the same then its not a palindrome
return print("This is not a palindrome,", False)
else:
return palindrome_check(string[1:-1])
# You need to get the input from the user in a loop so it can happen multiple times
print("Type your word to see if it is a palindrome")
punctuations = ''' !/?@#$;,()-[]{}<>./%^:'"&*_~ '''
# Your punctuation check returns a value
i = choice()
value = punctuation_check(i)
result = palindrome_check(value)
print(result)
| true
|
0f185d16ad186bc44dca5dd7d7dc338c2243f583
|
chng3/Python_work
|
/第五章练习题/5-2.py
| 703
| 4.15625
| 4
|
#5-1 条件测试
myday = 'Thursday'
print("Is mayday == 'Thursday'? I predict True.")
print(myday == 'Thursday')
print("\nIs myday == 'Sunday'? I predict False.")
print(myday == 'Sunday')
print("\n")
#5-2
year_0 = 12
year_1 = 13
print(year_0 == year_1)
print(year_0 != year_1)
print(year_0 > year_1)
print(year_0 < year_1)
print(year_0 <= year_1)
print(year_0 >= year_1)
print("\n")
name = 'James'
print(name.lower() == 'james')
print("\n")
year_0 = 18
year_1 = 22
print(year_0 <=22 and year_1 <=22)
year_0 = 25
print(year_0 <=21 or year_1 <=21)
numbers = [12, 34, 44, 44]
number_0 = 22
number_1 = 12
if number_1 in numbers:
print("True")
if number_0 not in numbers:
print("True")
| false
|
3c3bbefb54ddf8e30798a9115ba4de97aca0d396
|
chng3/Python_work
|
/第四章练习题/4-12.py
| 719
| 4.46875
| 4
|
#4-10
my_foods = ['pizza', 'falafel', 'carrot cake', 'chocolate']
print("The first three items in the list are:")
print(my_foods[:3])
print("Three items from the middle of the list are:")
print(my_foods[1:3])
print("The last items in the list are:")
print(my_foods[-3:])
#4-11 你的披萨和我的披萨
pizzas = ['tomato', 'banana', 'apple']
friend_pizzas = pizzas[:]
pizzas.append('hotdog')
friend_pizzas.append('pineapple')
print("My favorite pizzas are:")
for pizza in pizzas[:]:
print(pizza)
print("My friend's favorite pizzas are:")
for friend_pizza in friend_pizzas[:]:
print(friend_pizza)
#4-12
foods = ['pizza', 'falafel', 'carrot cake', 'ice cream']
for food in foods[:]:
print(food)
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.