blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
ffa49bbf0efab59dfd37036a488c256f1dbefbff | Michael-Zagon/ICS3U-Unit3-04-Python | /positive_o_negative.py | 573 | 4.3125 | 4 | #!/usr/bin/env python3
# Created by: Michael Zagon
# Created on: Sep 2021
# This program determines if a number is positive, negative or neutral.
def main():
# This function determines if a number is positive, negative or neutral.
# Input
integer = int(input("Enter an integer: "))
print("")
# Process and output
if integer > 0:
print("This is a positive number")
elif integer < 0:
print("This is a negative number")
else:
print("This is a neutral number")
print("\nDone.")
if __name__ == "__main__":
main()
| true |
07b32531a0ecd9e6e2c40cd54b7b8ce4c60e395c | AnupamKP/py-coding | /array/compstr_sort.py | 741 | 4.25 | 4 | '''
Given a list of non negative integers, arrange them such that they form the largest number.
For example:
Given [3, 30, 34, 5, 9], the largest formed number is 9534330.
Note: The result may be very large, so you need to return a string instead of an integer.
'''
from functools import cmp_to_key
def comparestr_sort(A: list) -> str:
def custom_compare(num1: int, num2:int) -> int:
left_val = int(str(num1)+str(num2))
right_val = int(str(num2)+str(num1))
if left_val > right_val:
return -1
else:
return 1
A.sort(key=cmp_to_key(custom_compare))
return "0" if A[0] == 0 else "".join(map(str,A))
if __name__ == "__main__":
A = [8,89]
print(comparestr_sort(A)) | true |
a498e72a6232e6bac2fe8995f50b5d738b698ff9 | AnupamKP/py-coding | /tree/trie.py | 1,416 | 4.1875 | 4 | class Trie:
class Node:
def __init__(self):
self.child_node = [None]*26
self.is_end = False
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = self.Node()
def char_to_index(self,ch):
return ord(ch) - ord('a')
def insert_word(self, word: str) -> None:
"""
Adds a word into the data structure.
"""
curr = self.root
for char in word:
index = self.char_to_index(char)
if not curr.child_node[index]:
curr.child_node[index] = self.Node()
curr = curr.child_node[index]
curr.is_end = True
def search_word(self, word: str) -> bool:
"""
Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
"""
curr = self.root
if '.' not in word:
for char in word:
index = self.char_to_index(char)
if not curr.child_node[index]:
return False
curr = curr.child_node[index]
else:
return False
return curr != None and curr.is_end
if __name__ == "__main__":
trie = Trie()
trie.insert_word('anupam')
trie.insert_word('pathi')
print(trie.search_word('pathi')) | true |
c9a47c3098275053913b79a77407439278a65759 | AnupamKP/py-coding | /string/already_palindrome.py | 582 | 4.21875 | 4 | '''
Given a string A consisting of lowercase characters.
We need to tell minimum characters to be appended (insertion at end) to make the string A a palindrome.
Example Input
Input 1:
A = "abede"
Input 2:
A = "aabb"
Example Output
Output 1:
2
Output 2:
2
'''
def min_append_to_palindrome(A: str) -> int:
len_A = len(A)
for i in range(len_A):
temp_str = A[i:]
if temp_str == temp_str[::-1]:
return len_A - (len_A - i)
return 1
if __name__ == "__main__":
A = "aabb"
print(min_append_to_palindrome(A)) | true |
6ab7976a2004c99514d9e907328c38ed57011d01 | anshu-vijay/Python | /BasicPrograms/list.py | 1,445 | 4.21875 | 4 |
print("**********************************************")
fruits = ['apple','mango',1,5,'@']
print("length of fruits list",len(fruits)) #length of list
print(fruits[2]) #printing a particular element
fruits[2] = 'banana' #adding new element
print(fruits) # printing list
print("*********************************************")
paragraph = "Global warming is a term used for the observed century-scale rise in the average temperature of " \
"the Earth's climate system and its related effects. Scientists are more than 95% certain that nearly all of global warming is caused by increasing concentrations of greenhouse gases (GHGs) and other human-caused emissions."
print("Length of paragraph : " ,len(paragraph))
print("paragraph to list: ",list(paragraph))
print("legth of paragraph list: ",len(list(paragraph)))
print("with single space: ",list(paragraph.split(" ")))
print("Length with single space: ",len(list(paragraph.split(" "))))
print("Length with multiple spaces: ",list(paragraph.split()))
print("Length with multiple spaces : ",len(list(paragraph.split())))
print("Counting the in paragraph: ",paragraph.count("the"))
print("Does paragraph contains effects?: ",paragraph.__contains__('effects'))
print("with single space: effects?: ",'effects' in paragraph)
print("*********************************************")
print(list("computer"))
car =("audi","merc","skoda","rangerover")
print("Tuple to List: ",list(car))
| true |
4fc4f76bca08d22d80e372e869a51cc6f683e9aa | ArifRezaKhan/pythonBasicProgramExamples | /Interest.py | 620 | 4.15625 | 4 | # Taking input for principle, rate and time
principle = float(input("Enter the principle amount: "))
rate = float(input("Enter percent of rate of interest: "))
time = float(input("Enter time in years: "))
# Calculating Simple Interest
def simple_interest():
si = (principle * rate * time) / 100
print("The simple interest on principle ", principle, "is", si)
# Calculating Complex Interest
def complex_interest():
ci = principle * (pow((1 + rate / 100), time))
print("The complex interest on principle ", principle, "is", ci)
# Driver Code
simple_interest()
complex_interest()
| true |
454a50185054716682d5557647da102d8c868166 | felipesch92/PythonExercicios | /ex083.py | 458 | 4.15625 | 4 | # Crie um programa onde o usuário digite uma expressão qualquer
# que use parênteses. Seu aplicativo deverá analisar se a expressão
# passada está com os parênteses abertos e fechados na ordem correta.
exp = input('Digite a expressão: ')
cont = 0
for c in exp:
if c == '(':
cont += 1
if c == ')':
cont -= 1
if cont == 0:
print(f'A expressão {exp} está correta! ')
else:
print(f'A expressão {exp} está incorreta!')
| false |
8cb3770023a410617e4330579ecdedfddb3c0f4f | felipesch92/PythonExercicios | /ex036.py | 803 | 4.21875 | 4 | #Exercício Python 36: Escreva um programa para aprovar o empréstimo
# bancário para a compra de uma casa. Pergunte o valor da casa,
# o salário do comprador e em quantos anos ele vai pagar.
# A prestação mensal não pode exceder 30% do salário ou então
# o empréstimo será negado.
v_casa = float(input('Digite o valor do imóvel: R$ '))
v_sal = float(input('Digite o valor do seu salário: R$ '))
q_anos = int(input('Em quantos anos deseja pagar? '))
p_men = v_casa / (q_anos * 12)
if v_sal * 0.3 >= p_men:
print('Parabéns empréstimo aprovado!')
print('Você irá pagar {} prestaçoes no valor de R$ {:.2f}!'.format(q_anos * 12, p_men))
else:
print('A prestação de R$ {:.2f} excede os 30% do seu salário de R$ {:.2f}'.format(p_men, v_sal))
print('Empréstimo reprovado.')
| false |
03492348ad0a85c12f85fddea8242163bc75f62c | felipesch92/PythonExercicios | /ex053.py | 419 | 4.21875 | 4 | #Crie um programa que leia uma frase qualquer e diga se ela é um
# palíndromo, desconsiderando os espaços. Exemplos de palíndromos:
#APOS A SOPA, A SACADA DA CASA, A TORRE DA DERROTA,
# O LOBO AMA O BOLO, ANOTARAM A DATA DA MARATONA.
f = input('Digite a frase: ').upper().replace(' ', '')
if f == f[::-1]:
print('A frase digitada é um palíndromo!')
else:
print('A frase digitada não é um palíndromo!')
| false |
5344b5bbcf6dc6a94f5b9cb38405fba1b2f4593a | felipesch92/PythonExercicios | /ex102.py | 869 | 4.28125 | 4 | # Crie um programa que tenha uma função fatorial() que receba dois parâmetros:
# o primeiro que indique o número a calcular e outro chamado show, que será um
# valor lógico (opcional) indicando se será mostrado ou não na tela o processo de cálculo do fatorial.
def fatorial(num, mostra=True):
"""
-> Função para calculo do fatorial de um número
:param num: número a ser fatorado
:param mostra: se irá mostrar o calculo ou somente o resultado final.
:return:
"""
i = 1
l_fatorial = ''
for x in range(num, 1, -1):
i *= x
if mostra:
print(f'{x} *', end=' ')
l_fatorial += f'{x} * '
if mostra:
print(f'1 = {i}')
l_fatorial += f'1 = {i}'
else:
print(f'Resultado final: {i}')
return l_fatorial
print(fatorial(5))
fatorial(10, False)
help(fatorial)
| false |
c78c91acccdd7fb7dce2b374f26d55c0cca2549f | Garyg0/jobeasy-python-course | /lesson_3/homework_3_1.py | 1,110 | 4.1875 | 4 | # FOR LOOPS EXERCISES
# Ex. 1
# Enter your name, save it in name variable and save in result_1 variable your name repeated 3 times (use loops)
name_1 = 'Gary'
result_1 = ''
for _ in range(3):
result_1 += name_1
# TODO: Here is your code
# Ex. 2
# Modify your previous program so that it will enter your name (save it in variable name_2) and a number
# (save in variable number) and then save in result_2 variable your name repeated as many times as number_1 is
# (use loops)
name_2 = 'Gary'
number_1 = 7
result_2 = ''
for _ in range(number_1):
result_2 += name_1
# TODO: Here is your code
# Ex. 3
# Enter a random string, which includes only digits. Write code which find a sum of digits in this string and save it
# into result_3 variable
string_number_1 = '13256798'
result_3 = 0
for digit in string_number_1:
result_3 += int(digit)
# TODO: Here is your code
# Ex. 4
# Create code which sums up all even numbers between 2 and 100 (include 100) and save it in result_4 variable
result_4 = 0
for number in range(2, 101, 2):
result_4 += number
# TODO: Here is your code | true |
85c562dab5ded76904021eab63bd6a1eb219cc7d | NallamilliRageswari/Python | /Prime_Factors.py | 294 | 4.125 | 4 | import math
def prime_factors(n):
while (n%2==0):
print(2)
n=n/2
for i in range(3,int(math.sqrt(n))+1,2):
while(n%i==0):
print(i)
n=n/i
if(n>2):
print(int(n))
num=int(input("enter a number: "))
prime_factors(num)
| false |
8f5dae8956458fdedebabd24b5b29de85ba2fdc4 | NallamilliRageswari/Python | /Triangle_Quest.py | 702 | 4.1875 | 4 | '''
You are given a positive integer N. Print a numerical triangle of height N-1 like the one below:
1
22
333
4444
55555
......
Can you do it using only arithmetic operations, a single for loop and print statement?
Use no more than two lines. The first line (the for statement) is already written for you. You have to complete the print statement.
Note: Using anything related to strings will give a score of 0.
Input Format
A single line containing integer, N.
Constraints
1<=N<=9
Output Format
Print N-1 lines as explained above.
Sample Input
5
Sample Output
1
22
333
4444
'''
#PROGRAM:
n=int(input())
for i in range(1,n):
print((10**(i)//9)*i)
| true |
046ab8adc03054778e63b098037a1434f05addb0 | NallamilliRageswari/Python | /Frequency_compute.py | 792 | 4.21875 | 4 | '''
5. Write a program to compute the frequency of the words from the input. The output should output after sorting the key alphanumerically.
Suppose the following input is supplied to the program:
New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3.
Then, the output should be:
2:2
3.:1
3?:1
New:1
Python:5
Read:1
and:1
between:1
choosing:1
or:2
to:1
'''
a=input()
l=a.split()
l.sort()
b=[]
count1=[]
for i in l:
if(i not in b):
b.append(i)
count1.append(l.count(i))
for i in range(len(b)):
print(b[i],":",count1[i])
'''
f={}
a=input().split()
for i in a:
f[i]=a.count(i)
res = list(f.keys())
res.sort()
for j in res:
print(j+':',a.count(j))
'''
| true |
9649e8991dc397236ee70639acafcbb84a6977b0 | NallamilliRageswari/Python | /countEvenOdd.py | 374 | 4.1875 | 4 | #To check count of even and odd in given number.
def countEvenOdd(n):
even_count,odd_count=0,0
while(n):
r=n%10
n=n//10
if(r%2==0):
even_count+=1
else:
odd_count+=1
print("odd count--",odd_count, "and", "even count--",even_count)
n=int(input("Enter a number--"))
countEvenOdd(n)
| true |
3e78961161e29e7421398506f065e726a6512e75 | NallamilliRageswari/Python | /Exceptions.py | 1,809 | 4.46875 | 4 | '''
Exceptions
Errors detected during execution are called exceptions.
Examples:
ZeroDivisionError
This error is raised when the second argument of a division or modulo operation is zero.
>>> a = '1'
>>> b = '0'
>>> print int(a) / int(b)
>>> ZeroDivisionError: integer division or modulo by zero
ValueError
This error is raised when a built-in operation or function receives an argument that has the right type but an inappropriate value.
>>> a = '1'
>>> b = '#'
>>> print int(a) / int(b)
>>> ValueError: invalid literal for int() with base 10: '#'
To learn more about different built-in exceptions click here.
Handling Exceptions
The statements try and except can be used to handle selected exceptions. A try statement may have more than one except clause to specify handlers for different exceptions.
#Code
try:
print 1/0
except ZeroDivisionError as e:
print "Error Code:",e
Output
Error Code: integer division or modulo by zero
Task
You are given two values a and b.
Perform integer division and print a/b.
Input Format
The first line contains T, the number of test cases.
The next T lines each contain the space separated values of a and b.
Constraints
* 0<T<10
Output Format
Print the value of a/b.
In the case of ZeroDivisionError or ValueError, print the error code.
Sample Input
3
1 0
2 $
3 1
Sample Output
Error Code: integer division or modulo by zero
Error Code: invalid literal for int() with base 10: '$'
3
Note:
For integer division in Python 3 use //.
'''
# PROGRAM :
n=int(input())
for i in range(n):
try:
a,b=input().split()
print(int(a)//int(b))
except ZeroDivisionError as e:
print ("Error Code:",e)
except ValueError as e:
print("Error Code:",e)
| true |
36202f2dd05bd48043aac4458b4650ef921eb3b8 | asierblaz/PythonProjects | /Blukleen Ariketak/EskatuBatHamar.py | 269 | 4.21875 | 4 | '''
03/12/2020 Asier Blazquez
Make a program that asks the number between 1 and 10.
If the number is out of range the program should display "invalid number".
'''
n= int(input("Sartu zenbaki bat: "))
if(n<1 or n>10):
print("invalid number") | true |
77601d6d1fdb3979eaf09328d653d007f27ad8c9 | austin-chou/learn-coding | /tests.py | 2,771 | 4.21875 | 4 | """
A collection of tests to ensure classes are implemented and functioning correctly
"""
from linked_list import Node, Linked_List
from queue import Queue
def test_linked_list():
"""
Code to test each part of the linked list class
"""
# empty()
ll = Linked_List()
assert ll.empty() == True
ll.head = Node(3)
assert ll.empty() == False
# next_is_empty()
assert ll.head.next_is_empty() == True
ll.head.tail = Node(4)
assert ll.head.next_is_empty() == False
# size()
ll.head.tail.tail = Node(5)
assert ll.size() == 3
assert Linked_List().size() == 0
size_one = Linked_List()
size_one.head = Node(18)
assert size_one.size() == 1
# value_at()
assert ll.value_at(0) == 3
assert ll.value_at(1) == 4
assert ll.value_at(2) == 5
assert ll.value_at(3) == "IndexError: Index is too large or incorrect. Should be an integer less than size of linkedlist"
# push_front()
ll.push_front(2)
assert ll.value_at(0) == 2
assert ll.value_at(1) == 3
assert ll.value_at(2) == 4
assert ll.value_at(3) == 5
assert ll.size() == 4
# pop_front()
front_value = ll.pop_front()
assert front_value == 2
assert ll.size() == 3
assert ll.value_at(0) == 3
# push_back()
ll.push_back(6)
assert ll.size() == 4
assert ll.value_at(3) == 6
# pop_back()
back_value = ll.pop_back()
assert ll.size() == 3
assert back_value == 6
# front()
front_value = ll.front()
assert front_value == 3
assert ll.size() == 3
# back()
back_value = ll.back()
assert back_value == 5
assert ll.size() == 3
# insert_at()
ll.insert_at(0, 2)
assert ll.size() == 4
assert ll.value_at(0) == 2
ll.insert_at(1, 2.5)
assert ll.size() == 5
assert ll.value_at(1) == 2.5
assert ll.value_at(2) == 3
# erase()
ll.remove(0)
assert ll.size() == 4
assert ll.value_at(0) == 2.5
ll.remove(1)
assert ll.size() == 3
assert ll.value_at(1) == 4
# value_n_from_end()
n = ll.value_n_from_end(0)
assert n == 5
assert ll.size() == 3
# reverse()
reversed = ll.reverse()
assert reversed.size() == 3
assert reversed.value_at(0) == 5
assert reversed.value_at(1) == 4
assert reversed.value_at(2) == 2.5
# remove_value(value)
reversed.remove_value(4)
assert reversed.size() == 2
assert reversed.value_at(0) == 5
assert reversed.value_at(1) == 2.5
def test_queue():
test_queue = Queue(4)
assert test_queue.full() == False
assert test_queue.empty() == True
test_queue.enqueue(0)
test_queue.enqueue(1)
test_queue.enqueue(2)
assert test_queue.full() == True
assert test_queue.dequeue() == 0
| true |
59d6c8dca1fecd976cc412a20b8c690489a6cbc1 | freizl/freizl.github.com | /codes/python/learning_python/Part5/class_basic.py | 1,076 | 4.21875 | 4 |
class FirstClass:
def setdata(self, value):
self.data = value
def display(self):
print "data value at FirstClass: %s " % self.data
class SecondClass(FirstClass):
def display(self):
print "data value at Second Class: %s" % self.data
class ThirdClass(SecondClass):
def __init__(self, value):
self.data = value
def __add__(self, other):
return ThirdClass(self.data + other)
def __mul__(self, other):
self.data = self.data * other
def first_class_test():
print "="*8,"I am the first class tester ..."
x = FirstClass()
y = FirstClass()
x.setdata("King Arthur")
y.setdata(3.1415)
FirstClass.data = "none"
x.display()
y.display()
def second_class_test():
print "="*8, "I am the second class tester ..."
x = FirstClass()
x.setdata("default value")
z = SecondClass()
z.setdata(42)
z.display()
x.display()
def third_class_test():
print "="*8, "I am the second class tester ..."
a = ThirdClass("abc")
a.display()
b = a + "xyz"
b.display()
a * 3
a.display()
if __name__ == "__main__":
first_class_test()
second_class_test()
third_class_test()
| true |
85e4039dad54d17b7095c1eb200c56953b01a421 | freizl/freizl.github.com | /codes/python/lang/gy.py | 546 | 4.125 | 4 | #!/usr/bin/python
# yieldex.py example of yield, return in generator functions
def gy():
print "start gy fun"
x = 2
y = 3
print " ... init x and y"
yield x,y,x+y
print "finish first yield"
z = 12
yield z/x
print "finish second yield"
print z/y
print "end gy fun"
return
def main():
print "== start main"
g = gy()
print "== init gy and first next"
print g.next() # prints x,y,x+y
print "== second next"
print g.next() # prints z/x
print "== third next"
print g.next()
if __name__ == '__main__':
main()
| false |
5ce53e0134f082f21b5527df3add87e104dffb2c | rindhaf/praxis-academy | /novice/01-01/kasus/mergesort.py | 1,021 | 4.21875 | 4 | def merge_sort(alist, start, end):
'''Sorts the list from indexes start to end - 1 inclusive.'''
if end - start > 1:
mid = (start + end)//2
merge_sort(alist, start, mid)
merge_sort(alist, mid, end)
merge_list(alist, start, mid, end)
def merge_list(alist, start, mid, end):
left = alist[start:mid]
right = alist[mid:end]
r = start
i = 0
n = 0
while (start + i < mid and mid + n < end):
if (left[i] <= right[n]):
alist[r] = left[i]
i = i + 1
else:
alist[r] = right[n]
n = n + 1
r = r + 1
if start + i < mid:
while r < end:
alist[r] = left[i]
i = i + 1
r = r + 1
else:
while r < end:
alist[r] = right[n]
r = r + 1
n = n + 1
alist = input('Enter the list of numbers: ').split()
alist = [int(x) for x in alist]
merge_sort(alist, 0, len(alist))
print('Sorted list: ', end='')
print(alist)
| true |
90a45954ebc6d4b3674c047322cb7ca5db29a839 | dmitrydoni/gb-algorithms-and-data-structures | /lesson-02/lesson_2_task_3.py | 488 | 4.3125 | 4 | """
Сформировать из введенного числа обратное по порядку входящих в него цифр и вывести на экран.
Например, если введено число 3486, надо вывести 6843.
"""
num_reversed = 0
num = int(input("Please enter a number: "))
while num > 0:
right_digit = num % 10
num_reversed = num_reversed * 10 + right_digit
num = num // 10
print(f'Reversed number: {num_reversed}')
| false |
1f7a34e9ced465e814a52b0e6c80de74450188a7 | dmitrydoni/gb-algorithms-and-data-structures | /lesson-02/lesson_2_task_2.py | 501 | 4.375 | 4 | """
Посчитать четные и нечетные цифры введенного натурального числа.
Например, если введено число 34560, в нем 3 четные цифры (4, 6 и 0) и 2 нечетные (3 и 5).
"""
even = 0
odd = 0
num = int(input("Please enter a number: "))
while num > 0:
digit = num % 10
if digit % 2 == 0:
even += 1
else:
odd += 1
num //= 10
print(f'Even digits: {even}\nOdd digits: {odd}')
| false |
eef1373fdb0c9100e034a4c8e8ca5d6e00d69ca0 | dmitrydoni/gb-algorithms-and-data-structures | /lesson-03/lesson_3_task_3.py | 924 | 4.25 | 4 | """
В массиве случайных целых чисел поменять местами минимальный и максимальный элементы.
"""
import random
arr = [random.randint(-100, 100) for _ in range(10)]
print("Randomly generated array: ", arr)
max_element = arr[0]
min_element = arr[0]
max_element_idx = 0
min_element_idx = 0
for n in arr:
if n > max_element:
max_element = n
max_element_idx = arr.index(max_element)
for n in arr:
if n < min_element:
min_element = n
min_element_idx = arr.index(min_element)
print(f'Max element: {max_element}, index: {max_element_idx}')
print(f'Min element: {min_element}, index: {min_element_idx}')
min_max_swap_arr = arr[:]
min_max_swap_arr[max_element_idx] = arr[min_element_idx]
min_max_swap_arr[min_element_idx] = arr[max_element_idx]
print("\nArray with swapped Min and Max elements: ", min_max_swap_arr)
| false |
abcc9984430e9a330085e4a4b9e34a25e07b21e7 | dmitrydoni/gb-algorithms-and-data-structures | /lesson-01/lesson_1_task_5.py | 560 | 4.21875 | 4 | '''
Пользователь вводит номер буквы в алфавите. Определить, какая это буква.
'''
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
letter_number = int(input("Please enter letter number (1...26): "))
if 0 < letter_number < 27:
alphabet_index = letter_number - 1
print("Letter: ", alphabet[alphabet_index])
else:
print("Invalid number. Please note that English alphabet consists of 26 letters.") | false |
0ebe3691987efd3cfcf495765740308516138611 | Gabrielonch/Prueba-Tecnica | /naves_espaciales.py | 1,688 | 4.125 | 4 | suma = 0 # Se crea la variable donde se guardaran los números que sean múltiplos de 3 o 5.
for it in range(1000): # Iterador que va de 0 a 999
if (it % 3 == 0 or it % 5 == 0): # Condición que sólo admite los valores que sean múltiplos de 3 o 5
suma = suma + it # Se agregan los valores que sean múltiplos a la variable suma
print('The sum of all the multiples of 3 or 5 below 1000 is =', suma)
import pandas as pd #Para este ejercicio se ocupara la librería de Pandas y sus funciones en cuanto a fechas y tiempo.
inicio = "1901-1-1" # Fecha de inicio del siglo 20
fin = "2000-12-31" # Fecha de fin de siglo 20
lista_fechas = pd.Series(pd.date_range(start = inicio, end = fin , freq="d")) # pd.Series da formato de una serie de datos
# pd.data_range crea una serie de datos en formato datetime desde una fecha de inicio hasta una fecha final que
# debe ser colocada por el usuario. freq="d" hace referencia a que nos interesa saber las fechas que hay desde el
# inicio al final día por día. Esta frecuencia puede ser cambiada dependiendo el rango de interes del usuario.
#lista_fechas = pd.DataFrame(pd.Series(pd.date_range(start = inicio, end = fin , freq="d")))
#lista_fechas.columns = ['date']
primero = lista_fechas[(lista_fechas.dt.day_name() == "Sunday") & (lista_fechas.dt.day == 1)] # En esta línea
# de código se obtienen las fechas que coincidan con la condición de que el día sea domingo y corresponda al
# primer día del mes. El comando "dt" nos permite acceder a el día, mes o año de una variable en formato datetime.
print("There are",primero.shape[0], "Sundays that fell on the first of the month during the twentieth century") | false |
69cc4e18ea416b8efda7d46f7463a424d14955c5 | alexshad2015/python_shad | /Markov_text_generator.py | 2,986 | 4.1875 | 4 | import random
import pickle
def choose_next_by_previous_one_word(current_word, two_words_statistic):
selection = [word for word in two_words_statistic if word[0] == current_word]
candidates = []
if len(selection) > 0:
candidates = [word[1] for word in selection if \
two_words_statistic[word] == max([two_words_statistic[word] for word in selection])]
return random.choice(candidates)
else:
return ""
def choose_next_by_previous_two_words(tuple_of_words, three_words_statistic):
selection = [word for word in three_words_statistic if (word[0], word[1]) == tuple_of_words]
candidates = []
if len(selection) > 0:
candidates = [word[2] for word in selection if three_words_statistic[word] > \
max([three_words_statistic[word] for word in selection]) - 1]
return random.choice(candidates)
else:
return choose_next_by_previous_one_word(tuple_of_words[1], two_words_statistic)
def create_sentence(one_word_statistic, two_words_statistic, three_words_statistic):
output = []
list_of_signs = [ ".", "!", "?"]
random.shuffle(one_word_statistic)
first = one_word_statistic[0]
while first in list_of_signs or first == "'" or first == " `" or first == " ":
random.shuffle(one_word_statistic)
first = one_word_statistic[0]
second = choose_next_by_previous_one_word(first, two_words_statistic)
if second in list_of_signs:
output.append(first)
output.append(second)
else:
third = choose_next_by_previous_two_words((first, second), three_words_statistic)
if third in list_of_signs:
output.append(first)
output.append(second)
output.append(third)
else:
while third not in list_of_signs:
first, second = second, third
third = choose_next_by_previous_two_words((first, second), three_words_statistic)
output.append(third)
print str(output[0].title()) + " " + " ".join(output[1:-1]) + str(output[-1])
def create_text(number_of_sentence, one_word_statistic, two_words_statistic, three_words_statistic):
while(number_of_sentence):
create_sentence(one_word_statistic, two_words_statistic, three_words_statistic)
number_of_sentence -= 1
if __name__ == "__main__":
with open('C:\\Users\\Alexander\\Downloads\\test\\dickens\\stat\\all_words.pickle', 'r') as result:
one_word_statistic = pickle.load(result)
with open('C:\\Users\\Alexander\\Downloads\\test\\dickens\\stat\\stat_two_words.pickle', 'r') as result:
two_words_statistic = pickle.load(result)
with open('C:\\Users\\Alexander\\Downloads\\test\\dickens\\stat\\stat_three_words.pickle', 'r') as result:
three_words_statistic = pickle.load(result)
create_text(30, one_word_statistic, two_words_statistic, three_words_statistic)
| false |
266eef40f8745d6e9d3b0058ec6ae802f3073532 | JosephComputerScience/Python | /CrackingTheCodingInterview/1.6 compressStringPython.py | 1,234 | 4.40625 | 4 | """Implement a method to perform basic string compression using the counts of repeated characters.
For example, the string aabcccccaaa would become a2b1c5a3.
If the "compressed" string would not become smaller than the original string,
your method should return the original string.
You can assume the string has only uppercase and lowercase letters(a-z)."""
#This function loops through the entire string to count the letters and stores the repeating letter
#into a string and its count into two lists the second lists which holds all the counts if it is all 1's
#then it will return the original string because it cannot be compressed
def compress(string):
if len(string) is 0:
return "No input"
aryS = []
aryI = []
index = 0
count = 0
for x in range(len(string)):
if len(aryS) is 0:
aryS.append(string[x])
if string[x] is aryS[index]:
count += 1
elif string[x] is not aryS[index]:
aryS.append(str(count))
aryI.append(count)
aryS.append(string[x])
count = 1
index += 2
aryS.append(str(count))
for x in aryI:
if x >1:
return "".join(aryS)
return string
| true |
9a105742038e8e9cf3180bb2e29bd3fc83def916 | emstumme/cssi-2010-emstumme | /guessstate.py | 2,464 | 4.28125 | 4 | # >>> game(100)
# Think of a number between 1 and 100. I will think of one, too.
# We will take turns guessing.
# Your guess? 50
# Too low! I guess 23? higher
# Your guess? ...
# ...
# There are five elements to the state of the game:
# number - the number that the user is guessing
# low - the lower bound for the computer's guesses
# high - the upper bound for the computer's guesses
# userwin - has the user won the game?
# compwin - has the computer won the game?
#
# Internally, we represent the state with a dictionary, but clients
# of this API do not know that.
#
# We will use this API for both the recursive and iterative versions.
class State(object):
"""keep the state of the guessing game"""
def __init__(self, number, maxvalue):
"""initial game state has a number and a maxvalue"""
self.number = number
self.low = 1
self.high = maxvalue
self.userwin = False
self.compwin = False
def __str__(self):
"""Print the state as a string"""
return str((self.number, self.low, self.high.
self.userwin, self.compwin))
def create_state(number, maxvalue):
"""return an initial game state with the number and the upper bound"""
return State(number, maxvalue)
return s
return { "number" : number,
"low" : 1,
"high" : maxvalue,
"userwin" : False,
"compwin" : False }
def get_number(state):
"""return the number that the user is trying to guess"""
return state.number
def get_low(state):
"""return the lower bound of the computer's guesses"""
return state.low
def get_high(state):
"""return the upper bound of the computer's guesses"""
return state.high
def get_compwin(state):
"""True iff the computer has won, False otherwise"""
return state.compwin
def get_userwin(state):
"""True iff the user has won, False otherwise"""
return state.userwin
def set_low(state, low):
"""Set the computer's lower bound"""
state.low = low
def set_high(state, high):
"""Set the computer's upper bound"""
state.high = high
def set_compwin_true(state):
"""Set the compwin condition to True"""
state.compwin = True
def set_userwin_true(state):
"""Set the userwin condition to True"""
state.userwin = True
| true |
52c2ce30f9ba40bdd36638092c5a0e5bf31c111d | paritabrahmbhatt/Python-for-Everybody | /Extra Problems/Easy/P010.py | 345 | 4.125 | 4 | #Python program to check whether a number is Prime or not
a = int(input("Enter: "))
def primeornot(a):
for i in range(2,a):
if(i % 2 == 0):
print(a, " is not a prime number")
break
else:
print(a, " is a prime number")
if(a>0):
primeornot(a)
else:
print("Wrong input")
| false |
6adcd04c9b9d55826ad1dfc62420d9313abce731 | ZYY12138dhc/python_demo | /day_01.py | 1,038 | 4.28125 | 4 | print("hello world!")
"""
知识点
1. python2和python3之前有些语句是不通用的。可在shell里面获得一些帮助
2. 查询函数帮助:
help(print)
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
3. 英文输入法,包括标点符号和英文字母
4 Ctrl+N,新建文件[New File]
4. print(" ")print(' ')[打印函数,单引号和双引号都可以]
按F5运行程序,出现*号,提示你要保存
5. >>> [表示提示符,程序已经准备好]
6. 程序可以在新建文件中运行,也可以在shell里面运行,按回车键
"""
| false |
42a8b64867c7081aefbe1bea943bd982527272b9 | ZYY12138dhc/python_demo | /day_13.py | 1,540 | 4.15625 | 4 | """
#eg.1
>>> age = 26
>>> if age < 30:
print('你可以称为一个小年轻!')
你可以称为一个小年轻!
>>>
#eg.2
>>> age = 26
>>> if age < 30:
print('你可以称为一个小年轻!')
print('你真的可以称为一个小年轻!')
SyntaxError: unexpected indent
>>>
>>> age = 26
>>> if age < 30:
print('你可以称为一个小年轻!')
print('你可以称为一个小年轻!')
SyntaxError: invalid syntax
>>>
>>> age = 26
>>> if age < 30:
print('你可以称为一个小年轻!')
print('你可以称为一个小年轻!')
SyntaxError: unindent does not match any outer indentation level
>>>
#eg.3
>>> a=input('来一个数字....')
来一个数字....36
>>> print(a)
36
>>> type(a)
<class 'str'>
>>>
>>> a=int(input('猜猜还记得庄老师的生日吗?'))
猜猜还记得庄老师的生日吗?24
>>> type(a)
<class 'int'>
>>>
"""
#eg.4
a=int(input('猜猜还记得庄老师的生日吗?'))
if a == 728:
print('i am so happy')
if a != 728:
print('i am so angry')
b=int(input('how much 2 plus 3 ? the answer is:'))
if a == 5:
print('bingo!')
if a != 5:
print('stupid')
"""
知识点:
1. if else 语句[判断语句]
1) 按下回车会自动缩进,只有缩进,才表示为一个功能块,四个空格
2)返回结果为真,执行下面语句;返回结果为假,跳过判断语句
3)不是同一个组块会报错,eg.2
2. input语句后面无论输入什么,都是字符串
eg.3
3.
"""
| false |
3fe5e50a93a68b2a8e45806a56cab74ec49ae7ba | ZYY12138dhc/python_demo | /day_07.py | 1,211 | 4.28125 | 4 | """
#eg.1
>>> foods_list=['milk','mango','beer']
>>> sports_list=['football','swimming']
>>> print('my favourite foods :\n',foods_list)
my favourite foods :
['milk', 'mango', 'beer']
>>> print('my favourite sports :\n',sports_list)
my favourite sports :
['football', 'swimming']
>>>
#eg.2
>>> 100*4+45*2+50*4+100*2
890
>>>
#eg.3
>>> str_name='zyy'
>>> str_hello='hello'
>>> str_hello='hello!%s'
>>> print(str_hello % str_name)
hello!zyy
>>>
"""
#eg.4
shop={'cola':4,'hamburger':6.5,'hotdog':3.5,'pizza':16}
a = int(input('cola:'))
b = int(input('hamburger:'))
c = int(input('hotdog:'))
d = int(input('pizza:'))
total_price = a*shop['cola']+b*shop['hamburger']+c*shop['hotdog']+d*shop['pizza']
hint = 'you need pay %s yuan!'
print(hint % total_price)
cola:1
hamburger:5
hotdog:7
pizza:0
you need pay 61.0 yuan!
>>>
"""
阶段性练习
1. 列出自己最喜爱的食物列表和运动项目列表,并且打印
eg.1
2. 算术题
动物园里面有100只大象,45只鸭子,50只鳄鱼,100只小鹿,用python计算全部动物有多少只脚
3. 利用占位符输出自己的名字
#eg.3
4. 可乐[4],汉堡包[6.5],pizza[16],热狗[3.5][强行转换int()]
eg.4
"""
| false |
a4d1c9f07c0a93ceed7ed2c7c6d697638b628652 | thomasbshop/pytutor | /udemyproject/strings.py | 731 | 4.25 | 4 | greetings = "Hello"
name = input("Please enter your name: ")
print(greetings + ' ' + name)
bird = "African eagle"
#print the third character
print(bird[2])
#you can count backwards
print(bird[-4])
#print a slice
print(bird[3:7])
print(bird[3:])
print(bird[:7])
#print skipping in steps
print(bird[1:11:2])
number = "6,364,635,868,121,098,243"
print(number[1::4])
numbers = "0,1,2,3,4,5,6,7,8,9"
print(numbers[0::2])
string1 = "Thats"
string2 = " it!"
print(string1 + string2)
print("Dinning" "at" "the" "high" "table")
#you can multiply strings
print("hello" *8)
#check if a string is a substring of another/useful for searching
today = "Thursday"
print("day" in today)
print("thur" in today) #case sensitive
print("fri" in today) | true |
ac560e5910f83496a2703c26a8de1b285e8d772c | thomasbshop/pytutor | /lists_tuples_ranges/tuples.py | 1,599 | 4.53125 | 5 | # tuples are similar to list but the difference is that they immutable - they cant be changed
# tuples - an ordered set of data
t = "a", "b", "c" # or t = ("a", "b", "c")
print(t)
print("a", "b", "c")
print(("a", "b", "c")) # add brackets when u want to print tuples
welcome = "Welcome to my nightmare", "Alice Copper", 1975
bad = "Bad Company", "Bad Company", 1974
Budgie = "Nightflight", "Budgie", 1981
imelda = "More Mayhem", "Emilda May", 2011
metallica = "Ride the lightning", "Metallica", 1984
print(metallica)
print(metallica[0])
print(metallica[1])
# you cannot make changes with tuples, e.g. item assignment, although tuples support indexing and slicing
imelda = imelda[0], "A change", imelda[2]
print(imelda)
# a type being immutable means u cant change the contents of an object once uve created it but it doesn't mean that your
# variable Can't be assigned a new object of that type, so that's an important clarification here.
# a dictionary key requires immutable objects e.g. tuple
# a list is intended to contain items of the same type - homogenous
# tuples are intended to store heterogenous stuff
# tuples help create robust code
title, artist, year = imelda
print(title)
print(artist)
print(year)
imelda1 = "More Mayhem", "Emilda May", 2011, (
(1, "Pulling the rug"), (2, "psycho"), (3, "Mayhem"), (4, "Kentish Town Waltz"))
title1, artist1, year1, tracks = imelda1
print(title1)
print(artist1)
print(year1)
print(tracks)
# we are using an extra set of parenthesis to to create tuples within a tuple
print("title:{0}, artist: {1}, year: {2}, tracks{3}".format(title1, artist1, year1, tracks))
| true |
7b9898b22c041127be1a41a10a2f87a05b30049a | thomasbshop/pytutor | /udemyproject/helloworld.py | 676 | 4.28125 | 4 | print("Hello world!")
print("1+3")
print(9*8)
print('The end!')
print('we can even include "quotes" in strings.')
print("hello"+"world")
greeting = "Hi there, "
jina = "Thomas"
# greetings
print(greeting + jina)
saslutation = "Mr."
name = input("please input your name")
print(saslutation + '' + name)
splitString = """Using a triple quote
to add a split string"""
print(splitString)
print('''Using tripe-quotes to manage quotations like this one: "Oh my that's Jane's" ''')
#variables and opeerators
a = 24
b = 3
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a // b)
print(a % b)
print(b - a // b + 2 * 2 - 1 + b / a)
for i in range(1, a//b):
print(i)
| true |
cccaa67ea2204403f56ae1d1cf65008f8f33bbdd | arturoromerou/practice_python3 | /listas_numeros.py | 825 | 4.3125 | 4 | """Crear una lista la cual almacene 10 numeros positivos ingresados por el usuario, mostrar en pantalla:
la suma de todos los numeros, el promedio, el numero mayor y el numero menor"""
elemento = int(input("ingrese un valor: "))
if elemento < 0:
print('Error solo numeros positivos')
exit()
lista_numeros = [elemento]
cantidad = len(lista_numeros)
while cantidad <= 9:
elemento = int(input("ingrese un valor: "))
if elemento < 0:
print('Error solo numeros positivos')
exit()
agregar = lista_numeros.append(elemento)
cantidad += 1
print('\nlos valores ingresados son:', lista_numeros)
print('\nla suma es:', sum(lista_numeros))
print('el promedio es:', sum(lista_numeros) / 10)
print('el valor maximo es:', max(lista_numeros))
print('el valor minimo es:', min(lista_numeros)) | false |
9465cfa70c4430efaca5669a19162cd8bd0a82ca | anirudhaps/Python_Programs | /basics/andor.py | 489 | 4.375 | 4 | #and-or study
num = input('Enter any whole number:')
if num>=0 and num<=9:
print 'It is a single digit number'
elif num>=10 and num<=99:
print 'It is a double digit number'
else:
if num<0:
print 'It is a negetive number'
else:
print 'It has three or more digits'
t = num%2
th = num%3
if t==0 or th==0:
print 'The number is divisible by either 2 or 3 or both'
else:
print 'The number is neither divisible by 2 nor by 3'
| true |
52decb44e5daafaaf1634c988d1d1cd110c91b87 | anirudhaps/Python_Programs | /basics/programs/powerN.py | 433 | 4.15625 | 4 | '''
Given base and n that are both 1 or more, compute recursively (no loops) the
value of base to the n power, so powerN(3, 2) is 9 (3 squared).
powerN(3, 1) → 3
powerN(3, 2) → 9
powerN(3, 3) → 27
'''
def powerN(base,n):
if n==0:
return 1
else:
return base * powerN(base,n-1)
b = input('Enter base: ')
p = input('Enter power: ')
print 'powerN(%d,%d) = %d' % (b,p,powerN(b,p))
| true |
2e6cae32a929bae914dc96f288f8e802d5a5f708 | anirudhaps/Python_Programs | /basics/programs/pairStar.py | 571 | 4.125 | 4 | '''
Given a string, compute recursively a new string where identical chars that
are adjacent in the original string are separated from each other by a "*".
pairStar("hello") → "hel*lo"
pairStar("xxyy") → "x*xy*y"
pairStar("aaaa") → "a*a*a*a"
'''
def pairStar(s):
l = len(s)
if l==1:
return s
else:
if s[1]==s[0]:
return s[0] + '*' + pairStar(s[1:])
else:
return s[0] + pairStar(s[1:])
st = raw_input('Enter any string: ')
print 'pairStar output: ' + pairStar(st)
| true |
ce6835888e27014830d3213e67a741773b5a4ecc | anirudhaps/Python_Programs | /practice_basics/char_input.py | 849 | 4.21875 | 4 | """
Create a program that asks the user to enter their name and their age.
Print out a message addressed to them that tells them the year that they will
turn 100 years old.
"""
def read_input():
name = raw_input('Please enter your name: ')
age = input('Enter your age: ')
msg_disp_count = input('Enter message display count: ')
return name, age, msg_disp_count
def print_hund_age_year(name, age, msg_disp_count):
import datetime
# get current date and time
now = datetime.datetime.now()
hundred_age_year = now.year + (100 - age)
msg = 'Hi %s, you will turn 100 years old in year %s' \
% (name, hundred_age_year)
print (msg + ' ') * msg_disp_count
print (msg + '\n') * msg_disp_count
if __name__ == '__main__':
name, age, msg_count = read_input()
print_hund_age_year(name, age, msg_count) | true |
09840350e02ea66f36250bfa1bfac392dab1cde5 | anirudhaps/Python_Programs | /basics/programs/fibonacci.py | 329 | 4.21875 | 4 | # fibonacci series
# 0 1 1 2 3 5 8 13 21 ...
# find nth fibonacci number
def fibo(n):
if n==0:
return 0
elif n==1:
return 1
else:
return fibo(n-1) + fibo(n-2)
k = input('Enter the value of n: ')
print 'The fibonacci number for n = ' + `k` + ' is:'
print fibo(k)
| false |
e5a8d60f37974b4f06ce04b81f1335d9fe37bcc8 | anirudhaps/Python_Programs | /basics/CodingBatProgs/big_diff.py | 570 | 4.125 | 4 | '''
Given an array length 1 or more of ints, return the difference between the largest and smallest values in the array. Note: the built-in min(v1, v2) and max(v1, v2) functions return the smaller or larger of two values.
big_diff([10, 3, 5, 6]) -> 7
big_diff([7, 2, 10, 9]) -> 8
big_diff([2, 10, 7, 2]) -> 8
'''
def big_diff(lst):
i = 1
mi = lst[0]
ma = lst[0]
while i<len(lst):
mi = min(mi,lst[i])
ma = max(ma,lst[i])
i+=1
return ma-mi
print big_diff([10,3,5,6])
print big_diff([7,2,10,9])
print big_diff([2,10,7,2])
| true |
225190cd5cabc3885438f0a2c4229e6ac82e5b1f | devanraek/projects | /story3.py | 733 | 4.46875 | 4 | # Story one that will be selected randomly from user. This simple program allows
# user to fill in the missing words to create a full story.
def madLibs():
per1 = input("Enter person: ")
adj1 = input("Enter an adjective: ")
adj2 = input("Enter an adjective: ")
noun1 = input("Enter an noun: ")
adj3 = input("Enter an adjective: ")
noun2 = input("Enter an noun: ")
adj4 = input("Enter an adjective: ")
print('A day at the park!')
madlib = f"Yesterday, {per1} and I went to the park. On our way to the\
{adj1} park, we saw a {adj2} {noun1} on a bike. We also saw big {adj3}\
balloons tied to a {noun2}. Once we got to the {adj4} park, the sky"
print(madlib) | true |
574bc1dd3689466727660fe2f5341542398562b1 | Md-Hafizur-Rahman/Python-Code | /File.py | 951 | 4.40625 | 4 |
# file :
'''
We will use the open () function to open Python file.
it have three parameter.
1.file name
2.Access mode
3.Buffering
2.access mode:
-> r,rb,r+,w,wb,w+,a,ab,a+,ab+
'''
# syntex and how to work.
my_file=open('test.txt','r') # open file
conent=my_file.read() # it use to read file
print(conent)
my_file.close() # it use to close file
print()
my_file=open('test.txt','w+')
my_file.write('I am a CSE student of Daffodil Interrnational University') # it use to wright file
print(my_file.read())
my_file.close()
print()
my_file=open('test.txt','r')
print(my_file.read(6))
print(my_file.read()) # it use to read file
print(my_file.tell()) # it find position of totall index number
my_file.seek(0,0) # it point first index number
print(my_file.read())
my_file.close() # to close file
print()
# with statment in file. it's best to use.not need to define close() method
with open('test.txt','r') as my_file :
print(my_file.read())
| true |
84e98bf5f8ee9c09f16f68085ae8b691fde1040a | nidhi2509/Mini-Python-Projects | /rec_homework.py | 2,753 | 4.3125 | 4 | """
Make sure to fill in the following information before submitting your
assignment. Your grade may be affected if you leave it blank!
For usernames, make sure to use your Whitman usernames (i.e. exleyas).
File name: sierpinski.py
Author username(s): harristr jaltarnr
Date: Dec. 4, 2017
"""
import turtle
import math
def sierpinski(tr, p1, p2, p3, depth):
'''
Draws a Sierpinski triangle with corners at p1, p2, and p3.
Preconditions:
tr is a turtle object to use to draw with
p1 is a tuple that is the first corner of the triangle
p2 is a tuple that is the second corner of the triangle
p3 is a tuple that is the third corner of the triangle
depth is an int that is the recursion depth
Postconditions: None
'''
assert isinstance(tr, turtle.Turtle), 'tr must be a turtle object'
assert isinstance(p1, tuple) and len(p1) == 2, 'p1 must be a tuple with 2 elements'
assert isinstance(p2, tuple) and len(p2) == 2, 'p2 must be a tuple with 2 elements'
assert isinstance(p3, tuple) and len(p3) == 2, 'p3 must be a tuple with 2 elements'
assert isinstance(depth, int) and depth >= 0, 'depth must be a non-negative int'
if depth == 0:
tr.goto(p2)
tr.down()
tr.goto(p3)
tr.goto(p1)
tr.goto(p2)
tr.up()
else:
sierpinski(tr, p1, ((p2[0] + p1[0]) / 2, (p2[1] + p1[1]) / 2), ((p3[0] + p1[0]) / 2, (p3[1] + p1[1]) / 2), depth - 1) #Draw first sub-triangle
tr.goto(((p2[0] + p1[0]) / 2, (p2[1] + p1[1]) / 2)) #Move to mid of p1 and p2
sierpinski(tr, ((p2[0] + p1[0]) / 2, (p2[1] + p1[1]) / 2), p2, ((p3[0] + p2[0]) / 2, (p3[1] + p2[1]) / 2), depth - 1) #Draw second sub-triangle
tr.goto(((p3[0] + p1[0]) / 2, (p3[1] + p1[1]) / 2)) #Move to mid of p1 and p3
#tr.pendown()
sierpinski(tr, ((p3[0] + p1[0]) / 2, (p3[1] + p1[1]) / 2), ((p3[0] + p2[0]) / 2, (p3[1] + p2[1]) / 2), p3, depth - 1) #Draw third sub-triangle
tr.goto((p1)) #Move to initial position
#tr.pendown()
def subsets(aset):
'''Recursive function that returns a list of all subsets of aset
Preconditions:
aset is a list
Postconditions:
returns a list of lists
'''
if aset == []:
return [[]]
sublist = subsets(aset[1:])
for y in sublist:
sublist = sublist + [[aset[0]] + y]
return sublist
def main():
"""
t = turtle.Turtle()
t.speed(0)
t.hideturtle()
sierpinski(t, (-100, -60), (0, 100), (100, -60), 4)
sc = t.getscreen()
sc.exitonclick()"""
print(subsets([1, 2, 3,4,5]))
if __name__ == '__main__':
main()
| true |
13a5d7b7ae4bbd808d442ac7e8f3d205a7a851a7 | nidhi2509/Mini-Python-Projects | /hamming.py | 1,493 | 4.375 | 4 | """
Make sure to fill in the following information before submitting your
assignment. Your grade may be affected if you leave it blank!
For usernames, make sure to use your Whitman usernames (i.e. exleyas).
File name: hamming.py
Author username(s): harristr jaltarnr
Date: Oct. 16, 2017
"""
def hamming(str1, str2):
"""
Finds the Hamming distance between two strings.
Parameters:
str1: String input
str2: String input
Returns: Hamming distance between str1 and str2
"""
distance = 0 #Initializes Hamming distance
if len(str1) <= len(str2): #Checks if str1 is shorter or equal to str2 and keeps same if true
newstr1 = str1
newstr2 = str2
else: #Flips which string is first if str1 is longer
newstr1 = str2
newstr2 = str1
for char in range(len(newstr1)): #Adds distance if characters not matching
if newstr1[char] != newstr2[char]:
distance += 1
if len(newstr1) != len(newstr2): #Adds distance if one string is longer
distance = distance + len(newstr2) - len(newstr1)
return(distance)
def main():
bits1 = open('bits1.txt', 'r')
bits2 = open('bits2.txt', 'r')
for linefirst in bits1:
line1 = linefirst
break
for linesecond in bits2:
line2 = linesecond
break
print(hamming(line1, line2))
bits1.close()
bits2.close()
if __name__ == '__main__':
main()
| true |
7caa675c0c7529765ec15c6abbfc054c0143fcbd | RitvikKhanna/StrongerTranspositionCipher | /a1p2.py | 1,473 | 4.25 | 4 | """
Before reading this file or using it please read the readme_Ritvik.pdf included in the zip file. The logic and other things have slightly been changed according to the assignment.
Everything about the resources used to make this file are in the above said file. Do not proceed without reading that.
"""
# All important comments are already in a1p3 and the logic used in the readme file.
import math
def main():
myMessage = input("Enter message : ")
print("\nEnter keys with spaces (Example: 1 2 3 4 5): ")
myKey = [int(num) for num in input().split()]
plaintext = decryptMessage(myKey,myMessage)
print("\nPlaintext is :\n"+plaintext + '|')
def decryptMessage(key,message):
colnum = math.ceil(len(message)/len(key))
rownum = len(key)
plaintext = [''] * colnum
message1 = [''] * rownum
message2 = [''] * rownum
message1 = [message[i:i+colnum] for i in range(0,len(message), colnum)]
i = 0
for row in range(rownum):
col = key[i]-1
message2[col] = message1[row]
i += 1
message2 = ''.join(message2)
plaintext = [''] * colnum
col = 0
row = 0
for symbol in message2:
plaintext[col] += symbol
col += 1
if (col == colnum):
col = 0
row += 1
plaintext = ''.join(plaintext)
plaintext = plaintext.strip()
return plaintext
if __name__ == '__main__':
main()
| true |
5def4c3242cc8d421ca62971b6c8f409c0e19b67 | jonathanortizdam1993445/DI | /python/EJERCICIOS LISTAS 2/ejercicio4.py | 629 | 4.125 | 4 | #!usr/bin/env python
print("Introduce el valor de a")
a=int(input())
print("Introduce el valor de b")
b=int(input())
print("Introduce el primer termino de la sucesion")
termino1=int(input())
print("Dime cuantos terminos de la sucesion quieres")
cantidad=int(input())
lista=[]#CREAMOS UNA LISTA VACIA
lista.append(termino1)#AÑADIMOS A LA LISTA EL 1º TERMINO
for i in range(cantidad):#RECORREMOS LA CANTIDAD DE TERMINOS
termino1=a*termino1+b#TERMINO1 VA CAMBIANDO DE VALOR Y LOS
#ALMACENA EN LA LISTA, HASTA QUE SE ACABE LA CANTIDAD DE TERMINOS
lista.append(termino1)
print("Los terminos de la sucesión son ",lista)
| false |
b76d095f235e47acca5aadfb27d5c0a3eec22049 | pmgasper/leetcode | /0347_top_k_frequent_elements.py | 907 | 4.125 | 4 | #!/usr/bin/env python3
#
# Given a non-empty array of integers, return the k most frequent elements.
# For example, Given [1,1,1,2,2,3] and k = 2, return [1,2].
# Note:
# You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
# Your algorithm's time complexity must be better than O(n log n), where n is
# the array's size.
def top_k_freq_counter(nums, k):
# using Counter module
from collections import Counter
return [num[0] for num in Counter(nums).most_common(k)]
def top_k_freq(nums, k):
# only builtins
count = {}
for num in nums:
if num in count:
count[num] += 1
else:
count[num] = 1
return sorted(count.keys(), key=count.get, reverse=True)[:k]
# Tests
print(top_k_freq([1,1,1,2,2,3], 2))
print(top_k_freq([1,1,1,2,2,3,3,3,3], 2))
print(top_k_freq([3,1,1,2,2,3,4,5], 3))
print(top_k_freq([1], 1))
| true |
20d749f59a54d2664a8ae6f9952b49cf3acc597c | pmgasper/leetcode | /0034_count_and_say.py | 1,059 | 4.34375 | 4 | #!/usr/bin/env python3
#
# The count-and-say sequence is the sequence of integers with the first five
# terms as following:
#
# 1. 1
# 2. 11
# 3. 21
# 4. 1211
# 5. 111221
# 1 is read off as "one 1" or 11.
# 11 is read off as "two 1s" or 21.
# 21 is read off as "one 2, then one 1" or 1211.
#
# Given an integer n, generate the nth term of the count-and-say sequence.
#
# Note: Each term of the sequence of integers will be a string.
def count_and_say(n):
say = '1'
for _ in range(n - 1):
char = say[0]
count = 1
new_say = ''
prev_char = char
for char in say[1:]:
if char == prev_char:
count += 1
else:
new_say += str(count) + prev_char
count = 1
prev_char = char
new_say += str(count) + char
say = new_say
return say
# Tests
print(count_and_say(1))
print(count_and_say(2))
print(count_and_say(3))
print(count_and_say(4))
print(count_and_say(5))
| true |
1f014a16010e5826ac1982d45a2dc7be2707ecd0 | pmgasper/leetcode | /0326_power_of_three.py | 850 | 4.625 | 5 | #!/usr/bin/env python3
#
# Given an integer, write a function to determine if it is a power of three.
def is_power_of_three(n):
if n <= 0:
return False
while n > 1:
if n % 3 != 0:
return False
n = n // 3
return True
# Tests
print(is_power_of_three(0))
print(is_power_of_three(1))
print(is_power_of_three(3))
print(is_power_of_three(6))
print(is_power_of_three(9))
print(is_power_of_three(27))
print(is_power_of_three(30))
#Let n be the decimal number.
#Let m be the number, initially empty, that we are converting to. We'll be
#composing it right to left.
#Let b be the base of the number we are converting to.
#Repeat until n becomes 0
# Divide n by b, letting the result be d and the remainder be r.
# Write the remainder, r, as the leftmost digit of b.
# Let d be the new value of n.
| true |
2cdcddee470338417ff3d5e4842648d9aaef621c | HussainAther/computerscience | /theory/turingmachine.py | 2,800 | 4.125 | 4 | """
Turing machine implementation. (turing)
"""
class Tape(object):
"""
Represent an object the Turing machine tape.
"""
blank_symbol = " " # For printing a blank symbol on the tape
def __init__(self, tape_string = ""):
"""
The dictionary of th turing machine is the tape that has the entries
we print on the tape.
"""
self.__tape = dict((enumerate(tape_string)))
def __str__(self):
"""
Print out part of the tape as a string.
"""
min_used_index = min(self.__tape.keys())
max_used_index = max(self.__tape.keys())
for i in range(min_used_index, max_used_index):
s += self.__tape[i]
return s
def __getitem__(self, index):
"""
Return an index from the tape.
"""
if index in self.__tape:
return self.__tape[index]
else:
return Tape.blank_symbol
def __setitem__(self, pos, char):
"""
Set a character chat at a certain position pos on the tape.
"""
self.__tape[pos] = char
class TuringMachine(object):
"""
The Turing machine object.
"""
def __init__(self,
"""
Initialize the tape and the machine with the states.
"""
tape = "",
blank_symbol = " ",
initial_state = "",
final_states = None,
transition_function = None):
self.__tape = Tape(tape)
self.__head_position = 0
self.__blank_symbol = blank_symbol
self.__current_state = initial_state
if transition_function == None:
self.__transition_function = {}
else:
self.__transition_function = transition_function
if final_states == None:
self.__final_states = set()
else:
self.__final_states = set(final_states)
def get_tape(self):
"""
Return the tape as it is.
"""
return str(self.__tape)
def step(self):
"""
Perform a step in our function.
"""
char_under_head = self.__tape[self.__head_position]
x = (self.__current_state, char_under_head)
if x in self.__transition_function:
y = self.__transition_function[x]
self.__tape[self.__head_position] = y[1]
if y[2] == "R":
self.__head_position += 1
elif y[2] == "L":
self.__head_position -= 1
self.__current_state = y[0]
def final(self):
"""
Have we reached a final state?
"""
if self.__current_state in self.__final_states:
return True
else:
return False
| true |
732df574974bfcbeb76ca82278e4ab6ee11c9aff | HussainAther/computerscience | /puzzles/substring.py | 1,847 | 4.21875 | 4 | """
Find the longest common substring between two strings.
subsequence sequence
"""
def lcs(x, y):
"""
Return the longest common substring (subsequence)
between two strings x and y.
"""
result = ""
m, n = len(x, len(y)
for i in range(m):
match = ""
for j in range(n):
if (i + j < m and x[i + j] == y[j]):
match += y[j]
else:
if (len(match) > len(result)): result = match
match = ""
return result
def lcsl(x, y):
"""
Return the length of the longest common substring.
Use a table to store lengths of the longest common
suffixes of substrings. The longest common suffix of
x and y. The first row and first column entries have
no logical meaning.
"""
m, n = len(x), len(y)
suff = [[0 for k in range(n+1)] for l in range(m+1)] # suffix table
result = 0
for i in range(m+1):
for j in range(n+1):
if (i == 0 or j == 0):
suff[i][j] = 0
elif (x[i-1] == y[j-1]):
suff[i][j] = suff[i-1][j-1] + 1
result = max(result, suff[i][j])
else:
suff[i][j] = 0
return result
"""
Find the shortest superstring (supersequence).
"""
def super(x, y):
"""
Shortest superstring between strings x and y.
Use longest common substring to determine how
a superstring results.
"""
lc = lcs(x, y)
scs = "" # shortest common superstring
while len(lc) > 0:
if y[0] == lc[0] and y[0] == lc[0]:
scs += lcs[0]
lc = lc[1:]
x = x[1:]
y = y[1:]
elif x[0] == lc[0]:
scs += y[0]
y = by[1:]
else:
scs += x[0]
x = x[1:]
return scs + x + y
| true |
48626ae932177c3683257f31c06ed1a60f8e83a3 | HussainAther/computerscience | /graph/kahn.py | 2,142 | 4.25 | 4 | from collections import deque, namedtuple
Vertex = namedtuple('Vertex', ['name', 'incoming', 'outgoing'])
"""
Kahn's (Kahn) algorithm for topological sort takes a directed acyclic graph
with a linera ordering of the vertices such that for every directed edge ev, vertex u comes
before v in the ordering. A directed acyclic graph is a finite directed graph with no
directed cycles. A directed graph is a graph that is made of vertices connected by edges
in which the edges have a direct association with them. A directed cycle is a directed
version of a cycle graph with all edges in the same direction.
"""
def build_doubly_linked_graph(graph):
"""
Given a graph with only outgoing edges, build a graph with incoming and
outgoing edges. The returned graph will be a dictionary mapping vertex to a
Vertex namedtuple with sets of incoming and outgoing vertices.
"""
g = {v:Vertex(name=v, incoming=set(), outgoing=set(o)) for v, o in graph.items()}
for v in g.values():
for w in v.outgoing:
if w in g:
g[w].incoming.add(v.name)
else:
g[w] = Vertex(name=w, incoming={v}, outgoing=set())
return g
def kahn_top_sort(graph):
"""
Given an acyclic directed graph return a
dictionary mapping vertex to sequence such that sorting by the sequence
component will result in a topological sort of the input graph. Output is
undefined if input is a not a valid DAG.
The graph parameter is expected to be a dictionary mapping each vertex to a
list of vertices indicating outgoing edges. For example if vertex v has
outgoing edges to u and w we have graph[v] = [u, w].
"""
g = build_doubly_linked_graph(graph)
# sequence[v] < sequence[w] implies v should be before w in the topological
# sort.
q = deque(v.name for v in g.values() if not v.incoming)
sequence = {v: 0 for v in q}
while q:
v = q.popleft()
for w in g[v].outgoing:
g[w].incoming.remove(v)
if not g[w].incoming:
sequence[w] = sequence[v] + 1
q.append(w)
return sequence
| true |
389ce9ea67d0141acf6d90a69afcc95403a2b4a8 | algobot76/leetcode-python | /leetcode/208_implement_trie/solution1.py | 1,445 | 4.21875 | 4 | from typing import Optional
class TrieNode:
def __init__(self):
self.is_word = False
self.children = [None] * 26
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode()
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
curr = self.root
for ch in word:
idx = ord(ch) - ord('a')
if not curr.children[idx]:
curr.children[idx] = TrieNode()
curr = curr.children[idx]
curr.is_word = True
def search(self, word: str) -> bool:
"""
Returns if the word is in the trie.
"""
result = self._find(word)
return result is not None and result.is_word
def startsWith(self, prefix: str) -> bool:
"""
Returns if there is any word in the trie that starts with the given prefix.
"""
return self._find(prefix) is not None
def _find(self, prefix: str) -> Optional[TrieNode]:
curr = self.root
for ch in prefix:
idx = ord(ch) - ord('a')
if not curr.children[idx]:
return None
curr = curr.children[idx]
return curr
# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix)
| true |
3de9dcc4680b99d4b5689a6e35a8d3ccef4b9724 | marcosvnl/exerciciosPythom3 | /ex016.py | 683 | 4.3125 | 4 | # 016 Crie um programa que leia um número Real qualquer pelo teclado e mostre na tela a sua porção inteira.
# Ex: Ditite o número 6.127 o número 6.127 tem a parte inteira 6.
import math
num = float(input('Digite um número inteiro: '))
# math.trunc = vai te mostar a parte inteira de um número Ex: 6.127 iara mostar o 6
print('A parte inteira de {} é {}'.format(num, math.trunc(num)))
# ou fazer importando apenas o comando trunc "from math import trunc
# nesse caso na resolução do coamndo não precisa colocar math. antes do trunc
# ou fazer apenas com o comando int o mesmo do primitivo q indica um número inteiro
# nesse caso a resolução fica: .format(num, int(num))
| false |
46767b2d9df165085270b6c0202ef5d6e93ec67c | marcosvnl/exerciciosPythom3 | /ex033.py | 599 | 4.15625 | 4 | # 033 faça um programa que leia três números e mostre qual é o maior e qual é o menor.
a1 = int(input('Digite um número: '))
a2 = int(input('Digite outro número: '))
a3 = int(input('Mais um número: '))
# Verificando o número menor:
if a1 < a2 and a1 < a3:
menor = a1
if a2 < a1 and a2 < a3:
menor = a2
if a3 <a1 and a3 < a2:
menor = a3
print('O número MENOR é o {}'.format(menor))
# verificando o número menor:
if a1 > a2 and a1 > a3:
maior = a1
if a2 > a1 and a2 > a3:
maior = a2
if a3 > a1 and a3 > a2:
maior = a3
print('O número MAIOR é o {}'.format(maior))
| false |
a2e432e9c059ebb368868a28524f053ebb751148 | marcosvnl/exerciciosPythom3 | /ex065.py | 926 | 4.25 | 4 | # 065 Crie um progrma que leia varios números inteiros pelo teclado. No final da execução, mostre a média
# entre todos os valores e o maior e o menor número digitado. programa deve perguntar ao usúario se ele
# quer ou não continuar a digitar valores.
maior = 0
menor = 0
mais = ''
soma = 0
conta = 0
media = 0
while mais != 'N':
numero = int(input('Digite um número: '))
soma += numero
conta += 1
if conta == 1:
maior = numero
menor = numero
else:
if numero > maior:
maior = numero
if numero < menor:
menor = numero
mais = str(input('Quer contunuar a digitar números[S/N]: ')).strip().upper()[0]
media = soma / conta
print(soma)
print('Foram digirados {} números'.format(conta))
print('A media entres os números digitados é {:.2f}'.format(media))
print('O número maior é {}'.format(maior))
print('E o menor é {}.'.format(menor))
| false |
b2f39ad8877901076be9931ee8cc707c0c39b8cd | marcosvnl/exerciciosPythom3 | /ex037.py | 644 | 4.1875 | 4 | # 037 Escreva um porgrama que leia um número inteiro qualquer e e peça para o usuário escolher
# qual será a base de conversão:
# - 1 p/ binário
# - 2 p/ octal
# - 3 p/ hexadecimal
num = int(input('Digite um número inteiro: '))
print('''Você gostaria de converter para qual base a baixo:
[1] para binário
[2] para octal
[3] para hexadecimal''')
esc = int(input('Escolha uma opção: '))
if esc == 1:
print('O valor {} em BINÁRIO é {}'.format(num, bin(num)[2:]))
elif esc == 2:
print('O valor {} em OCTAL é {}'.format(num, oct(num)[2:]))
elif esc == 3:
print('O valr {} em HEXADECIMAL é {}'.format(num, hex(num)[2:]))
| false |
2a6fbd4af88ddfaa8663d8bdf3dedffc7ee97441 | marcosvnl/exerciciosPythom3 | /ex098.py | 957 | 4.25 | 4 | # Exercício Python 098: Faça um programa que tenha uma função chamada contador(),
# que receba três parâmetros: início, fim e passo. Seu programa tem que realizar
# três contagens através da função criada:
#
# a) de 1 até 10, de 1 em 1
# b) de 10 até 0, de 2 em 2
# c) uma contagem personalizada
from time import sleep
def contador(ini, fim, de):
if de == 0:
de = 1
if de < 0:
de *= -1
print('=+' * 20)
print(f'Contando de {ini} até {fim} de {de} em {de}')
if ini < fim:
c = ini
while c <= fim:
print(f'{c} ', end='')
sleep(0.3)
c += de
else:
c = ini
while c >= fim:
print(f'{c} ', end='',)
sleep(0.3)
c -= de
contador(1, 10, 1)
print()
contador(10, 0, 2)
print()
print('Pesonalize uma contagem:')
i = int(input('Inicío: '))
f = int(input('Fim: '))
d = int(input('Passo: '))
contador(i, f, d)
| false |
01c0db99f53dc75387a22d5c59d8408d89c1a353 | chenkunyu66/Algorithm-proj04 | /proj04/TreeSet.py | 1,869 | 4.125 | 4 | class TreeSet:
"""
A set data structure backed by a tree.
Items will be stored in an order determined by a comparison
function rather than their natural order.
"""
def __init__(self, comp):
"""
Constructor for the tree set.
You can perform additional setup steps here
:param comp: A comparison function over two elements
"""
self.comp = comp
# added stuff below
def __len__(self):
return 0
def height(self):
return -1
def insert(self, item):
return False
def remove(self, item):
return False
def __contains__(self, item):
return False
def first(self):
raise KeyError
def last(self):
raise KeyError
def clear(self):
pass
def __iter__(self):
return iter([])
# Pre-defined methods
def is_empty(self):
"""
Determines whether the set is empty
:return: False if the set contains no items, True otherwise
"""
return len(self) == 0
def __repr__(self):
"""
Creates a string representation of this set using an in-order traversal.
:return: A string representing this set
"""
return 'TreeSet([{0}])'.format(','.join(str(item) for item in self))
# Helper functions
# You can add additional functions here
class TreeNode:
"""
A TreeNode to be used by the TreeSet
"""
def __init__(self, data):
"""
Constructor
You can add additional data as needed
:param data:
"""
self.data = data
self.left = None
self.right = None
# added stuff below
def __repr__(self):
"""
A string representing this node
:return: A string
"""
return 'TreeNode({0})'.format(self.data)
| true |
f469d4e096530d0a7113e1cd05523f1af1aa59dc | azznggu/pythonScrapTest | /basic/dictionaryTest.py | 761 | 4.46875 | 4 | dic= {'a':1, 'b':[2,3,4], 'c':'ccc'}
#dictinary related functions
#1. keys - get key lists of dictionary.
print(dic.keys())
for key in dic.keys() :
print(key)
#2. values - get value lists of dictionary.
for val in dic.values():
print(val)
#3. items - key & value set
for item in dic.items() :
print(item)
#4. clear - delete all item? of dictionary
dic.clear()
print(dic)
#5. get value by key
dic= {'a':1, 'b':[2,3,4], 'c':'ccc'}
# it is same as dic['a']
gotVal = (dic.get('a'))
print(gotVal)
#6. in - check if key is in dic
result = 'a' in dic
print(result)
#practice
dic = {'name':'a','birth':1128, 'age':30}
a = {'A':90, 'B':80, 'C':70}
print(a.get('B'))
items = a.items()
print(items)
a = {'A':90, 'B':80}
print(a.get('C', 'nope')) | false |
c1fd9451e62218f48e3857f05b46384d3712caa8 | Frolki1-Dev/learn_python | /basic/list.py | 267 | 4.1875 | 4 | # How to work with lists
students = [
"Monika",
"Fritz",
"Luise",
"Andi"
]
print(students)
# Add item to list
students.append("Ronald")
print(students)
# Get the length of the list
print(len(students))
# Get a specific student
print(students[2]) | true |
2e71219a2a37ff97306352b590a440785774e137 | NiranjanW/Python | /scripts/BubbleSort1.py | 305 | 4.15625 | 4 |
def bubbleSort(items):
for i in range(len(items)):
for j in range(len(items) -1 -i):
if items[j] > items[j+1]:
items[j] , items[j+1] = items[j+1] , items[j]
if __name__ == "__main__":
args =[1,6,2,5,8]
bubbleSort(args)
for x in args:
print x | false |
fb3cb3f82af3d43cce33a67d5ae92acb0452e6a6 | majopj/Assignment | /SUM OF SERIES.PY | 256 | 4.1875 | 4 | print("SUM OF THE SERIES")
print()
def sum_series(num):
res = 0
fact = 1
for i in range(1, num+1):
fact=fact*i
res = res + (i/ fact)
print ("Sum of this series is:",res)
n = int(input("Enter the value of N:"))
sum_series(n) | true |
0bd50b4b0b76f5b0a9d29d714ddd2942c5cc5ff0 | erikliu0801/leetcode | /python3/solved/P840. Magic Squares In Grid.py | 2,963 | 4.3125 | 4 | # ToDo:
"""
840. Magic Squares In Grid
Easy
A 3 x 3 magic square is a 3 x 3 grid filled with distinct numbers from 1 to 9 such that each row, column, and both diagonals all have the same sum.
Given an grid of integers, how many 3 x 3 "magic square" subgrids are there? (Each subgrid is contiguous).
Example 1:
Input: [[4,3,8,4],
[9,5,1,9],
[2,7,6,2]]
Output: 1
Explanation:
The following subgrid is a 3 x 3 magic square:
438
951
276
while this one is not:
384
519
762
In total, there is only one magic square inside the given grid.
Note:
1 <= grid.length <= 10
1 <= grid[0].length <= 10
0 <= grid[i][j] <= 15
"""
# Conditions & Concepts
"""
1. distinct 1~9
2. sum of all columns, rows and both diagonals are same
"""
# Code
## submit part
class Solution:
def numMagicSquaresInside(self, grid: List[List[int]]) -> int:
## test part
def numMagicSquaresInside(grid):
"""
grid: List[List[int]])
rtype: int:
"""
## code here
#1
"""
Success
Runtime: 52 ms, faster than 24.04% of Python3 online submissions for Magic Squares In Grid.
Memory Usage: 14.1 MB, less than 11.40% of Python3 online submissions for Magic Squares In Grid.
"""
def numMagicSquaresInside(grid):
count = 0
rows, cols = len(grid), len(grid[0])
if rows < 3 or cols < 3: return 0
for r in range(rows-2):
for c in range(cols-2):
# origin = (r,c)
r1 = [grid[r][c], grid[r][c+1], grid[r][c+2]]
r2 = [grid[r+1][c], grid[r+1][c+1], grid[r+1][c+2]]
r3 = [grid[r+2][c], grid[r+2][c+1], grid[r+2][c+2]]
c1 = [grid[r][c], grid[r+1][c], grid[r+2][c]]
c2 = [grid[r][c+1], grid[r+1][c+1], grid[r+2][c+1]]
c3 = [grid[r][c+2], grid[r+1][c+2], grid[r+2][c+2]]
d1 = [grid[r][c], grid[r+1][c+1], grid[r+2][c+2]]
d2 = [grid[r][c+2], grid[r+1][c+1], grid[r+2][c]]
nums = r1 + r2 + r3
if len(nums) != len(set(nums)): continue
if sorted(nums) != [i for i in range(1,10)]: continue
if sum(r1) != 15 or \
sum(r2) != 15 or \
sum(r3) != 15 or \
sum(c1) != 15 or \
sum(c2) != 15 or \
sum(c3) != 15 or \
sum(d1) != 15 or \
sum(d2) != 15: continue
count += 1
return count
# Test
## Functional Test
"""
# Conditions & Concepts
"""
if __name__ == '__main__':
input1 = []
expected_output = []
for i in range(len(input1)):
if func(input1[i]) != expected_output[i]:
print("Wrong!!!", ' Output:', func(input1[i]), '; Expected Output:', expected_output[i])
else:
print("Right")
# print(func(input1[-1]))
## Performance Test
import cProfile
cProfile.run('')
## Unit Test
import unittest
class Test(unittest.TestCase):
def test(self):
pass
if __name__ == '__main__':
unittest.main() | true |
e23640e812f94f19da865f9aa8052270fee0b4fc | erikliu0801/leetcode | /python3/solved/P970. Powerful Integers.py | 2,548 | 4.15625 | 4 | # ToDo:
"""
P970. Powerful Integers
Easy
Given two positive integers x and y, an integer is powerful if it is equal to x^i + y^j for some integers i >= 0 and j >= 0.
Return a list of all powerful integers that have value less than or equal to bound.
You may return the answer in any order. In your answer, each value should occur at most once.
Example 2:
Input: x = 3, y = 5, bound = 15
Output: [2,4,6,8,10,14]
Note:
1 <= x <= 100
1 <= y <= 100
0 <= bound <= 10^6
"""
# Conditions & Concepts
"""
"""
# Code
## submit part
class Solution:
def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]:
## test part
class Solution:
def powerfulIntegers(self, x, y, bound):
"""
x: int
y: int
bound: int
rtype: List[int]
"""
## code here
#1
"""
Time Limit Exceeded
Last executed input: 2, 1, 10
"""
class Solution:
def powerfulIntegers(self, x, y, bound):
res = set()
i = 0
while x**i <= bound:
j = 0
base = x**i
while base + y**j <= bound:
res.add(base + y**j)
j += 1
i += 1
return list(res)
#1.1
"""
Success
Runtime: 20 ms, faster than 96.83% of Python3 online submissions for Powerful Integers.
Memory Usage: 12.7 MB, less than 100.00% of Python3 online submissions for Powerful Integers.
"""
class Solution:
def powerfulIntegers(self, x, y, bound):
if bound < 2: return []
if x == 1 and y == 1: return [2]
if y == 1: x, y = y, x
res = set()
i = 0
while x**i <= bound:
j = 0
base = x**i
while base + y**j <= bound:
res.add(base + y**j)
j += 1
if x == 1: break
i += 1
res = list(res)
return res
# Test
## Functional Test
"""
# Conditions & Concepts
"""
if __name__ == '__main__':
input1 = [2, 3, 1]
input2 = [3, 5, 1]
input3 = [100, 15, 3]
expected_output = [[2,3,4,5,7,9,10], [2,4,6,8,10,14], []]
for i in range(len(input1)):
if func(input1[i]) != expected_output[i]:
print("Wrong!!!", ' Output:', func(input1[i]), '; Expected Output:', expected_output[i])
else:
print("Right")
# print(func(input1[-1]))
## Performance Test
import cProfile
cProfile.run('')
## Unit Test
import unittest
class Test(unittest.TestCase):
def test(self):
pass
if __name__ == '__main__':
unittest.main() | true |
fc327e9ed306075454765b121ad5b28c2410017a | erikliu0801/leetcode | /python3/solved/P122. Best Time to Buy and Sell Stock II.py | 2,575 | 4.28125 | 4 | # ToDo:
"""
122. Best Time to Buy and Sell Stock II
Easy
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).
Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).
Example 1:
Input: [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
Example 2:
Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again.
Example 3:
Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
"""
# Conditions & Concepts
"""
"""
# Code
## submit part
class Solution:
def maxProfit(self, prices: List[int]) -> int:
## test part
def maxProfit(prices):
"""
prices: List[int]
rtype: int
"""
## code here
#1
"""
serveral times maxProfit()
def maxProfit(prices):
buy_val, earn = float('inf'), 0
for val in prices:
if val < buy_val:
buy_val = val
if val - buy_val > earn:
earn = val - buy_val
return earn
Success
Runtime: 56 ms, faster than 96.77% of Python3 online submissions for Best Time to Buy and Sell Stock II.
Memory Usage: 13.9 MB, less than 68.29% of Python3 online submissions for Best Time to Buy and Sell Stock II.
"""
def maxProfit(prices):
buy_val, earn, earn_sum = float('inf'), 0, 0
for val in prices:
if val < buy_val:
buy_val = val
if val - buy_val > earn:
earn = val - buy_val
elif val - buy_val < earn:
earn_sum += earn
buy_val, earn = val, 0
earn_sum += earn
return earn_sum
# Test
## Functional Test
"""
# Conditions & Concepts
"""
if __name__ == '__main__':
input_prices = [[7,1,5,3,6,4],[1,2,3,4,5],[7,6,4,3,1]]
expected_output = [7,4,0]
for i in range(len(input_prices)):
if maxProfit(input_prices[i]) != expected_output[i]:
print("Wrong!!!")
print(maxProfit(input_prices[i]))
else:
print("Right")
# print(maxProfit(input_prices[-1]))
## Performance Test
import cProfile
cProfile.run('')
## Unit Test
import unittest
class Test(unittest.TestCase):
def test(self):
pass
if __name__ == '__main__':
unittest.main() | true |
fedfb8f625a0a0acb63f30585592fbf53b61083c | erikliu0801/leetcode | /python3/solved/P415. Add Strings.py | 1,357 | 4.125 | 4 | # ToDo:
"""
415. Add Strings
Easy
Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
Note:
The length of both num1 and num2 is < 5100.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
You must not use any built-in BigInteger library or convert the inputs to integer directly.
"""
# Conditions & Concepts
"""
"""
# Code
## submit part
class Solution:
def addStrings(self, num1: str, num2: str) -> str:
## test part
def addStrings(num1, num2):
"""
num1: str
num2: str
rtpye: str
"""
## code here
#1
"""
Success
Runtime: 28 ms, faster than 97.84% of Python3 online submissions for Add Strings.
Memory Usage: 12.7 MB, less than 100.00% of Python3 online submissions for Add Strings.
"""
def addStrings(num1, num2):
return str(int(num1)+int(num2))
# Test
## Functional Test
"""
# Conditions & Concepts
"""
if __name__ == '__main__':
input1 = []
expected_output = []
for i in range(len(input1)):
if func(input1[i]) != expected_output[i]:
print("Wrong!!!")
print(func(input1[i]))
else:
print("Right")
# print(func(input1[-1]))
## Performance Test
import cProfile
cProfile.run('')
## Unit Test
import unittest
class Test(unittest.TestCase):
def test(self):
pass
if __name__ == '__main__':
unittest.main() | true |
02499169a663e0e2a8f4973230d7f1574f2f863e | erikliu0801/leetcode | /python3/solved/P374. Guess Number Higher or Lower.py | 2,657 | 4.25 | 4 | # ToDo:
"""
374. Guess Number Higher or Lower
Easy
We are playing the Guess Game. The game is as follows:
I pick a number from 1 to n. You have to guess which number I picked.
Every time you guess wrong, I'll tell you whether the number is higher or lower.
You call a pre-defined API guess(int num) which returns 3 possible results (-1, 1, or 0):
-1 : My number is lower
1 : My number is higher
0 : Congrats! You got it!
Example :
Input: n = 10, pick = 6
Output: 6
"""
# Conditions & Concepts
"""
"""
# Code
## submit part
# The guess API is already defined for you.
# @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
# def guess(num: int) -> int:
class Solution:
def guessNumber(self, n: int) -> int:
## test part
def guessNumber(n):
"""
n: int
rtype: int
"""
## code here
#1
"""
adjust from P278 firstBadVersion(n)
def firstBadVersion(n):
if n in [0,1] or isBadVersion(n) is False:
return n
elif isBadVersion(1) is True:
return 1
else:
try_num = n//2
high_limit, low_limit = n, 1
while try_num < n:
if isBadVersion(try_num) is True:
high_limit = try_num
try_num = (high_limit + low_limit) // 2
if high_limit - 1 == low_limit:
return high_limit
elif isBadVersion(try_num) is False:
low_limit = try_num
try_num = (high_limit + low_limit) // 2
if low_limit + 1 == high_limit:
return high_limit
Success
Runtime: 24 ms, faster than 82.42% of Python3 online submissions for Guess Number Higher or Lower.
Memory Usage: 12.6 MB, less than 100.00% of Python3 online submissions for Guess Number Higher or Lower.
Next challenges:
"""
def guessNumber(n):
if n in [0,1] or guess(n) == 0:
return n
elif guess(1) is 0:
return 1
else:
try_num = n//2
high_limit, low_limit = n, 1
while try_num < n:
if guess(try_num) == 0:
return try_num
elif guess(try_num) == -1:
high_limit = try_num
try_num = (high_limit + low_limit) // 2
if high_limit - 1 == low_limit:
return high_limit
elif guess(try_num) == 1:
low_limit = try_num
try_num = (high_limit + low_limit) // 2
if low_limit + 1 == high_limit:
return high_limit
# Test
## Functional Test
"""
# Conditions & Concepts
"""
if __name__ == '__main__':
input1 = []
expected_output = []
for i in range(len(input1)):
if func(input1[i]) != expected_output[i]:
print("Wrong!!!")
print(func(input1[i]))
else:
print("Right")
# print(func(input1[-1]))
## Performance Test
import cProfile
cProfile.run('')
## Unit Test
import unittest
class Test(unittest.TestCase):
def test(self):
pass
if __name__ == '__main__':
unittest.main() | true |
dfae91d031f608c6f94d14cc97d36155dbaf826f | erikliu0801/leetcode | /python3/P687. Longest Univalue Path.py | 1,585 | 4.125 | 4 | # ToDo:
"""
687. Longest Univalue Path
Easy
Given a binary tree, find the length of the longest path where each node in the path has the same value. This path may or may not pass through the root.
The length of path between two nodes is represented by the number of edges between them.
Example 1:
Input:
5
/ \
4 5
/ \ \
1 1 5
Output: 2
Example 2:
Input:
1
/ \
4 5
/ \ \
4 4 5
Output: 2
Note: The given binary tree has not more than 10000 nodes. The height of the tree is not more than 1000.
"""
# Conditions & Concepts
"""
"""
# Code
## submit part
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def longestUnivaluePath(self, root: TreeNode) -> int:
## test part
class Solution:
def longestUnivaluePath(self, root):
"""
root: TreeNode
rtype: int
"""
## code here
#1
class Solution:
def longestUnivaluePath(self, root):
# Test
## Functional Test
"""
# Conditions & Concepts
"""
if __name__ == '__main__':
input1 = []
expected_output = []
for i in range(len(input1)):
if func(input1[i]) != expected_output[i]:
print("Wrong!!!", ' Output:', func(input1[i]), '; Expected Output:', expected_output[i])
else:
print("Right")
# print(func(input1[-1]))
## Performance Test
import cProfile
cProfile.run('')
## Unit Test
import unittest
class Test(unittest.TestCase):
def test(self):
pass
if __name__ == '__main__':
unittest.main() | true |
a329cb238540cd938689df4eadea1fdd4588f6a2 | Parzha/Assignment4 | /assi4project4.py | 384 | 4.1875 | 4 | def Fibonacci(n):
if n < 0:
print("Incorrect input")
elif n == 0:
return 0
elif n == 1 or n == 2:
return 1
else:
return Fibonacci(n - 1) + Fibonacci(n - 2)
Fibonacci_list=[]
n=int(input("please enter N for fibonacci serie"))
for items in range(n):
Fibonacci_list.append(Fibonacci(items))
print(Fibonacci_list) | false |
b925408b4322dfd1463ad746b893def7e62f0828 | sandeepinigithub/IPM | /testfile.py | 1,667 | 4.5625 | 5 | def func1(arg1, arg2, **kwargs):
print("I am func1 ", arg1, arg2)
def func2(arg21, arg22, **kwargs):
print(" I am func2", arg21, arg22)
FUNC_MAP = {
"func1": func1,
"func2": func2
}
some_arguments = {"arg1": 1, "arg2": 2, "arg21": 3, "arg22": 4}
FUNC_MAP["func1"](**some_arguments)
FUNC_MAP["func2"](**some_arguments)
# run this file now yeah, got it ?
sir samajh toh aaya kaise kiya
pr aisa hua kaise?
I mean maine kbhi aisa kuch nii pda
Its easy.
Think of the functions like a reference, now you already know that we have two types of arguments,
keyword and positional,
now lets say we have a dict of some arguments..
some_arguments = {"arg1": 1, "arg2": 2, "arg21": 3, "arg22": 4}
^ this one
and we know the function name as well eg. func1, func2..
then if we unpack this dictionary with the function's reference it would be passed like this
func1(arg1=1, arg2=2, arg21=3, arg22=4) # func1 only consumes arg1 and arg2 so we need something to capture the rest of the arguments
func2(arg1=1, arg2=2, arg21=3, arg22=4)# func2 only consumes arg21 and arg22 so we need something to capture the rest of the arguments
# thats why we put **kwargs
makes sense ? there ?
yes sir, yes sir totally
mere liye new tha yeh toh isiliye nii smjha tha main
but sir not lets say that yeh dono functions yha nii hote
toh yha pr
FUNC_MAP = {
"func1": func1,
"func2": func2
}
func1 not defined aata naa??
yeah definitely
Okay just to give you a hint about where did I adopt this idea from.
go to urls.py
siarn any ony e
any urls.py
yes sir I am there in jira folder urls.py | false |
86dc1c1ae303e247832b4c943e9ee83e0fe9ad0f | corinnelhh/code_eval | /hard/string_permutations.py | 965 | 4.40625 | 4 | # https://www.codeeval.com/open_challenges/14/
# String Permutations
# Challenge Description:
# Write a program to print out all the permutations of a string in
# alphabetical order. We consider that
# digits < upper case letters < lower case letters. The sorting should be
# performed in ascending order.
# Input sample:
# Your program should accept as its first argument a path to a file
# containing an input string, one per line.
# E.g.
# hat
# abc
# Zu6
# Output sample:
# Print to stdout, permutations of the string, comma separated, in
# alphabetical order.
# E.g.
# aht,ath,hat,hta,tah,tha
# abc,acb,bac,bca,cab,cba
# 6Zu,6uZ,Z6u,Zu6,u6Z,uZ6
import sys
import itertools
def get_permutations(string):
perms = itertools.permutations(string)
print ",".join(sorted("".join(perm) for perm in perms))
if __name__ == '__main__':
with open(sys.argv[1], 'r') as f:
for line in f.readlines():
get_permutations(line.strip())
| true |
03e1d631c9d488a3107e5c241ea31db6ea6f1eef | corinnelhh/code_eval | /easy/happy_numbers.py | 1,293 | 4.25 | 4 | # https://www.codeeval.com/open_challenges/39/
# Happy Numbers
# Challenge Description:
# A happy number is defined by the following process. Starting with any
# positive integer, replace the number by the sum of the squares of its
# digits, and repeat the process until the number equals 1 (where it will
# stay), or it loops endlessly in a cycle which does not include 1. Those
# numbers for which this process ends in 1 are happy numbers, while those
# that do not end in 1 are unhappy numbers.
# Input sample:
# The first argument is the pathname to a file which contains test data,
# one test case per line. Each line contains a positive integer. E.g.
# 1
# 7
# 22
# Output sample:
# If the number is a happy number, print out 1. If not, print out 0. E.g
# 1
# 1
# 0
# For the curious, here's why 7 is a happy number: 7->49->97->130->10->1.
# Here's why 22 is NOT a happy number:
# 22->8->64->52->29->85->89->145->42->20->4->16->37->58->89 ...
import sys
def get_happy_number(num):
history = set()
while num != 1:
if num in history:
return 0
history.add(num)
num = sum(int(i) * int(i) for i in str(num))
return 1
with open(sys.argv[1], 'r') as f:
for line in f.readlines():
print get_happy_number(int(line.strip()))
| true |
40e42b7236568da10ab7b6a1da0cad10a1967a13 | corinnelhh/code_eval | /medium/pascals_triangle.py | 1,474 | 4.34375 | 4 | # https://www.codeeval.com/open_challenges/66/
# Pascals Triangle
# Challenge Description:
# A Pascals triangle row is constructed by looking at the previous row
# and adding the numbers to its left and right to arrive at the new value.
# If either the number to its left/right is not present, substitute a
# zero in its place. More details can be found here: Pascal's triangle.
# E.g. a Pascal's triangle upto a depth of 6 can be shown as:
# 1
# 1 1
# 1 2 1
# 1 3 3 1
# 1 4 6 4 1
# 1 5 10 10 5 1
# Input sample:
# Your program should accept as its first argument a path to a filename.
# Each line in this file contains a positive integer which indicates the
# depth of the triangle (1 based). E.g.
# 6
# Output sample:
# Print out the resulting pascal triangle upto the requested depth in
# row major form. E.g.
# 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1
import sys
import itertools
def pascals_triangle(depth):
row_count = 1
rows = [[1]]
while row_count < depth:
new_row, last_el = [], 0
for el in rows[-1]:
new_row.append(last_el + el)
last_el = el
new_row.append(1)
rows.append(new_row)
row_count += 1
return " ".join([str(n) for n in list(
itertools.chain.from_iterable(rows))])
with open(sys.argv[1], 'r') as f:
for line in f.readlines():
print pascals_triangle(int(line.strip()))
| true |
f49f3bfacbbbbaddd5655dab6945bac307f12bb1 | corinnelhh/code_eval | /easy/reverse_words.py | 701 | 4.4375 | 4 | # https://www.codeeval.com/open_challenges/8/
# Reverse words
# Challenge Description:
# Write a program to reverse the words of an input sentence.
# Input sample:
# The first argument will be a path to a filename containing multiple
# sentences, one per line. Possibly empty lines too. E.g.
# Hello World
# Hello CodeEval
# Output sample:
# Print to stdout, each line with its words reversed, one per line. Empty
# lines in the input should be ignored. Ensure that there are no trailing
# empty spaces on each line you print.
# E.g.
# World Hello
# CodeEval Hello
import sys
with open(sys.argv[1], 'r') as f:
for line in f.readlines():
print " ".join(line.strip().split()[::-1])
| true |
e3826694ab0ed38da0761651730279fd655d9092 | KoveKim/Python-Practice | /Conditional Practice 1.py | 282 | 4.28125 | 4 | def max_num():
num1 = input("First number: ")
num2 = input("Second number: ")
num3 = input("Third number: ")
if num1 >= num2 and num1 >= num3:
print(num1)
elif num2 >= num1 and num2 >= num3:
print(num2)
else:
print(num3)
max_num()
| false |
82ab298af88bae3ae8b575e4bc032d4f21cb7bdc | CompThinking20/python-project-derryh123 | /calendar.py | 2,010 | 4.46875 | 4 | import calendar
from tkinter import *
##simple python program to display one month of the year
#yy = 2020
#mm = 12
##print(calendar.month(yy, mm))
##This function for the calendar is a little more interactive.
##Its a gui and creates a separate window to view the date.
##this function shows the whole year as well
##I wanted to test out something more interactive since
##it will be part of a smart mirror which should include visual components.
def Calendar():
#creates graphical interface window
cal_gui = Tk()
#background color
cal_gui.config(background = "blue")
cal_gui.title("Calendar")
cal_gui.geometry("500x600")
#returns text as string
new_year = int(year_field.get())
#method from calendar module which returns calendar of given year
cal_content = calendar.calendar(new_year)
cal_year = Label(cal_gui, text = cal_content, font = "Calibri 10 bold")
cal_year.grid(row = 5, column = 1, padx = 20)
cal_gui.mainloop()
##driver
if ___name__ == "__main__":
gui = Tk()
gui.config(background = "white")
gui.title("CALENDER")
##tkinter window with dimensions 250x140
gui.geometry("250x140")
cal = Label(gui, text = "CALENDAR", bg = "dark gray",
font = ("times", 28, 'bold'))
# where you enter the year
year = Label(gui, text = "Enter Year", bg = "light green")
# text entry box
year_entry = Entry(gui)
# Create a button to show calendar
Display = Button(gui, text = "Show Calendar", fg = "Black",
bg = "Red", command = Calendar)
Exit = Button(gui, text = "Exit", fg = "Black", bg = "Red", command = exit)
# grid method is used for placing
# components at certain positions
cal.grid(row = 1, column = 1)
year.grid(row = 2, column = 1)
year_entry.grid(row = 3, column = 1)
Display.grid(row = 4, column = 1)
Exit.grid(row = 6, column = 1)
##starts the gui
gui.mainloop()
| true |
7e7a8323d9732f4d003e8a954fbeafa53381b40b | luismglvieira/Python-and-OpenCV | /00 - Python3 Tutorials/12 - If, Elif, Else statements.py | 352 | 4.34375 | 4 | # -*- coding: utf-8 -*-
x = int(input("Enter an integer number: "))
if x > 0:
if (x%2) == 0:
print("Your number, " + str(x) + ", is positive and even.")
else:
print("Your number, " + str(x) + ", is positive and odd.")
elif x == 0:
print("Your number is zero.")
else:
print("Your number, " + str(x) + ", is negative.") | false |
3a74252d867856d66a233fd9a899ed6e6eee4f35 | Duzj/PythonDemo | /PythonDemo/function_docstring.py | 449 | 4.1875 | 4 | #“函数的第一行逻辑行中的字符串是该函数的 文档字符串(DocString)”
#文档功能 函数 _doc_
def print_max(x,y):
'''Prints the maximum of two numbers.打印两个数值中的最大数。
The two values must be integers.这两个数都应该是整数'''
x = int(x)
y = int(y)
if x > y:
print(x,'is maximum')
else:
print(y,'is maxmum')
print_max(3,6)
print(print_max.__doc__)
| false |
32862a673c51a4a1d6b7c81567c64c28cc84ea68 | peskywyvern/homework6 | /61.py | 277 | 4.15625 | 4 | def insert_whitespace(text):
new_text = ''
for character in text:
if character.isupper():
new_text += ' ' + character
else:
new_text += character
return new_text
text1 = 'WhatIsUp'
print(insert_whitespace(text1)) | true |
1bb559f8dad1d8c350c1aaafa37d6ba668d1a899 | AlexandreBittencourt/aula-python-excessoes | /erros-excecoes.py | 1,114 | 4.34375 | 4 | ### Erro
###print("João)
###Exceção
#print(2/0)
from typing import overload
#entrada = int(input("Digite um valor numérico: "))
###Podemos tratar as exceções com as funções try e except
try:
print("Olá")
print("olá")
except:
print("Escreva corretamente")
try:
print(2/1)
except NameError:
print("não divida por zero")
try:
print(2 + ("a"))
except:
print("não pode somar assim")
try:
div=(2/0)
print(div)
except ZeroDivisionError:
print("Número não pode ser dividido por zero")
### Tratar exceções com condicionais e loops
def perguntaint():
while True:
try:
numint = int(input("Digite um número inteiro: "))
except:
print("Digite certo")
continue
else:
print("Ok registrado")
break
finally:
print("Fim do programa")
perguntaint()
### Criar a própria exceção com a função raise
#def divisao(x,y):
# if y ==0:
# raise ValueError("Segundo valor não pode ser 0")
# return x /y
#print(divisao(2,0))
print("planta")
| false |
6dfef449558707aa6159d3b4aedd2efc4e8ca206 | slyslide/slyslide | /Python Projects/chapter2.py | 697 | 4.125 | 4 | print("Compound Interest")
print(" ")
PRINCIPAL = float(input('Input principal investment for calculation: '))
INTEREST_RATE = float((input('Input the interest rate percentage on the account: ')))
INTEREST_RATE = INTEREST_RATE/100
INTEREST_TIME_PERIOD = float(input("Input the rate that interest compouts, in how many times a year it occurs (int): "))
TOTAL_TIME_INVESTED = float(input("How many years will you let the account accrue interest: "))
amount = PRINCIPAL*((1+(INTEREST_RATE/INTEREST_TIME_PERIOD))**(INTEREST_TIME_PERIOD*TOTAL_TIME_INVESTED))
print("The final amount you can withdraw after ", TOTAL_TIME_INVESTED, " years is: ")
print("$", format(amount, ',.2f'), sep='')
| true |
5d80b26b2aa8ef141f8d1b292ae4f67c1a91b6c4 | cdne/python | /calculator.py | 2,091 | 4.25 | 4 | """
Write a calculator script that waits for the user to enter a number, then a sign (plus, minus, multiplication and division),
then a number again. After the 2nd number input, the script should calculate the addition or subtraction and print it out.
Then the program should run again with asking for the first number.
The script should exit when the user enters a letter instead of a number.
"""
# declaring variables
number1, number2, result = 0, 0, 0
sign = ""
# informing the user what to do
info = '''
You will be asked to enter 2 numbers and a valid sign for operations
If you enter a letter when you're asked for a number or anything else that is not a sign when asked for operation the app will stop
'''
print(info)
try:
# read first number
number1 = float(input("Enter first number: "))
# read sign + - * /
sign = input("Enter a sign (+ - * /): ")
# if sign is not a sign except is executed and prints "Application stopped"
if sign != "*" and sign != "-" and sign != "/" and sign != "+":
sys.exit()
# read second number
number2 = float(input("Enter second number: "))
# loop executes only if number1 or number2 are not strings
while(number1 and number2) != "":
if sign == "+":
result = number1 + number2
print("Result is: ", result)
elif sign == "-":
result = number1 - number2
print("Result is: ", result)
elif sign == "*":
result = number1 * number2
print("Result is: ", result)
elif sign == "/":
result = number1 / number2
print("Result is: ", result)
else:
print("You didn't enter a valid sign")
# after app executes if or elif, reads numbers and sign
number1 = float(input("Enter first number: "))
sign = input("Enter a sign (+ - * /): ")
# if is not a sign applicaton stops with "Application stopped"
if sign != "*" and sign != "-" and sign != "/" and sign != "+":
sys.exit()
number2 = float(input("Enter second number: "))
except:
print("Application stopped") | true |
893881fa8ba8c601a6e02f9c100d5ff5923c42b3 | sharonbabz44/pythoncodes | /ques1.py | 223 | 4.25 | 4 | name = input("Enter the name")
if len(name)<3:
print ("Name hads to have a mazximum of 3 characters")
elif len(name)>50:
print ("Name has to have a max of 50 characters")
else:
print ("Name looks good")
| true |
8d8e99479e1c0aba2fdba8a9d7ebd0d406f1c360 | LoganHentschel/csp_python | /CSP_Sem1/Living_Code_Final/size_turtle.py | 451 | 4.21875 | 4 | #turtle size should increase when spacebar is pressed; size 1-5, increasing; should go back to size 1 after size 5
import turtle
screen = turtle.Screen()
# # # # #
def size_change():
global current_size
if current_size == 5:
current_size = 0
size_turtle.shapesize(current_size+1)
# # #
size_turtle = turtle.Turtle()
current_size = 0
screen.onkeypress(size_change, 'space')
screen.listen()
# # # # #
screen = turtle.mainloop() | true |
6e030d147f72b22f38adcde76dcd93444319f747 | LewisB53/Python | /hello.py | 1,253 | 4.15625 | 4 | import sys
# Define a main() function that prints a little greeting.
def main():
# Get the name from the command line, using 'World' as a fallback.
if len(sys.argv) >= 2:
name = sys.argv[1]
else:
name = 'World'
print 'Hello', name
# This is the standard boilerplate that calls the main() function.
if __name__ == '__main__':
main()
def secondFunction():
eggs = 12
return eggs
print secondFunction()
"""say what!?
another line thats cool
wow"""
from datetime import datetime
now = datetime.now()
print '%s/%s/%s' % (now.year, now.month, now.day)
print '%s:%s:%s' % (now.hour, now.minute, now.second)
def usingIf():
if 5>1 or 4>1: # Start coding here!
print "this"
return True
elif 1 != 1:
print "that"
return False
else:
print "the other"
return True
usingIf()
def stringMethods():
pyg = 'ay'
original = raw_input('Enter a word:')
if len(original) > 0 and original.isalpha():
word = original.lower()
first = word[0]
new_word = word + first + pyg
new_word = new_word[1:len(new_word)]
print new_word
else:
print 'empty'
return
stringMethods()
| true |
ac36b6fd16ad08987243e84ebfbb7222a6346ffa | KhelassiHub/Project-Euler | /Problem 19/Counting Sundays.py | 1,837 | 4.34375 | 4 | # You are given the following information, but you may prefer to do some research for yourself.
# - 1 Jan 1900 was a Monday.
# - 7 Jan 1900 was a Sunday.
# - Thirty days has September,
# - April, June and November.
# - All the rest have thirty-one,
# - Saving February alone,
# - Which has twenty-eight, rain or shine.
# - And on leap years, twenty-nine.
# - A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
# How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
def main():
months={'January':31,'February':28,'March':31,'April':30,'Mai':31,'June':30,'July':31,'August':31,'September':30,
'October':31,'November':30,'December':31}
print('Starting from 1 January 1900 till 31 December 2000 there are 36890 days')
numberOfDays=0
numberOfSundays=0
realSundayResult=0
# if January 1 1900 was a monday then January 1 1901 was a Tuesday because 1900 has 365 days
for Year in range(1901,2001):
if Year%4==0 and Year%100!=0 or Year%400==0:
months['February']=29
else :
months['February']=28
for days in months.values():
numberOfDays+=days
if (numberOfDays+1)%7==5: # equal to 5 because if the module is equal to 0 we would calculate
# the number Tuesday's that fell in the first of the month (the margin of 5 days between tuesday and
# Sunday is 5 days)
realSundayResult+=1
for i in range(1,numberOfDays+1):
if i%7==0:
numberOfSundays+=1
print(f'Strating from 1 January 19001 till 31 Ddecember 2000 there are {numberOfDays} days')
print(f'The number of Sundays in that period of time is {numberOfSundays} Sunday')
print(f'But the real number of Sundays that fell in the first of the month is {realSundayResult}')
if __name__ == '__main__':
main() | true |
e828ed83f85518a159bd2e93ee35f67bf077566a | KhelassiHub/Project-Euler | /Problem 7/10001st prime.py | 871 | 4.125 | 4 |
# By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
# What is the 10 001st prime number?
def isPrime(n) :
# Special cases
if (n <= 1) :
return False
if (n <= 3) :
return True
# This is checked so that we can skip
# middle five numbers in below loop
if (n % 2 == 0 or n % 3 == 0) :
return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6 # all primes are of the form 6k ± 1
return True
def main():
x=2 # start from the number 2
i=0 # indice of the prime number
while x!=0:
if isPrime(x)==True:
i=i+1
if i==10001:
print("the 10001 prime number is {}".format(x))
break
x=x+1
if __name__ == "__main__":
# execute only if run as a script
main()
| true |
745b473060d66e8ab6d24aafc6e02b5c63f12593 | jianli0/CS5800-Algorithm | /Assignment8/new-bfs.py | 2,416 | 4.125 | 4 | class Queue:
"A container with a first-in-first-out (FIFO) queuing policy."
def __init__(self):
self.list = []
def push(self,item):
"Enqueue the 'item' into the queue"
self.list.insert(0,item)
def pop(self):
"""
Dequeue the earliest enqueued item still in the queue. This
operation removes the item from the queue.
"""
return self.list.pop()
def isEmpty(self):
"Returns true if the queue is empty"
return len(self.list) == 0
def printq(self):
"Print the content of queue"
print self.list[::-1]
graph1 ={1:[5,8],
2:[4,6,7],
3:[4,6,7,8],
4:[3,5,7,8],
5:[3,6],
6:[3,4,5,8],
7:[2],
8:[3,4,5,6]
}
graph2 ={1:[5,8],
2:[4,6,7],
3:[4,6,7,8],
4:[3,5,7,8],
5:[3,6],
6:[3,4,5,8],
7:[2,3],
8:[4,5,6]
}
graph3 ={1:[5,8],
2:[4,6,7],
3:[4,6,7,8],
4:[3,5,7,8],
5:[3,6],
6:[3,4,5,8],
7:[2,3,4],
8:[5,6]
}
graph4 ={1:[5,8],
2:[4,6,7],
3:[4,5,6,8],
4:[3,5,7,8],
5:[3,6,8],
6:[3,4,5,8],
7:[2,3,4],
8:[5,6]
}
graph5 ={1:[5,8],
2:[4,6,7],
3:[4,5,6,8],
4:[3,5,6,7,8],
5:[3,6,8],
6:[3,5,8],
7:[2,3,4],
8:[5,6]
}
graph6 ={1:[5,8],
2:[4,6,7],
3:[5,6,8],
4:[3,5,6,7,8],
5:[3,6,8],
6:[3,5,8],
7:[2,3,4],
8:[5]
}
class Solution:
def __init__(self,graph):
self.graph = graph
self.visited = []
self.parent = {}
for i in self.graph.keys():
self.visited.append(False)
def BFS(self,s):
Q = Queue()
Q.push(s)
self.parent[s] = None
self.visited[s-1] = True
while not Q.isEmpty():
#print "the present queue is "
#Q.printq()
#print "now distance from source node is"
#print self.dist[1:12]
u = Q.pop()
print "(%r -> %r)" %(self.parent[u],u)
for v in self.graph[u]:
if self.visited[v-1] == False:
self.visited[v-1] = True
Q.push(v)
self.parent[v] = u
a = Solution(graph6)
a.BFS(8)
| true |
49bbe2e45f9c86d97476cb6665538cd6a9df1309 | danyentezari/PythonSessions | /tkinter-starter-file.py | 1,281 | 4.34375 | 4 | # Import the tkinter module and include Tk, Label, and Button widgets.
# Note that Tk creates the actual window.
from tkinter import Tk, Label, Button
class MyFirstGUI:
def __init__(self, window):
self.window = window
window.title("A simple GUI")
# Create a Label widget (object)
self.label = Label(window, text="This is our first GUI!")
# Attach the widget to the window
self.label.pack()
# Create a Button widget (object)
self.someButton = Button(window, text="Say Hello", command=self.sayHello)
# Attach the widget to the window
self.someButton.pack()
# Create a Button widget (object)
self.closeButton = Button(window, text="Close Window", command=window.quit)
# Cttach the widget to the window
self.closeButton.pack()
def sayHello(self):
# Check the console for output
print("Greetings!")
# Create a new TK instance (object) called appWindow
appWindow = Tk()
# Create a new instance (object) of the class in this
# and pass appWindow as an argument. Note this is the window
# variable in the class.
myGUI = MyFirstGUI(appWindow)
# The mainloop() method belongs to the Tk() object.
# It will launch the window.
appWindow.mainloop()
| true |
1bc0423601ef9cc8d9e407df446e5fc3b6373672 | bashadmin/pythoncc | /pycc/pycc05.py | 1,665 | 4.34375 | 4 | # In order to help us always set important values, we can use constructor methods
# We can use a special method called constructor
# The consturctor of the class is the method that'[s called when you call the name of the class.
# it's always named init, and this method starts and ends with two underscores.
class Apple():
def __init__(self, name, color, flavor):
self.name = name
self.color = color
self.flavor = flavor
def __str__(self):
return f"""
Name: {golden.name}
Color: {golden.color}
Flavor: {golden.flavor}
"""
golden = Apple("Golden Delicous", "Yellow", "Sweet")
print(golden)
def to_seconds(hours, minutes, seconds):
"""Returns the amount of seconds in the given hours, minutes and seconds"""
return hours*3600+minutes*60+seconds
class Elevator:
def __init__(self, bottom, top, current):
"""Initializes the elevator instance."""
self.bottom = bottom
self.top = top
self.current = current
def up(self):
"""makes the elevator go up one floor."""
self.current += 1
def down(self):
"""makes the elevator go down one floor."""
self.current -= 1
def go_to(self, floor):
"""Makes the elevator go to a specific floor."""
if (self.bottom <= floor <= self.top):
self.current = floor
return "Please try again."
def __str__(self):
return "Top: {}\nBottom: {}\nCurrent: {}".format(self.top, self.bottom, self.current)
ele = Elevator(-1,15,0)
print(ele)
ele.down()
print(ele.current)
ele.go_to(10)
ele.up()
print(ele.current)
ele.go_to(1)
ele.down()
print(ele.current)
| true |
7812f3a1e6e4516e3906454165e80470c7e6dbfb | bashadmin/pythoncc | /pylabs/twt/twtoop03.py | 1,494 | 4.375 | 4 | # Inherentence
"""
class Cat:
def __init__(self, name, age):
self.name = name
self.age = age
def speak(self):
print("Meow")
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def speak(self):
print("Bark")
"""
# Ideally we wouldn't want to have to retype the self.name and self.age because only the speak method is different.
# The is the general class and upper level class
class Animal:
def __init__(self, name, age, species):
self.name = name
self.age = age
self.species = species
def get_info(self):
print(f"Name: {self.name}", f"Age: {self.age}", f"Species: {self.species}", sep="\n")
def speak(self):
print("Sound unknown.")
# This is the lower level class that is inherating from the upper level class
class Cat(Animal):
def __init__(self, name, age, species, color):
super().__init__(name, age, species)
self.color = color
def speak(self):
print("Meow")
def get_info(self):
print(f"Name: {self.name}", f"Age: {self.age}", f"Species: {self.species}", f"Color: {self.color}", sep="\n")
class Dog(Animal):
def speak(self):
print("Bark")
class Fish(Animal):
pass
new_cat01 = Cat("Sam", 12, "Blue Russian", "Orange")
new_dog01 = Dog("Milo", 3, "German Shepherd")
new_dog01.get_info()
new_cat01.speak()
a = Animal("Gary", 1, "Gold Fish")
a.speak()
new_cat01.get_info() | true |
9b3070b2941d3a91e5f545244b8c0a3ec66bdc6e | patricklapgar/Rock_Paper_Scissors_Game | /rps_version_2.py | 1,117 | 4.28125 | 4 | # Rock, Paper, Scissors Game
# There are two versions of this game that will be created.
# The first will be basic version where two players enter their choice and
# only one will win
# The second version will be refactored and more simplified than the first version.
# The third version will have the player be put up against a computer-generated response
print("Rock...")
print("Paper...")
print("Scissors...")
player1 = input("Player 1, make your move:\n")
print("**** NO CHEATING ****\n\n" * 20)
player2 = input("Player 2, make your move:\n")
if player1 == player2:
print("Tie game!!")
elif player1 == "rock":
if player2 == "scissors":
print("player 1 wins!!")
elif player2 == "paper":
print("player 2 wins!!")
elif player1 == "paper":
if player2 == "rock":
print("player 1 wins!!")
elif player2 == "scissors":
print("player 2 wins!!")
elif player1 == "scissors":
if player2 == "rock":
print("player 2 wins!!")
elif player2 == "paper":
print("player 1 wins!!")
else:
print("something went wrong, please enter a choice") | true |
824d06d301b70dfb3cb73b37888bd8e1b76a6d56 | termith/aoc-2020 | /day8/solution.py | 2,292 | 4.25 | 4 | """
Code is represented as a text file with one instruction per line of text.
Each instruction consists of an operation (acc, jmp, or nop) and an argument (a signed number like +4 or -20).
* acc increases or decreases a single global value called the accumulator by the value given in the argument.
For example, acc +7 would increase the accumulator by 7. The accumulator starts at 0.
After an acc instruction, the instruction immediately below it is executed next.
* jmp jumps to a new instruction relative to itself.
The next instruction to execute is found using the argument as an offset from the jmp instruction;
* nop stands for No OPeration - it does nothing. The instruction immediately below it is executed next.
P1. Immediately before any instruction is executed a second time, what value is in the accumulator?
P2. Fix the program so that it terminates normally by changing exactly one jmp (to nop) or nop (to jmp).
What is the value of the accumulator after the program terminates?
"""
from copy import copy
with open('input') as f:
code = list(map(lambda s: s.strip(), f.readlines()))
def detect_loop(code):
idx = 0
acc = 0
while idx != len(code):
if code_copy[idx] is None:
return acc, True
command, number = code_copy[idx].split()
number = int(number)
code_copy[idx] = None
if command == 'nop':
idx += 1
elif command == 'acc':
acc += number
idx += 1
elif command == 'jmp':
idx += number
return acc, False
code_copy = copy(code)
print(detect_loop(code_copy)[0])
NOPS = []
JMPS = []
for i in range(len(code)):
if code[i].startswith('jmp'):
JMPS.append(i)
elif code[i].startswith('nop'):
NOPS.append(i)
for jmp in JMPS:
code_copy = copy(code)
code_copy[jmp] = code_copy[jmp].replace('jmp', 'nop')
acc, is_loop = detect_loop(code_copy)
if not is_loop:
print(f'Index to change: {jmp}, acc is {acc}')
exit(0)
for nop in NOPS:
code_copy = copy(code)
code_copy[nop] = code_copy[nop].replace('nop', 'jmp')
acc, is_loop = detect_loop(code_copy)
if not is_loop:
print(f'Index to change: {nop}, acc is {acc}')
exit(0)
| true |
5afbb257b1634b26c4e8c5993110a63c8062cf74 | damianbao/practice_python | /Py_practice_pr15.py | 205 | 4.15625 | 4 | def flip_it():
phrase = input('Please enter your favorite phrase.\n')
flip = phrase.split()
it =('Reverse it:')
for i in reversed(flip):
it = it + ' ' + i
print (it)
flip_it()
| true |
134db440da7b3f649effe2108c665128610bf04b | kadulemos/Python | /Scrimba/input_exercise.py | 503 | 4.59375 | 5 | # - Create a distance converter converting Km to miles
# - Take two inputs from user: Their first name and the distance in km
# - Print: Greet user by name and show km, and mile values
# - 1 mile is 1.609 kilometers
# - hint: use correct types for calculating and print
# - Did you capitalize the name
name = input('Say your name: ')
km = input('What is the distance in km? ')
miles = float(km)/1.609
msg = f'Hello {name.title()}! The distance in km is {km} and in miles is {round(miles,1)}'
print(msg) | true |
97341ee747be14c238214fb08a7c51f47990d24d | Sachin-12/Solved_problems | /codekata/strings/convert_string.py | 1,213 | 4.28125 | 4 | # Write a program to get a string S, Type of conversion
# (1 - Convert to Lowercase, 2 - Convert to Uppercase) T, and integer P .
# Convert the case of the letters in the positions which are multiples of P.(1 based indexing).
# Input Description:
# Given a string S, Type of conversion T, and integer P
# Output Description:
# Convert the case of the letters and print the string
# Sample Input :
# ProFiLe
# 1
# 2
# Sample Output :
# Profile
import sys
S = input()
T = int(input())
P = int(input())
if P > len(S)-1:
print("Invalid Index")
sys.exit()
def convert_string(s,t,indices):
l = len(s)
new_string = ""
if t == 1:
new_string = ("".join(x.lower() if i in indices else x for i,x in enumerate(s)))
elif t == 2:
new_string = ("".join(x.upper() if i in indices else x for i,x in enumerate(s)))
else:
return 0
return new_string
def indices_to_be_converted(s,p):
l = len(s)
indexes =[]
for i in range(p-1,l,p):
indexes.append(i)
return indexes
indices = indices_to_be_converted(S,P)
result = convert_string(S,T,indices)
print(result) if result else print("Invalid Type") | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.