blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
77eeda8905113f1cbd1d2fe1e13685c814ebe662 | denisefavila/python-playground | /src/linked_list/swap_nodes_in_pair.py | 720 | 4.125 | 4 | from typing import Optional
from src.linked_list.node import Node
def swap_pairs(head: Optional[Node]) -> Optional[Node]:
"""
Given a linked list, swap every two adjacent nodes and return its head.
You must solve the problem without modifying the values in the list's nodes
(i.e., only nodes themselves may be changed.)
"""
dummy = previous_node = Node(0, head)
while previous_node.next and previous_node.next.next:
current_node = previous_node.next
next_node = current_node.next
previous_node.next = current_node.next
current_node.next = next_node.next
next_node.next = current_node
previous_node = current_node
return dummy.next
| true |
45c1771c5a496bf65e92c07f5fcb8a6d5891f5f4 | chuanski/py104 | /LPTHW/2017-04-26-10-31-18.py | 1,422 | 4.53125 | 5 | # -*- coding: utf-8 -*-
# [Learn Python the Hard Way](https://learnpythonthehardway.org/book)
# [douban link](https://book.douban.com/subject/11941213/)
# ex6.py Strings and Text
x = "There are %d types of people." % 10
binary = "binary"
do_not = "don't"
y = "Those who know %s and those who %s." % (binary, do_not)
yy = 'Those who know %s and those who %s.' % (binary, do_not)
yysq = "Those who know %s and those who %s."
#yysq_1 = "Those who know %s and those who %s." % (binary)
yydq = 'Those who know %s and those who %s.'
# - seems that there is no difference between ' and " \
# except which kind of quotation you want to output in the whole sentence.
# - if there are no arguements after the formatting string, the '%s' will be \
# considered as a string but not a format declaration
# - if the number of arguments does not match that of the formatting strings, \
# the interpreter will report an error.
print x
print y
print yy
print yysq
print yydq
print "I said: %r." % x
print "I also said: '%s'." % y
print "I also said: '"' I said: %s."' % y
print "I also said: ' I said: '%r'." % y
# single and double quotations are used consecutively.
hilarious = False # the first letter 'F' is uppercase.
joke_evaluation = "Isn't that joke so funny?! %r"
print joke_evaluation % hilarious
w = "This is the left side of..."
e = "a string with a right side."
print w+e
# CHANGELOG
#
# - 2017-04-26 --create
| true |
4504fdabb7ca47f4c3e20e13050b12971cadb240 | BhagyeshDudhediya/PythonPrograms | /5-list.py | 2,285 | 4.5625 | 5 | #!/usr/bin/python3
import sys;
# Lists are the most versatile of Python's compound data types.
# A list contains items separated by commas and enclosed within square brackets ([]).
# To some extent, lists are similar to arrays in C.
# One of the differences between them is that all the items belonging to a list can be of different data type.
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print ("list: ", list) # Prints complete list
print ("list[0]: ", list[0]) # Prints first element of the list
print ("list[1:3]: ", list[1:3]) # Prints elements starting from 2nd till 3rd
print ("list[2:]: ", list[2:]) # Prints elements starting from 3rd element
print ("tinylist *2: ", tinylist * 2) # Prints list two times
print ("list + tinylist: ", list + tinylist) # Prints concatenated lists
# Lists in python are read-write list, we can change the value of a list variable
list[3] = 'xyz'
print (list)
### TUPLES IN PYTHON ###
print ("\n\n## TUPLES ##")
# A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas.
# Unlike lists, however, tuples are enclosed within parenthesis.
# The main difference between lists and tuples is- Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed,
# while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as read-only lists
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
print ("tuple: ", tuple) # Prints complete tuple
print ("tuple[0]: ", tuple[0]) # Prints first element of the tuple
print ("tuple[1:3]: ", tuple[1:3]) # Prints elements starting from 2nd till 3rd
print ("tuple[2:]: ", tuple[2:]) # Prints elements starting from 3rd element
print ("tinytuple *2: ", tinytuple * 2) # Prints tuple two times
print ("tuple + tinytuple: ", tuple + tinytuple) # Prints concatenated tuples
# Tuples are just readbale, one cannot modify any element in tuple
# Following line when uncommented throws error: TypeError: 'tuple' object does not support item assignment
# tuple[2] = 123
| true |
ed871e8bf632e9db119245d7b68af57af885343a | BhagyeshDudhediya/PythonPrograms | /2-quoted-strings.py | 994 | 4.3125 | 4 | #!/usr/bin/python
# A program to demonstrate use of multiline statements, quoted string in python
import sys;
item_1 = 10;
item_2 = 20;
item_3 = 30;
total_1 = item_1 + item_2 + item_3;
# Following is valid as well:
total_2 = item_1 + \
item_2 + \
item_3 + \
10;
print("total_1 is:", total_1);
print("\ntotal_2 is:", total_2, "\nDone..");
# NOTE: Python does not have multi-line comment feature in it.
# Following is the way quotations are used for a string
# Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals,
# as long as the same type of quote starts and ends the string.
# The triple quotes are used to span the string across multiple lines
word = 'word'
statement = "This is a statement";
multiline_string = """This is a multi-line string
You can call it a paragraph if you wish..!!
Choice is yours..:P""";
print("\n\nWord:", word, "\n\nStatement:", statement, "\n\nMulti-line string: ", multiline_string);
| true |
4df0cac6d76dda3a1af63e399d508cec7159e781 | BhagyeshDudhediya/PythonPrograms | /18-loop-cntl-statements.py | 2,145 | 4.53125 | 5 | #!/usr/bin/python3
# The Loop control statements change the execution from its normal sequence. When the execution leaves a scope,
# all automatic objects that were created in that scope are destroyed.
# There are 3 loop control statements:
# 1. break, 2. continue, 3. pass
# BREAK STATEMENT
# The break statement is used for premature termination of the current loop. After abandoning the loop,
# execution at the next statement is resumed, just like the traditional break statement in C.
# The most common use of break is when some external condition is triggered requiring a hasty exit from a loop.
# The break statement can be used in both while and for loops.
# If you are using nested loops, the break statement stops the execution of the innermost loop and
# starts executing the next line of the code after the block.
print ('Break Statement:');
my_num=int(input('any number: '))
numbers=[11,33,55,39,55,75,37,21,23,41,13]
print ('list', numbers);
for num in numbers:
if num==my_num:
print ('number',my_num,'found in list')
break
else:
print ('number',my_num,'not found in list')
# CONTINUE STATEMENT
# The continue statement in Python returns the control to the beginning of the current loop.
# When encountered, the loop starts next iteration without executing the remaining statements in the current iteration.
# The continue statement can be used in both while and for loops.
print ('\nContinue Statement:');
var = 10 # Second Example
while var > 0:
var = var - 1;
if var == 5:
print ("var == 5, so continue..")
continue
print ('Current variable value :', var)
# PASS STATEMENT
# It is used when a statement is required syntactically but you do not want any command or code to execute.
# The pass statement is a null operation; nothing happens when it executes. The pass statement is also
# useful in places where your code will eventually go, but has not been written yet i.e. in stubs).
print ('\nPass Statement')
for letter in 'Python':
if letter == 'h':
pass
print ('This is pass block')
print ('Current Letter :', letter)
| true |
49da84798e3df53e56671287c625dc5d725e42f3 | Niloy28/Python-programming-exercises | /Solutions/Q14.py | 578 | 4.1875 | 4 | # Write a program that accepts a sentence and calculate the number of upper case letters and lower case letters.
# Suppose the following input is supplied to the program:
# Hello world!
# Then, the output should be:
# UPPER CASE 1
# LOWER CASE 9
in_str = input()
words = in_str.split()
upper_letters = lower_letters = 0
for word in words:
for char in word:
if char.isupper():
upper_letters += 1
elif char.islower():
lower_letters += 1
print(f"UPPER CASE {upper_letters}")
print(f"LOWER CASE {lower_letters}")
| true |
345ce55214f53b15b5c95309c21ad414da483d78 | Niloy28/Python-programming-exercises | /Solutions/Q24.py | 528 | 4.125 | 4 | # Python has many built-in functions, and if you do not know how to use it, you can read document online or find some books. But Python has a built-in document function for every built-in functions.
# Please write a program to print some Python built-in functions documents, such as abs(), int(), raw_input()
# And add document for your own function
def square(root):
'''Return square of root
The input must be an integer'''
return root ** 2
print(abs.__doc__)
print(round.__doc__)
print(square.__doc__)
| true |
da81d7c444c0465736cf3fc0e085db8fa8c607e1 | Niloy28/Python-programming-exercises | /Solutions/Q22.py | 692 | 4.40625 | 4 | # 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
from collections import defaultdict
frequency = dict()
s = input()
words = s.split()
for word in words:
frequency[word] = frequency.get(word, 0) + 1
keys = frequency.keys()
keys = sorted(keys)
for key in keys:
print(f"{key}:{frequency[key]}")
| true |
b2ba0782b339b8a9d555378872260f0bae6852e6 | Niloy28/Python-programming-exercises | /Solutions/Q53.py | 603 | 4.3125 | 4 | # Define a class named Shape and its subclass Square. The Square class has an init function which takes a length as argument.
# Both classes have a area function which can print the area of the shape where Shape's area is 0 by default.
class Shape(object):
def __init__(self, length=0):
pass
def area(self):
return 0
class Square(Shape):
def __init__(self, length):
self.length = length
def area(self):
return self.length ** 2
shape = Shape()
square = Square(3)
print(f"{shape.area():.2f}")
print(f"{square.area():.2f}")
| true |
0870d3f73baba9157e9efc8e59cdf6bf630af41a | Niloy28/Python-programming-exercises | /Solutions/Q57.py | 365 | 4.40625 | 4 | # Assuming that we have some email addresses in the "username@companyname.com" format, please write program to print the user name of a given email address.
# Both user names and company names are composed of letters only.
import re
email_id = input()
pattern = r"([\w._]+)@([\w._]+)[.](com)"
match = re.search(pattern, email_id)
if match:
print(match.group(1))
| true |
0b69e07cf5ee6963767afa0539a63c54292fda1d | olayinka91/PythonAssignments | /RunLenghtEncoding.py | 848 | 4.34375 | 4 | """Given a string containing uppercase characters (A-Z), compress the string using Run Length encoding. Repetition of character has to be replaced by storing the length of that run.
Write a python function which performs the run length encoding for a given String and returns the run length encoded String.
Provide different String values and test your program
Sample Input Expected Output
AAAABBBBCCCCCCCC 4A4B8C"""
def encode(message):
name = message
output = ''
count = 1
for i in range(len(name)):
if i < len(name)-1 and name[i] == name[i+1]:
count += 1
else:
output += str(count) + name[i]
count = 1
return output
#Provide different values for message and test your program
encoded_message=encode("ABBBBCCCCCCCCAB")
print(encoded_message)
| true |
4f701b58fcf157bd5f96991e082a8b00a6bb220c | scottshepard/advent-of-code | /2015/day17/day17.py | 1,869 | 4.125 | 4 | # --- Day 17: No Such Thing as Too Much ---
#
# The elves bought too much eggnog again - 150 liters this time. To fit it all
# into your refrigerator, you'll need to move it into smaller containers.
# You take an inventory of the capacities of the available containers.
#
# For example, suppose you have containers of size 20, 15, 10, 5, and 5 liters.
# If you need to store 25 liters, there are four ways to do it:
#
# 15 and 10
# 20 and 5 (the first 5)
# 20 and 5 (the second 5)
# 15, 5, and 5
#
# Filling all containers entirely, how many different combinations of
# containers can exactly fit all 150 liters of eggnog?
#
# --- Part Two ---
#
# While playing with all the containers in the kitchen, another load of eggnog
# arrives! The shipping and receiving department is requesting as many
# containers as you can spare.
#
# Find the minimum number of containers that can exactly fit all 150 liters of
# eggnog. How many different ways can you fill that number of containers and
# still hold exactly 150 litres?
#
# In the example above, the minimum number of containers was two.
# There were three ways to use that many containers, and so the answer there
# would be 3.
#
# -----------------------------------------------------------------------------
from itertools import combinations
import re
if __name__ == '__main__':
target = 150
fileobject = open('day17.txt')
data = fileobject.read()
containers = [int(x) for x in re.split('\n', data)]
bools = []
lens = []
for i in range(len(containers)):
combos = combinations(containers, i+1)
for combo in combos:
bools.append(sum(combo) == 150)
lens.append(len(combo))
print("Part 1:", sum(bools))
# Correct answer is 1638
print("Part 2:", len([b for n, b in zip(lens, bools) if b and n == 4]))
# Correct answer is 17
| true |
053699bdc95f9bf5833916aca6da13fbe99c4a10 | MatheusL3/python-news | /teste_003.py | 799 | 4.125 | 4 | nome = str(input('Digite seu nome completo: '))
print('Seu nome com todas as letras maiúsculas é {}'.format(nome.upper()))
print('Seu nome com todas as letras minúsculas é {}'.format(nome.lower()))
print('Seu nome contem {} letras ao todo, e {} sem contar espaços'.format(len(nome), len(nome.replace(" ", ""))))
print('A quantidade de letras do primeiro nome é {}'.format(len(nome.split()[0])))
print('O primeiro e o ultimo nome é {} {}'.format(nome.split()[0],nome.split()[len(nome.split())-1]))
print('Seu nome tem Silva? {}'.format("SIM" if (('silva' in nome.lower()) == True) else "NÃO"))
if('silva' in nome.lower()) == True:
print('seu nome tem Silva sim')
elif('lopes' in nome.lower()) == True:
print("o seu nome tem Lopes")
else:
print("seu nome não tem silva nem lopes") | false |
e67363c2be2fc782679324cffb7afa0900c3b493 | NovaStrikeexe/FtermLabs | /Massive.py | 697 | 4.1875 | 4 | import random
n = 0
n = int(input("Enter the number of columns from 2 and more:"))
if n < 2:
print("The array must consist of at least two columns !")
n = int(input("Enter the number of columns from 2 and more:"))
else:
m = [][]
for i in range(0, n):
for j in range(0, n):
m[i][j] = random.randint(0, 200)
print("Massive m:\n", m)
"""n = 0
n = int(input("Enter the number of columns from 2 and more:"))
while n < 2:
print("The array must consist of at least two columns !")
n = int(input("Enter the number of columns from 2 and more:"))
#int N.random(0, 200)
m = [[n for _ in range(0, n)] for _ in range(0, n)]
print(m)""" | true |
fe0004a380012ba1138fc4cb6fce9e167821c673 | NovaStrikeexe/FtermLabs | /SUM LAST AND FIRST.py | 676 | 4.15625 | 4 | print("Start program.....")# 1.42
#Найти сумму первой и последней цифр любого целого положительного числа.
print("====================")
x = int(input("input x:"))
print("====================")
if x < 0:
print("Your x is negative it wouldnt work")
elif x < 10:
print("Only one simbol in list:", x)
else:
arr = list(str(x))
print(arr)
print("====================")
f = int(arr[0])
p = int(arr[-1])
sum = f + p
print("Sum of first and last number =:", sum)
print("====================")
print("End of program")
input("Press <Enter> to close program") | false |
d3d3e1bd76011772b1617b8c1a2ca18b4e6ec080 | NovaStrikeexe/FtermLabs | /list of lists.py | 1,230 | 4.46875 | 4 | #3.49
#Дано натуральное число n>=2, список списков, состоящий из n элементов по n чисел в элементе.
# Список заполняется случайным образом числами из промежутка от 0 до 199.
# Найти количество всех двухзначных чисел, у которых сумма цифр кратна 2.
import random
i = 0
z = 0
j = 0
n = 0
n = int(input("Enter the number of columns from 2 and more:"))
while n < 2:
print("The array must consist of at least two columns !")
n = int(input("Enter the number of columns from 2 and more:"))
m = [[random.randint(0,200) for _ in range(0,n)] for _ in range(0, n)]
print("Massive m:","\n",m)
for lst in m:
for elem in lst:
if 10 < elem < 100:
f = elem // 10
i = elem % 10
#f = int(elem[0])
#p = int(elem[-1])
summa = f + i
if summa % 2 == 0:
z += 1
#print(elem)
print("The number of all two-digit numbers whose sum of digits is a multiple of 2 =", z)
print("End of program")
input("Press <Enter> to close program") | false |
0ee66518a54adf969661ad33b91752d508391bad | scarter13/House-Hunting | /hourly_pay.py | 319 | 4.34375 | 4 | hours_worked = float (input("Enter Hours Worked: "))
hourly_rate = float (input("Enter Hourly Rate: "))
#if you worked more than 40
if hours_worked > 40:
overtime = hours_worked - 40
wages = (40* hourly_rate + overtime * hourly_rate * 1.5)
else:
wages = hours_worked * hourly_rate
print ("Total: $", wages) | false |
d641e7077401b04ab5d5ac4502ba363d71f6def3 | keremh/codewars | /Python/8KYU/reverse_array.py | 222 | 4.21875 | 4 | """
Get the number n to return the reversed sequence from n to 1.
Example : n=5 >> [5,4,3,2,1]
"""
def reverse_seq(n):
n_array = []
i = 0
for i in range(n, 0, -1):
n_array.append(i)
return n_array
| false |
c10f523deaca3b606d195f0c80b8dc16188b913e | userddssilva/Exemplos-introducao-a-programacao | /listas.py | 2,775 | 4.6875 | 5 | """
## Listas em python 3
As listas em python são objetos heterogênios iteráveis, isso significa que podem
armazenar em tempo de execução dados de valores e tipos diferentes.
- Exemplo:
```python
>>> lista = ["NOME 1", 12, "QUIN. B", 1.90]
>>> lista
['NOME 1', 12, 'QUIN. B', 1.9]
```
### Índices
Para acessar os valores de uma lista em python usa-se os índicies, eles podem ser
negativos (-N, ..., -2, -1) e positivos (0, 1, 2, .., N). Os positivos acessam os
itens de forma crescente e os negativos decrescente.
- Exemplo:
```python
>>> lista[0]
NOME 1
>>> lista[3]
1.90
>>> lista[1]
12
>>> lista[-1]
1.90
>>> lista[-2]
QUINT. B
>>> lista[-3]
12
```
### Adicionar itens
Para adicionar itens na lista é possível usando ```.append()```, ```.insert()``
```.extend()``, ```[ ] + [ ]```.
- Exemplo:
```python
>>> lista.append("CENTRO")
>>> lista
['NOME 1', 12, 'QUIN. B', 1.9, 'CENTRO']
>>> lista.insert(-1, 78.4)
>>> lista
['NOME 1', 12, 'QUIN. B', 1.9, 78.4, 'CENTRO']
>>> lista.extend(["MANAUS", "AMAZONAS"])
>>> lista
['NOME 1', 12, 'QUIN. B', 1.9, 78.4, 'CENTRO', 'MANAUS', 'AMAZONAS']
>>> lista = lista + ["BRASIL"]
>>> lista
['NOME 1', 12, 'QUIN. B', 1.9, 78.4, 'CENTRO', 'MANAUS', 'AMAZONAS', 'BRASIL']
```
### Remover itens
Para remover é possível usar ```.pop()```, sem parâmetro remove o últimos elemento,
passando um parâmetro remove o item que tem como índice o parâmtro, caso passe o número
2 remove o item na posição 2. Outra opção é o ```.remove()``` passando como parâmetro o
elemento que se deseja remover. Há ainda a possibilidade de remover todos os elementos
de uma lista usando o ```.clear()```
- Exemplo:
```python
>>> lista.pop()
'BRASIL'
>>> lista
['NOME 1', 12, 'QUIN. B', 1.9, 78.4, 'CENTRO', 'MANAUS', 'AMAZONAS']
>>> lista.pop(2)
'QUIN. B'
>>> lista
['NOME 1', 12, 1.9, 78.4, 'CENTRO', 'MANAUS', 'AMAZONAS']
>>> lista.remove(78.4)
>>> lista
['NOME 1', 12, 1.9, 'CENTRO', 'MANAUS', 'AMAZONAS']
>>> lista.clear()
>>> lista
[]
```
"""
lista_1 = []
lista_1.append(["DAYVSON", 12, "QUIN. B", 1.90])
lista_1.append(["THAYANE", 9, "QUIN. B.", 1.85])
print(lista_1)
for i in range(2):
nome = input(" informe seu nome: ")
idade = input(" informe sua idade: ")
endereco = input(" informe seu endereco: ")
altura = input(" informe sua altura: ")
lista_3 = []
lista_3.append(nome)
lista_3.append(idade)
lista_3.append(endereco)
lista_3.append(altura)
lista_1.append(lista_3)
print(lista_1)
| false |
b51ea3673b3366bc2bc8646a49888b13c2dca444 | sanneabhilash/python_learning | /Concepts_with_examples/inbuild_methods_on_lists.py | 350 | 4.25 | 4 | my_list = [2, 1, 3, 6, 5, 4]
print(my_list)
my_list.append(7)
my_list.append(8)
my_list.append("HelloWorld")
print(my_list)
my_list.remove("HelloWorld") # sorting of mixed list throws error, so removing string
my_list.sort() # The original object is modified
print(my_list) # sort by default ascending
my_list.sort(reverse=True)
print(my_list)
| true |
db7b4af913e90310e154910ef8e11eb52269890b | sanneabhilash/python_learning | /Concepts_with_examples/listOperations.py | 2,139 | 4.40625 | 4 | # List is an ordered sequence of items. List is mutable
# List once created can be modified.
my_list = ["apples", "bananas", "oranges", "kiwis"]
print("--------------")
print(my_list)
print("--------------")
# accessing list using index
print(my_list[0])
print(my_list[3])
# slicing list
print(my_list[1:4])
print(my_list[-2:])
print(my_list[:-2])
print("--------------")
# iterating over list
for item in my_list:
print(item)
print("--------------")
# check if item exists
if "apples" in my_list:
print("Yes")
print("--------------")
# modify list element
my_list[2] = "guava"
print(my_list)
print("---------------")
# list is mutable. try delete an element from list
del my_list[2]
print("list destructor")
# delete list
del my_list
print("--------------")
my_list = ["apples", "bananas", "oranges", "kiwis"]
print("list is mutable. try append an element to an list")
my_list.append("pomegranate")
print(my_list)
print("--------------")
# reverse list
print(my_list[::-1])
print("--------------")
# sort list
print(sorted(my_list))
print("--------------")
# concatenate lists
my_list1 = ["apples", "bananas"]
my_list2 = ["oranges", "kiwis"]
print(my_list1 + my_list2)
print("--------------")
# list index method
my_list = ["apple", "banana", "orange", "kiwi"]
print(my_list.index("orange"))
print("--------------")
# convert a list into set
my_list = ['apples', 'bananas', 'kiwis', 'oranges']
my_list = set(my_list)
print(type(my_list))
print(my_list)
print("--------------")
# convert list to an dictionary
my_list = [['a', "apple"], ['b', "banana"], ['c', "cat"], ['d', "dog"]]
dict1 = dict(i for i in my_list)
print(dict1)
print("--------------")
# convert a list to an string
my_list = ["apple", "banana", "orange", "kiwi"]
strtest = ','.join(my_list)
print(strtest)
# list copy : shallow copy and deep copy methods
import copy
my_list = ["apple", "banana", "orange", "kiwi"]
print("--------------")
new_list = copy.copy(my_list)
print(my_list, id(my_list))
print(new_list, id(new_list))
print("--------------")
new_list = copy.deepcopy(my_list)
print(my_list, id(my_list))
print(new_list, id(new_list)) | true |
01677a7c933fa163221e27a8bea963a35b8888be | oddsorevans/eveCalc | /main.py | 2,991 | 4.34375 | 4 | # get current day and find distance from give holiday (christmas) in this case
from datetime import date
import json
#made a global to be used in functions
holidayList = []
#finds the distance between 2 dates. Prints distance for testing
def dateDistance(date, holiday):
distance = abs(date - holiday).days
print(distance)
return distance
#The holiday has a dummy year, since that could change depending on the current date.
#To get around that, the program finds the year of the next time the holiday will occur
#dependent on the date given
def findYear(date, holiday):
if date.month < holiday.month:
holiday = holiday.replace(date.year)
elif date.month > holiday.month:
holiday = holiday.replace(date.year + 1)
else:
if date.day > holiday.day:
holiday = holiday.replace(date.year + 1)
else:
holiday = holiday.replace(date.year)
return holiday
#check if a given variable is in the list, and return true or false
def findInList(list, variable):
present = False
for i in list:
if i == variable:
present = True
return present
#get user input
def userInput():
desired = input("What holiday would you like to calculate the eve for? Type options for available holidays\n")
#keep window open until they get the correct answer
correctInput = False
while correctInput == False:
if desired == "options":
print(holidayList)
desired = input("What holiday would you like to calculate the eve for? Type options for available holidays\n")
else:
if findInList(holidayList, desired) == True:
correctInput = True
else:
print("That is not a valid holiday")
desired = input("What holiday would you like to calculate the eve for? Type options for available holidays\n")
return desired
def main():
#take contents of json and load into dictionary
holidayDict = {}
scratch = open("holidays.json", 'r')
temp = scratch.read()
holidayDict = (json.loads(temp))
#create list with all the titles so that the user knows input options
#as well as something to check their input on
for i in holidayDict["holidayList"]:
holidayList.append(i)
desired = userInput()
print(holidayDict["holidayList"][desired])
#d1 can be altered to custom date to test year finding function
d1 = date.today()
#1 is a dummy year. Will be used to check if it is a user created year
holiday = date(holidayDict["holidayList"][desired]["year"],holidayDict["holidayList"][desired]["month"],holidayDict["holidayList"][desired]["day"])
holiday = findYear(d1, holiday)
eve = "Merry " + desired
#print out eve for distance. If date distance is 0, it is that day
#and never concatenates eve
for i in range(0, dateDistance(d1, holiday)):
eve = eve + " eve"
eve = eve + "!"
print(eve)
main() | true |
70fec296d60c640fc3f7886ee624a2ca90a16799 | pdeitel/PythonFundamentalsLiveLessons | /examples/ch02/snippets_py/02_06.py | 1,577 | 4.15625 | 4 | # Section 2.6 snippets
name = input("What's your name? ")
name
print(name)
name = input("What's your name? ")
name
print(name)
# Function input Always Returns a String
value1 = input('Enter first number: ')
value2 = input('Enter second number: ')
value1 + value2
# Getting an Integer from the User
value = input('Enter an integer: ')
value = int(value)
value
another_value = int(input('Enter another integer: '))
another_value
value + another_value
bad_value = int(input('Enter another integer: '))
int(10.5)
##########################################################################
# (C) Copyright 2019 by Deitel & Associates, Inc. and #
# Pearson Education, Inc. All Rights Reserved. #
# #
# DISCLAIMER: The authors and publisher of this book have used their #
# best efforts in preparing the book. These efforts include the #
# development, research, and testing of the theories and programs #
# to determine their effectiveness. The authors and publisher make #
# no warranty of any kind, expressed or implied, with regard to these #
# programs or to the documentation contained in these books. The authors #
# and publisher shall not be liable in any event for incidental or #
# consequential damages in connection with, or arising out of, the #
# furnishing, performance, or use of these programs. #
##########################################################################
| true |
4a9dddf948d68d000c1da8065c0d4762eba63a8c | lokesh-pathak/Python-Programs | /ex21.py | 516 | 4.21875 | 4 | # Write a function char_freq() that takes a string and builds a frequency listing of the characters contained in it.
# Represent the frequency listing as a Python dictionary.
# Try it with something like char_freq("abbabcbdbabdbdbabababcbcbab").
def char_freq(str):
frequency = {}
for n in str:
key = frequency.keys()
if n in key:
frequency[n] += 1
else:
frequency[n] = 1
return frequency
#test
print char_freq('abbabcbdbabdbdbabababcbcbab')
print char_freq('qqqqqqqqqbuyfcvadkdnigfnclddncidug')
| true |
0bdc8ceb19ab6e4f6f305bc33ca8682917661dff | lokesh-pathak/Python-Programs | /ex41.py | 1,135 | 4.21875 | 4 | # In a game of Lingo, there is a hidden word, five characters long.
# The object of the game is to find this word by guessing,
# and in return receive two kinds of clues:
# 1) the characters that are fully correct, with respect to identity as well as to position, and
# 2) the characters that are indeed present in the word, but which are placed in the wrong position.
# Write a program with which one can play Lingo. Use square brackets to mark characters correct in the sense of
# 1) and ordinary parentheses to mark characters correct in the sense of
# 2) Assuming, for example, that the program conceals the word "tiger",
# you should be able to interact with it in the following way:
# snake
# Clue: snak(e)
# fiest
# Clue: f[i](e)s(t)
# times
# Clue: [t][i]m[e]s
# tiger
# Clue: [t][i][g][e][r]
def lingo():
word='tiger'
guess=raw_input()
while guess!=word:
pos=-1
output=''
for char in guess:
pos+=1
if char in word:
if word[pos]==guess[pos]:
output+='['+char+']'
else:
output+='('+char+')'
else:
output+=char
print 'clue:' +output
guess=raw_input()
print 'Found!'
#test
lingo()
| true |
8eafb237ab16ac14decc606b7ee80e4e82119196 | lokesh-pathak/Python-Programs | /ex33.py | 918 | 4.84375 | 5 | # According to Wikipedia, a semordnilap is a word or phrase that spells a different word or phrase backwards.
# ("Semordnilap" is itself "palindromes" spelled backwards.)
# Write a semordnilap recogniser that accepts a file name
# (pointing to a list of words) from the user and finds and prints
# all pairs of words that are semordnilaps to the screen.
# For example, if "stressed" and "desserts" is part of the word list,
# the the output should include the pair "stressed desserts".
# Note, by the way, that each pair by itself forms a palindrome!
import re
def Semordnilap():
f=open('file_path','r+')
file=f.readlines()
for line in file:
line = line.strip()
z=list(line.split())
for word in z:
p=word[::-1]
for x in z:
if x==p:
print [word,x]
print ("the line is not semordnilap")
f.close()
#test
# Semordnilap('stressed','desserts')
# Semordnilap('stressed','dessert')
Semordnilap()
| true |
97d90fb94f6427ae1c13eba623ea4e9ce7665670 | lokesh-pathak/Python-Programs | /ex1.py | 269 | 4.28125 | 4 | # Define a function max() that takes two numbers as arguments and returns the largest of them.
# Use the if-then-else construct available in Python.
def max(num1, num2):
if num1 > num2:
return num1
else:
return num2
#test
print max(3, 5)
print max(10, 6)
| true |
a0ea041eeb131dd28038413c9389d99f0290dc32 | GanLay20/The-Python-Workbook-1 | /pyworkbookex024.py | 353 | 4.125 | 4 | print("The Seconds Calculator\n")
days = int(input("Enter the amount of Days:\n>>> "))
hours = int(input("Enter the amount of Hours:\n>>> "))
minutes = int(input("Enter the amount of Minutes:\n>>> "))
day_s = days * 86400
hour_s = hours * 3600
minute_s = minutes * 60
seconds = day_s + hour_s + minute_s
print("The total is:\n", seconds, "seconds") | false |
f4a61563068fa1a16ef68ff5817ff56d76fd7fa0 | GanLay20/The-Python-Workbook-1 | /pyworkbookex046.py | 926 | 4.375 | 4 | print("The Seasons\n")
month = input("Enter the month:\n>>> ")
day = int(input("Enter the day:\n>>> "))
if month == "january" or month == "febuary":
season = "Winter"
elif month == "march":
if day <= 20:
season = "Winter"
else:
season = "Spring"
elif month == "april" or month == "may":
season = "Spring"
elif month == "june":
if day <= 20:
season = "Spring"
else:
season = "Summer"
elif month == "july" or month == "august":
season = "Summer"
elif month == "september":
if day <= 20:
season = "Summer"
else:
season = "Fall"
elif month == "october" or month == "november":
season = "Fall"
elif month == "december":
if day <= 20:
season = "Fall"
else:
season = "Winter"
else:
print("Response Invalid")
season = "Invalid"
print("For the date:", month.title(), day)
print("The season is:", season) | false |
0d043a4d307c675be436b57aacf85851d5d55463 | GanLay20/The-Python-Workbook-1 | /pyworkbookex082.py | 560 | 4.125 | 4 | def main():
print(" Taxi Taxi\n~~~Trip Calculator~~~")
km = float(input("Enter distance travelled in KM:\n>>> "))
taxi_fare(km)
def taxi_fare(km):
'''Calculate a taxi fare'''
distance = 7.1428571428571 # 1km ÷ 140 m (7.14...... km)
set_fee = 4.00
fee = .25 # per 140 m
fare = ((distance * km) * fee) + set_fee
if fare % 5 == 0:
print("Total: $%.2f" % fare)
elif fare % 5 != 0:
fare = round(fare, 1)
print("Total: $%.2f" % fare)
print("\nYou Travelled: %.2f KM" % km)
main() | false |
d242694b3d8ac4b4a5ed9c01c00269ee4c6dca2d | GanLay20/The-Python-Workbook-1 | /pyworkbookex003.py | 226 | 4.125 | 4 | print("The area calculator")
lenth = float(input("Enter The Lenth In Feet >>> "))
width = float(input("Enter The Width In Feet >>> "))
print(lenth)
print(width)
area = lenth * width
print("The Area Is: ", area, " Square Feet") | true |
87e9c3980f14dde7910ba0314d7dd24427849ba2 | GanLay20/The-Python-Workbook-1 | /pyworkbookex014.py | 381 | 4.3125 | 4 | print("Enter you height in FEET followed by INCHES")
feet_height = int(input("Feet:\n>>> "))
inch_height = int(input("Inches:\n>>> "))
print("Your height is", feet_height, "feet", inch_height, "inches\n")
# 1 inch = 2.54cm // 1 foot = 30.48
feet_cm = feet_height * 30.48
inch_cm = inch_height * 2.54
total_height = feet_cm + inch_cm
print("Your height is", total_height, "cm") | true |
f7ce7a2b80cea0e04204a84727743e2b9217a293 | GanLay20/The-Python-Workbook-1 | /pyworkbookex066.py | 1,570 | 4.34375 | 4 | print("~~~~Grade Point Average Calculator~~~~\n")
grade_letter = ()
float_grade = 0
average_count = 0
while grade_letter != "":
grade_letter = input("Enter A Grade Letter:\n>>> ")
average_count += 1
if grade_letter == "a+" or grade_letter == "A+":
float_grade = 4.10 + float_grade
elif grade_letter == "a" or grade_letter == "A":
float_grade = 4.0 + float_grade
elif grade_letter == "a-" or grade_letter == "A-":
float_grade = 3.70 + float_grade
elif grade_letter == "b+" or grade_letter == "B+":
float_grade = 3.50 + float_grade
elif grade_letter == "b" or grade_letter == "B":
float_grade = 3.00 + float_grade
elif grade_letter == "b-" or grade_letter == "B-":
float_grade = 2.7 + float_grade
elif grade_letter == "c+" or grade_letter == "C+":
float_grade = 2.3 + float_grade
elif grade_letter == "c" or grade_letter == "C":
float_grade = 2.0 + float_grade
elif grade_letter == "c-" or grade_letter == "C-":
float_grade = 1.7 + float_grade
elif grade_letter == "D+" or grade_letter == "D+":
float_grade = 1.3 + float_grade
elif grade_letter == "d" or grade_letter == "D":
float_grade = 1.0 + float_grade
elif grade_letter == "f" or grade_letter == "F":
float_grade = 0 + float_grade
elif grade_letter == "":
gpa = float_grade / (average_count - 1)
average_counter = average_count - 1
print("The Grade Point Average Is: %.1f" % gpa)
print("Total Grades Calculated: %.1f "% average_counter) | false |
0e2655f5c91f4ffaf5644430f0e6de8e3c98e23b | GanLay20/The-Python-Workbook-1 | /pyworkbookex036.py | 373 | 4.28125 | 4 | print("Vowel or Consonant")
letter = input("Enter a letter:\n>>> ")
if letter == "a" or letter == "e" or letter == "i" or letter == "o" or letter == "u":
print("The letter", letter.title(), "is a Vowel.")
elif letter == "y":
print("The letter", letter.title(), "is sometimes a Vowel or Consonant.")
else:
print("The letter", letter.title(), "is a Consonant.") | false |
af2e6ddea575ea304623b4f39d8935f1f0e697a0 | GanLay20/The-Python-Workbook-1 | /pyworkbookex055.py | 522 | 4.5 | 4 | print("The 7 Categories Of Radiation\n")
hz = float(input("Enter The Radiation Frequency In Hz:\n>>> "))
type = ""
if hz <= 3 * 10 **9:
type = "Radio Waves"
elif hz <= 3 * 10 **12:
type = "Microwaves"
elif hz <= 4.3 * 10 **14:
type = "Infrared Light"
elif hz <= 7.5 * 10 **14:
type = "Visible Light"
elif hz <= 3 * 10 **17:
type = "Ultraviolet Light"
elif hz <= 3 * 10 **19:
type = "X-Rays"
elif hz > 3 * 10 **19:
type = "Gamma Rays"
print("Radiation With", hz,"Hz Is Categorized As:", type) | false |
123a72dee8b7f8c819a18acea4f3db365cdf9792 | taichi2781/machineLearning | /test.py | 215 | 4.15625 | 4 | print("こんにちは")
print("10+8=",10+8)
print("10-8=",10-8)
print("10*8=",10*8)
print("九九")
for x in range(0,9):
for y in range(0,9):
print('{0}'.format('%2d'%((x+1)*(y+1))), end="")
print('')
| false |
276158e1754954c9cb1017c535d83bdaaff28867 | Iboatwright/mod9homework | /sum_of_numbers.py | 1,750 | 4.53125 | 5 | # sum_of_numbers.py
# Exercise selected: Chapter 10 program 3
# Name of program: Sum of Numbers
# Description of program: This program opens a file named numbers.dat
# that contains a list of integers and calculates the sum of all the
# integers. The numbers.dat file is assumed to be a string of positive
# integers separated by \n.
#
# Ivan Boatwright
# March 19, 2016
def main():
# Local variables
fileName = 'numbers.dat'
nums = []
numSum = 0
# Display the intro to the user.
fluffy_intro()
# Assign the integer contents of the file to the nums array.
get_file_contents(fileName, nums)
# Store the sum of the nums array in the numSum variable.
numSum = sum(nums)
# Display the results to the user.
display_results(fileName, numSum)
return None
# Displays an introduction to the program and describes what it does.
def fluffy_intro():
print('Welcome to the Sum of Numbers program.')
print('This program opens the numbers.dat file and displays')
print('the sum of the integers read from the file.')
return None
# This module accepts the filename and an array by reference as parameters.
# It opens the file, splits the string of integers by the '\n' delimiter,
# converts each string into an integer and stores them in the nums list.
def get_file_contents(fName, nums):
with open(fName,'r') as f:
nums.extend([int(x) for x in f.read().split('\n')[:-1]])
return None
# Displays the summation results to the user.
def display_results(fName, numSum):
sep = '\n\n{}\n\n'.format('-'*79)
print('{0}The sum of all the integers in the {1} file is: {2:>23} {0}'
''.format(sep, fName, numSum))
return None
# Call the main program.
main() | true |
d6a4ee396926531ca232760b942022ba640e8362 | BAFurtado/Python4ABMIpea2019 | /class_da_turma.py | 964 | 4.40625 | 4 | """ Exemplo de uma class construída coletivamente
"""
class Turma:
def __init__(self, name='Python4ABMIpea'):
self.name = name
self.students = list()
def add_student(self, name):
self.students.append(name)
def remove_student(self, name):
self.students.remove(name)
def count_std(self):
return len(self.students)
def list_std(self):
for each in self.students:
print(each)
def __repr__(self):
return '{} tem {} alunos'.format(self.name, self.count_std())
if __name__ == '__main__':
a = Turma()
print(type(a))
print(a)
a.add_student('Sissi')
a.add_student('Esa Pekka')
a.add_student('Gerson')
a.add_student('Marlene')
a.add_student('Rafael')
a.add_student('Francirley')
a.add_student('Sissi')
a.list_std()
a.remove_student('Francirley')
print(a)
b = Turma('Planejamento Estratégico Governamental')
print(b)
| false |
6fea9cb7658163ab3b70cb174d5d78575a8fbc98 | CarolGonz/daily_coding | /camel_case.py | 1,029 | 4.3125 | 4 | # Complete the method/function so that it converts dash/underscore delimited words into camel casing.
# The first word within the output should be capitalized only
# if the original word was capitalized (known as Upper Camel Case, also often referred to as Pascal case).
import re
def to_camel_case(text):
#cria uma lista de strings seprando pelos delimitadores [' ','-', '_']
list_strings = re.split('-| |_|\n',text)
''' checa se a primeira string é lower case, se verdadeiro
cria nova lista excluindo a primeira string e capitaliza cada elemeto
depois junta todas as strings da lista com a primeira string da lista sem capitalizar
'''
if list_strings[0].islower():
new_list = list_strings[1:]
list_capit = [x.capitalize() for x in new_list]
join_strings = ''.join(list_capit)
return list_strings[0]+join_strings
else:
list_capit = [x.capitalize() for x in list_strings]
join_strings = ''.join(list_capit)
return join_strings
| false |
aafc08f19ab42d5f6ca102407c3ebbc3a8fde67d | saikirankondapalli03/HW-05-01 | /new/TestTriangle.py | 1,353 | 4.125 | 4 | from Triangle import classify_triangle
import unittest
class TestCases(unittest.TestCase):
"""This is a testing class for the classify_triangles method"""
def test_equilateral_triangle(self):
assert classify_triangle(1, 1, 1) == 'Equilateral triangle'
assert classify_triangle(100, 100, 100) == 'Equilateral triangle'
assert classify_triangle(0, 0, 0) != 'Equilateral triangle'
def test_right_angled_triangle(self):
"""Test that right triangles are identified"""
assert classify_triangle(15, 17, 8) == 'Right angled triangle'
assert classify_triangle(28, 45, 53) == 'Right angled triangle'
assert classify_triangle(12, 5, 13) == 'Right angled triangle'
def test_isoceles_triangle(self):
assert classify_triangle(10, 10, 10) != 'Isoceles triangle'
assert classify_triangle(5, 5, 3) == 'Isoceles triangle'
def test_Scalene_triangle(self):
assert classify_triangle(13, 9, 14) == 'Scalene triangle'
assert classify_triangle(7.7, 5, 9) == 'Scalene triangle'
def test_invalid_triangle(self):
assert classify_triangle(-1, -1, -9) == 'invalid input'
assert classify_triangle(0, 0, 0) == 'invalid input'
if __name__ == '__main__':
# note: there is no main(). Only test cases here
unittest.main(exit=False, verbosity=2)
| false |
9467d64a8114c389f05ca2e4ededfcd967d6e5a2 | MaxLouis/variables | /Python Basics Math Exercise 2.py | 305 | 4.21875 | 4 | #Max Louis
#Python Basics Math: Exercise 2
#14/09/14
int1 = int(input("What is your first integer?"))
int2 = int(input("What is your second integer?"))
int3 = int(input("What is your third integer?"))
multiply = int1 * int2
total = multiply / int3
print("Your Result is: {0}".format(total))
| false |
c292b92e7d84623749c1c4c704cbfa33f0b01017 | Roman-Rogers/Wanclouds | /Task - 2.py | 522 | 4.34375 | 4 | names = ['ali Siddiqui', 'hamza Siddiqui', 'hammad ali siDDiqui','ghaffar', 'siddiqui ali', 'Muhammad Siddique ahmed', 'Ahmed Siddiqui']
count = 0
for name in names: # Go through the List
lowercase=name.lower() # Lower Case the string so that it can be used easily
splitname=lowercase.split() # Split the name in first, middle, lastname and so on...
length=len(splitname) # Calculate the length so that we search just lastname
if splitname[length-1] == 'siddiqui': # Condition to count names with last name siddiqui
count=count+1
print (count)
| true |
ff2ae3318ec47aefe5035cf1ee4f7ea92bcc3291 | Jay168/ECS-project | /swap.py | 306 | 4.125 | 4 | #swapping variables without using temporary variables
def swapping(x,y):
x=x+y
y=x-y
x=x-y
return x,y
a=input("input the first number A:\n")
b=input("input the second number B:\n")
a,b=swapping(a,b)
print "The value of A after swapping is:",a
print "The value of B after swapping is:",b
| true |
1a233003afdf53e979e155a2c8122012183de4c5 | anurag3753/courses | /david_course/Lesson-03/file_processing_v2.py | 850 | 4.3125 | 4 | """In this new version, we have used the with statement, as with stmt
automatically takes care of closing the file once we are done with the file.
"""
filename = "StudentsPerformance.csv"
def read_file_at_once(filename):
"""This function reads the complete file in a single go and put it into a
text string
Arguments:
filename {str} -- Name of the file
"""
with open(filename, 'r') as f:
data = f.read()
print (data)
# Way 1
read_file_at_once(filename)
def read_file_line_by_line(filename):
"""This function reads the file line-by-line
Arguments:
filename {str} -- Name of file
"""
with open(filename, 'r') as f:
for line in f:
print(line, end='') # It removes the addition of extra newline while printing
# Way 2
read_file_line_by_line(filename) | true |
ca9f27843c8dd606097931adad722688d36d060a | pankajiitg/EE524 | /Assignment1/KManivas_204102304/Q09.py | 676 | 4.40625 | 4 | ## Program to multiply two matrices
import numpy as np
print("Enter the values of m, n & p for the matrices M1(mxn) and M2(nxp) and click enter after entering each element:")
m = int(input())
n = int(input())
p = int(input())
M1 = np.random.randint(1,5,(m,n))
M2 = np.random.randint(1,5,(n,p))
M = np.zeros((m,p),dtype='int16')
print(M1)
print(M2)
print(M)
for i in range(m):
for j in range(p):
for k in range(n):
M[i,j] = M[i,j] + (M1[i,k]*M2[k,j])
print("The elements of resultant matrix, M, using manual calculations is:")
print(M)
print("The elements of resultant matrix, M, using inbuilt function is:")
print(np.matmul(M1,M2))
| true |
50e26426d5913ff0252d1e05fd3d4a26afd04ed1 | pankajiitg/EE524 | /Assignment1/KManivas_204102304/Q03.py | 294 | 4.46875 | 4 | ##Program to print factorial of a given Number
def factorial(num):
fact = 1
for i in range(1,num+1):
fact = fact * i
return fact
print("Enter a number to calculate factorial:")
num1 = int(input())
print("The factorial of ", num1, "is ", factorial(num1))
| true |
a1e0a66a58a5e0d96ddbd2a07424b9b313912a23 | nova-script/Py-Check-IO | /01_Elementary/08.py | 1,247 | 4.46875 | 4 | """
# Remove All Before
## Not all of the elements are important.
## What you need to do here is to remove from the list all of the elements before the given one.
## For the illustration we have a list [1, 2, 3, 4, 5] and we need to remove all elements
## that go before 3 - which is 1 and 2.
## We have two edge cases here: (1) if a cutting element cannot be found,
## then the list shoudn't be changed. (2) if the list is empty, then it should remain empty.
- Input: List and the border element.
- Output: Iterable (tuple, list, iterator ...).
"""
def remove_all_before(items: list, border: int) -> list:
if border not in items:
return items
else:
return items[items.index(border):]
# These "asserts" are used for self-checking and not for an auto-testing
assert list(remove_all_before([1, 2, 3, 4, 5], 3)) == [3, 4, 5]
assert list(remove_all_before([1, 1, 2, 2, 3, 3], 2)) == [2, 2, 3, 3]
assert list(remove_all_before([1, 1, 2, 4, 2, 3, 4], 2)) == [2, 4, 2, 3, 4]
assert list(remove_all_before([1, 1, 5, 6, 7], 2)) == [1, 1, 5, 6, 7]
assert list(remove_all_before([], 0)) == []
assert list(remove_all_before([7, 7, 7, 7, 7, 7, 7, 7, 7], 7)) == [7, 7, 7, 7, 7, 7, 7, 7, 7] | true |
0f882f1f2a162f6fac61d29a40ae0a44b7c6b771 | Tarunmadhav/Python1 | /GuessingGame.py | 419 | 4.25 | 4 | import random
number=random.randint(1,9)
chances=0
print("Guess A Number Between 1-9")
while chances<5:
guess=int(input("Guess A Number 1-9"))
if(guess==number):
print("Congratulations")
break
elif(guess<number):
print("Guess Higher Number")
else:
print("Guess Lesser Number")
chances+=1
if(chances>5):
print("You Loose and The Number is",number) | true |
3c3182c02d122f69bc1aecb800ceb778ccaa6968 | sr-murthy/inttools | /arithmetic/combinatorics.py | 1,277 | 4.15625 | 4 | from .digits import generalised_product
def factorial(n):
return generalised_product(range(1, n + 1))
def multinomial(n, *ks):
"""
Returns the multinomial coefficient ``(n; k_1, k_2, ... k_m)``, where
``k_1, k_2, ..., k_m`` are non-negative integers such that
::
k_1 + k_2 + ... + k_m = n
This number is the coefficient of the term
::
x_1^(k_1)x_2^(k_2)...x_m^(k_m)
(with the ``k_i`` summing to ``n``) in the polynomial expansion
::
(x_1 + x_2 + ... x_m)^n
The argument ``ks`` can be separate non-negative integers adding up to the
given non-negative integer ``n``, or a list, tuple or set of such
integers prefixed by ``'*'``, e.g. ``*[1, 2, 3]``.
"""
return int(factorial(n) / generalised_product(map(factorial, ks)))
def binomial(n, k):
"""
Returns the familiar binomial cofficient - the number of ways
of choosing a set of ``k`` objects (without replacement) from a set of
``n`` objects.
"""
return multinomial(n, k, n - k)
def binomial2(n, k):
"""
Faster binomial method using a more direct way of calculating factorials.
"""
m = min(k, n - k)
return int(generalised_product(range(n - m + 1, n + 1)) / generalised_product(range(1, m + 1))) | true |
4e39eb65f44e423d9695653291c6c15b95920df2 | rocket7/python | /S8_udemy_Sets.py | 695 | 4.1875 | 4 | ###############
# SETS - UNORDERED AND CONTAINS NO DUPLICATES
###############
# MUST BE IMMUTABLE
# CAN USE UNION AND INTERSECTION OPERATIONS
# CAN BE USED TO CLEAN UP DATA
animals = {"dog", "cat", "lion", "elephant", "tiger", "kangaroo"}
print(animals)
birds = set(["eagle", "falcon", "pigeon", "bluejay", "flamingo"])
print(birds)
for animal in birds:
print(animal)
birds.add("woodpecker")
animals.add("woodpecker")
print(animals)
print(birds)
# In the exercise below, use the given lists to print out a set containing all the participants from event A which did not attend event B.
a = ["Jake", "John", "Eric"]
b = ["John", "Jill"]
A = set(a)
B = set(b)
print(A.difference(B))
| true |
dcd02ef61c6b2003024857d5132f8f4d8cf72e01 | venkat284eee/DS-with-ML-Ineuron-Assignments | /Python_Assignment2.py | 605 | 4.46875 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Question 1:
# Create the below pattern using nested for loop in Python.
# *
# * *
# * * *
# * * * *
# * * * * *
# * * * *
# * * *
# * *
# *
# In[1]:
n=5;
for i in range(n):
for j in range(i):
print ('* ', end="")
print('')
for i in range(n,0,-1):
for j in range(i):
print('* ', end="")
print('')
# Question 2:
#
# Write a Python program to reverse a word after accepting the input from the user.
# In[3]:
value = input("Enter a string: " )
for i in range(len(value) -1, -1, -1):
print(value[i], end="")
print("\n")
| true |
faffa16c4ee560cb5fdb32013893bbf83e947ba1 | mrparkonline/py_basics | /solutions/basics1/circle.py | 300 | 4.46875 | 4 | # Area of a Circle
import math
# input
radius = float(input('Enter the radius of your circle: '))
# processing
area = math.pi * (radius ** 2)
circumference = 2 * math.pi * radius
# output
print('The circle area is:', area, 'units squared.')
print('The circumference is:', circumference, 'units.') | true |
c914ff467f6028b7a7e9d6f7c3b710a1445d15e4 | Safirah/Advent-of-Code-2020 | /day-2/part2.py | 975 | 4.125 | 4 | #!/usr/bin/env python
"""part2.py: Finds the number of passwords in input.txt that don't follow the rules. Format:
position_1-position_2 letter: password
1-3 a: abcde is valid: position 1 contains a and position 3 does not.
1-3 b: cdefg is invalid: neither position 1 nor position 3 contains b.
2-9 c: ccccccccc is invalid: both position 2 and position 9 contain c.
"""
import re
valid_passwords_count = 0
lines = [line.rstrip('\n') for line in open("input.txt")]
for line in lines:
match = re.search("(?P<pos_1>\d+)-(?P<pos_2>\d+) (?P<letter>.): (?P<password>.+)", line)
pos_1 = int(match.group('pos_1'))
pos_2 = int(match.group('pos_2'))
letter = match.group('letter')
password = match.group('password')
password_pos_1 = password[pos_1 - 1]
password_pos_2 = password[pos_2 - 1]
if (bool(password_pos_1 == letter) is not bool(password_pos_2 == letter)):
valid_passwords_count = valid_passwords_count + 1
print (f"Valid passwords: {valid_passwords_count}") | true |
17bca95271d269cf806decd0f1efafa05367146c | ycechungAI/yureka | /yureka/learn/data/bresenham.py | 1,424 | 4.125 | 4 | def get_line(start, end):
"""Modified Bresenham's Line Algorithm
Generates a list of tuples from start and end
>>> points1 = get_line((0, 0), (3, 4))
>>> points2 = get_line((3, 4), (0, 0))
>>> assert(set(points1) == set(points2))
>>> print points1
[(0, 0), (1, 1), (1, 2), (2, 3), (3, 4)]
>>> print points2
[(3, 4), (2, 3), (1, 2), (1, 1), (0, 0)]
"""
# Setup initial conditions
x1, y1 = start
x2, y2 = end
dx = x2 - x1
dy = y2 - y1
# Determine how steep the line is
is_steep = abs(dy) > abs(dx)
# Rotate line
if is_steep:
x1, y1 = y1, x1
x2, y2 = y2, x2
# Swap start and end points if necessary
if x1 > x2:
x1, x2 = x2, x1
y1, y2 = y2, y1
# Recalculate differentials
dx = x2 - x1
dy = y2 - y1
# Calculate error
error = int(dx / 2.0)
ystep = 1 if y1 < y2 else -1
# Iterate over bounding box generating points between start and end
prev_x = None
prev_y = None
y = y1
for x in range(x1, x2 + 1):
coord = (y, x) if is_steep else (x, y)
if prev_x is None or prev_x != coord[0]:
yield (0, coord[0])
prev_x = coord[0]
if prev_y is None or prev_y != coord[1]:
yield (1, coord[1])
prev_y = coord[1]
error -= abs(dy)
if error < 0:
y += ystep
error += dx
| true |
f712fa962c06854c9706919f63b52e6a6a6002ab | vasetousa/Python-basics | /Animal type.py | 263 | 4.21875 | 4 | animal = input()
# check and print what type animal is wit, also if it is a neither one (unknown)
if animal == "crocodile" or animal == "tortoise" or animal == "snake":
print("reptile")
elif animal == "dog":
print("mammal")
else:
print("unknown")
| true |
81e59147bf9304406776dc59378b66c5aaa5eaea | ProgramNoona/cti110 | /M6T2_FeetToInches_Reaganb.py | 324 | 4.21875 | 4 | # Program that converts feet to inches
# November 2, 2017
# CTI-110 M6T2_FeetToInches
# Bethany Reagan
INCHES_PER_FOOT = 12
def main():
feet = int(input("Enter a number of feet: "))
print(feet, "feet equals", feetToInches(feet), "inches.")
def feetToInches(feet):
return feet * INCHES_PER_FOOT
main()
| false |
bc25ffa52620a3fd26e1b687452a60cb18dbf75e | Paulokens/CTI110 | /P2HW2_MealTip_PaulPierre.py | 968 | 4.375 | 4 | # Meal and Tip calculator
# 06/23/2019
# CTI-110 P2HW2 - Meal Tip calculator
# Pierre Paul
#
# Get the charge for the food.
food_charge = float(input('Enter the charge for the food: '))
# Create three variables for the tip amounts.
tip_amount1 = food_charge * 0.15
tip_amount2 = food_charge * 0.18
tip_amount3 = food_charge * 0.20
# Create three variables for the meal's total cost.
meal_total_cost1 = food_charge + tip_amount1
meal_total_cost2 = food_charge + tip_amount2
meal_total_cost3 = food_charge + tip_amount3
# Display the result.
print("For a 15% tip, the tip amount is",format(tip_amount1,',.2f'), "and the meal's total cost is",format (meal_total_cost1,",.2f"))
print("For an 18% tip, the tip amount is", format(tip_amount2,',.2f'), "and the meal's total cost is",format (meal_total_cost2,",.2f"))
print("For a 20% tip, the tip amount is", format(tip_amount3, ',.2f'), "and the meal's total cost is",format (meal_total_cost3,",.2f"))
| true |
08bdce0f2d75b36746c86c2ea252adaa3a19741b | michaelzh17/6001_Python | /6001_Python-michael_zhang/isIn.py | 521 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 31 20:59:46 2017
@author: xinyezhang
"""
def isIn(char, aStr):
'''
char: a single character
aStr: an alphabetized string
returns: True if char is in aStr; False otherwise
'''
l = len(aStr)
if l == 0:
return False
elif char == aStr[l//2]:
return True
elif char > aStr[l//2]:
return isIn(char, aStr[l//2 + 1: l])
elif char < aStr[l//2]:
return isIn(char, aStr[0: l//2])
| false |
310f273de1a26854e584fe7da798dc0ef9c21322 | jsavon/final-project | /devel/diceroll.py | 2,408 | 4.125 | 4 | import random
print("")
print("Welcome to Josh's Dice rolling program!")
print("Press enter to roll the die")
input()
number=random.randint(1,6)
if number==1:
print("You rolled a one!")
print("[----------]")
print("[ ]")
print("[ O ]")
print("[ ]")
print("[----------]")
if number==2:
print("You rolled a two!")
print("[----------]")
print("[ ]")
print("[ O O ]")
print("[ ]")
print("[----------]")
if number==3:
print("You rolled a three!")
print("[----------]")
print("[ ]")
print("[ O ]")
print("[ O O ]")
print("[ ]")
print("[----------]")
if number==4:
print("You rolled a four!")
print("[----------]")
print("[ ]")
print("[ O O ]")
print("[ O O ]")
print("[ ]")
print("[----------]")
if number==5:
print("You rolled a five!")
print("[---------]")
print("[ O O ]")
print("[ O ]")
print("[ O O ]")
print("[---------]")
if number==6:
print("You rolled a six!")
print("[---------]")
print("[ O O ]")
print("[ O O ]")
print("[ O O ]")
print("[---------]")
while True:
import random
print("")
print("Press enter to roll again")
input()
number=random.randint(1,6)
if number==1:
print("You rolled a one!")
print("[----------]")
print("[ ]")
print("[ O ]")
print("[ ]")
print("[----------]")
if number==2:
print("You rolled a two!")
print("[----------]")
print("[ ]")
print("[ O O ]")
print("[ ]")
print("[----------]")
if number==3:
print("You rolled a three!")
print("[----------]")
print("[ ]")
print("[ O ]")
print("[ O O ]")
print("[ ]")
print("[----------]")
if number==4:
print("You rolled a four!")
print("[----------]")
print("[ ]")
print("[ O O ]")
print("[ O O ]")
print("[ ]")
print("[----------]")
if number==5:
print("You rolled a five!")
print("[---------]")
print("[ O O ]")
print("[ O ]")
print("[ O O ]")
print("[---------]")
if number==6:
print("You rolled a six!")
print("[---------]")
print("[ O O ]")
print("[ O O ]")
print("[ O O ]")
print("[---------]")
| false |
f27015948ad6042d42f278c8cbd287d46b502e93 | GaryLocke91/52167_programming_and_scripting | /bmi.py | 392 | 4.46875 | 4 | #This program calculates a person's Body Mass Index (BMI)
#Asks the user to input the weight and height values
weight = float(input("Enter weight in kilograms: "))
height = float(input("Enter hegiht in centimetres: "))
#Divides the weight by the height in metres squared
bmi = weight/((height/100)**2)
#Outputs the calculation rounded to one decimal place
print("BMI is: ", round(bmi, 1))
| true |
f1786bf43dc19040524461b7b96c1b0bfb50e5de | zanzero/pyodbc | /test.py | 832 | 4.28125 | 4 | import datetime
from datetime import timedelta
now = datetime.datetime.now()
print("Current date and time using str method of datetime object:")
print(str(now))
d = str(now + timedelta(minutes=2))
print(d[:-3])
print(type(d))
"""
print("Current date and time using instance attributes:")
print("Current year: %d" % now.year)
print("Current month: %d" % now.month)
print("Current day: %d" % now.day)
print("Current hour: %d" % now.hour)
print("Current minute: %d" % now.minute)
print("Current second: %d" % now.second)
print("Current 88888microsecond: %d" % (now.microsecond/1000))
"""
print("Current date and time using strftime:")
time = now.strftime("%Y-%m-%d %H:%M:%S:%f")
print(time[:-3])
print(type(time))
"""
print("Current date and time using isoformat:")
print(now.isoformat())
""" | false |
c216eba9270aac25b2475e80237791e74e26797f | contact2sourabh/Collge-Assignmnt-Python- | /Arithmetic.py | 827 | 4.1875 | 4 | #%%
# Addition
num1=int(input('enter number: '))
num2=int(input('enter 2nd number: '))
sum=num1+num2
print('the sum of ',num1,'and',num2,'is :',sum)
#%%
#Subtraction
num1=int(input('enter number: '))
num2=int(input('enter 2nd number: '))
dif=num1-num2
print('the difference of ',num1,'and',num2,'is :',dif)
#%%
#multiplication
num1=int(input('enter number: '))
num2=int(input('enter 2nd number: '))
product=num1*num2
print('the product of ',num1,'and',num2,'is :',product)
#%%
#division
num1=int(input('enter number: '))
num2=int(input('enter 2nd number: '))
division=num1/num2
print('the division of ',num1,'with',num2,'is :',division)
#%%
# checking data type float
v = 3.14159
print(type(v))
#%%
# for str
v = 'sourabh'
print(type(v))
#%%
# for integer
v = 14159
print(type(v))
| false |
92bc95604d982256a602ef749f090b63b4f47555 | knightscode94/python-testing | /programs/cotdclass.py | 433 | 4.28125 | 4 |
"""
Define a class named Rectangle, which can be constructed by a length and width.
The Rectangle class needs to have a method that can compute area.
Finally, write a unit test to test this method.
"""
import random
class rectangle():
def __int__(self, width, length):
self.width=width
self.length=length
def area():
return length*width
length=random.randint(1,100)
width=random.randint(1,100)
| true |
499cccb2e57239465a929e0a2dc0db0e9d4602b7 | ivankatliarchuk/pythondatasc | /python/academy/sqlite.py | 872 | 4.1875 | 4 | import sqlite3
# create if does not exists and connect to a database
conn = sqlite3.connect('demo.db')
# create the cursor
c = conn.cursor()
# run an sql
c.execute('''CREATE TABLE users (username text, email text)''')
c.execute("INSERT INTO users VALUES ('me', 'me@mydomain.com')")
# commit at the connection level and not the cursor
conn.commit()
# passing in variables
username, email = 'me', 'me@mydomain.com'
c.execute("INSERT INTO users VALUES (?, ?)", (username, email) )
# passing in multiple records
userlist = [
('paul', 'paul@gmail.com'),
('donny', 'donny@gmail.com'),
]
c.executemany("INSERT INTO users VALUES (?, ?)", userlist )
conn.commit()
# passed in variables are tuples
username = 'me'
c.execute('SELECT email FROM users WHERE username = ?', (username,))
print c.fetchone()
lookup = ('me',)
c.execute('SELECT email FROM users WHERE username = ?', lookup )
print c.fetchone()
| true |
0aeaa34a11aef996450483d8026fe6bdc4da6535 | ivankatliarchuk/pythondatasc | /python/main/datastructures/set/symetricdifference.py | 820 | 4.4375 | 4 | """
TASK
Given 2 sets of integers, M and N, print their difference in ascending order. The term symmetric
difference indicates values that exist in eirhter M or N but do not exist in both.
INPUT
The first line of input contains integer M.
The second line containts M space separeted integers.
The third line contains an integer N
The fourth line contains N space separated integers.
CONSTANTS
-----
OUTPUT
Output the symmetric difference integers an ascending order, one per line
SAMPLE INPUT
4
2 4 5 9
4
2 4 11 12
SAMPLE OUTPUT
5
9
11
12
EXPLANATION
-----
"""
M = int(input())
MM = set([int(x) for x in input().split()])
N = int(input())
NN = set([int(x) for x in input().split()])
difference = MM.symmetric_difference(NN)
data = list(difference)
data.sort()
# sorted(list)
for x in data:
print(x)
| true |
b64c41f1627f672833c1998c0230d300d6790763 | OMR5221/MyPython | /Analysis/Anagram Detection Problem/anagramDetect_Sorting-LogLinear.py | 626 | 4.125 | 4 | # We can also sort each of the strings and then compare their values
# to test if the strings are anagrams
def anagramDetect_Sorting(stringA, stringB):
#Convert both immutable strings to lists
listA = list(stringA)
listB = list(stringB)
# Sort using Pythons function
listA.sort()
listB.sort()
continueSearch = True
index = 0
# Compare the two lists
while index < len(listA) and continueSearch:
if listA[index] != listB[index]:
continueSearch = False
else:
index += 1
return continueSearch
print(anagramDetect_Sorting('abcd', 'dcba')) | true |
79a96ea2bf66f92ab3df995e2a330fd51cbae567 | OMR5221/MyPython | /Trees/BinarySearchTree.py | 2,308 | 4.125 | 4 | # BinarySearchTree: Way to map a key to a value
# Provides efficient searching by
# categorizing values as larger or smaller without
# knowing where the value is precisely placed
# Build Time: O(n)
# Search Time: O(log n)
# BST Methods:
'''
Map(): Create a new, empty map
put(key,val): Add a new key, value pair to the map.
If already in place then replace old values
get(key): Find the key in search tree and return value
del: remove key-value in map using del map[key]
len():Return the number of key-value pairs in the map
in: return True/False if key found in map
'''
class BinarySearchTree:
def __init__(self):
self.root = None
self.size = 0
def length(self):
return self.size
def __len__(self):
return self.size
def __iter__(self):
return self.root.__iter__()
class TreeNode:
# Python optional parameters: Use these values if none passed on initialization
def __init__(self,key,val,left=None,right=None,
parent=None):
self.key = key
self.payload = val
self.leftChild = left
self.rightChild = right
self.parent = parent
def hasLeftChild(self):
return self.leftChild
def hasRightChild(self):
return self.rightChild
# Is this Node a left or right child to its parent?
def isLeftChild(self):
return self.parent and self.parent.leftChild == self
def isRightChild(self):
return self.parent and self.parent.rightChild == self
# Rott Node only node without a parent Node
def isRoot(self):
return not self.parent
# Leaf Nodes: No children Nodes
def isLeaf(self):
return not (self.rightChild or self.leftChild)
def hasAnyChildren(self):
return self.rightChild or self.leftChild
def hasBothChildren(self):
return self.rightChild and self.leftChild
def replaceNodeData(self,key,value,lc,rc):
self.key = key
self.payload = value
self.leftChild = lc
self.rightChild = rc
# Update parent reference of this node's children
if self.hasLeftChild():
self.leftChild.parent = self
if self.hasRightChild():
self.rightChild.parent = self | true |
4143917f483f11fde2e83a52a829d73c62fc2fcd | OMR5221/MyPython | /Data Structures/Deque/palindrome_checker.py | 1,264 | 4.25 | 4 | # Palindrome: Word that is the same forward as it is backwards
# Examples: radar, madam, toot
# We can use a deque to get a string from the rear and from the front
# and compare to see if the strings ae the same
# If they are the same then the word is a palindrome
class Deque:
def __init__(self):
self.items = []
# O(1) Operation
def addFront(self, item):
self.items.append(item)
# O(n) operation to shift other elements to the right
def addRear(self, item):
self.items.insert(0, item)
# O(1) Operation
def removeFront(self):
return self.items.pop()
# O(n) operation to shift other elements to the left
def removeRear(self):
return self.items.pop(0)
def isEmpty(self):
return self.items == []
def size(self):
return len(self.items)
def PalindromeChecker(checkWord):
rearDeque = Deque()
for letter in checkWord:
rearDeque.addRear(letter)
stillEqual = True
while rearDeque.size() > 1 and stillEqual:
if rearDeque.removeRear() == rearDeque.removeFront():
stillEqual = True
else:
stillEqual = False
return stillEqual
print(PalindromeChecker("radar"))
print(PalindromeChecker("cook")) | true |
bb8c26d9f183f83582717e8fadc247b21f3c174d | freddieaviator/my_python_excercises | /ex043/my_throw.py | 982 | 4.28125 | 4 | import math
angle = float(input("Input angle in degrees: "))
velocity = float(input("Input velocity in km/h: "))
throw_height = float(input("Input throw height in meter: "))
angle_radian = math.radians(angle)
throw_velocity = velocity/3.6
horizontal_velocity = throw_velocity * math.cos(angle_radian)
vertical_velocity = throw_velocity * math.sin(angle_radian)
ball_airtime = (vertical_velocity + math.sqrt(vertical_velocity**2 + 2*9.81*throw_height))/9.81
throw_distance = horizontal_velocity * ball_airtime
print(f"The throw angle in radians is: {angle_radian:.2f}")
print(f"The throw velocity in m/s is: {throw_velocity:.2f}")
print(f"The throw velocity in the horizontal direction in m/s is: {horizontal_velocity:.2f}")
print(f"The throw velocity in the vertical direction in m/s is: {vertical_velocity:.2f}")
print(f"The ball airtime is: {ball_airtime:.2f}")
print(f"The throw distance is: {throw_distance:.2f}")
#f) a little bit less than 45 degrees for the longest throw. | true |
aad041babf64d755db4dad331ef0f7446a1f7527 | s-ruby/pod5_repo | /gary_brown_folder/temperture.py | 710 | 4.15625 | 4 | '''----Primitive Data Types Challenge 1: Converting temperatures----'''
# 1) coverting 100deg fahrenheit and celsius
# The resulting temperature us an integer not a float..how i know is because floats have decimal points
celsius_100 = (100-32)*5/9
print(celsius_100)
# 2)coverting 0deg fahrenheit and celsius
celsius_0 = (0-32)*5/9
print(celsius_0)
# 3) coverting 34.2deg fahrenheit and celsius
# making a statement without saving any variables
print((34.2-32)*5/9)
# 4) Convert a temperature of 5deg celsius to fahrenheit?
fahrenheit_5 = (9*5)/5+32
print(fahrenheit_5)
# 5) Going to see if 30.2deg celsius or 85.1deg fahrenheit is hotter
whichIsHotterCelsius = (9*30.2)/5+32
print(whichIsHotterCelsius) | true |
8407a85c075e4a560de9a9fbc2f637c79f813c1e | scottbing/SB_5410_Hwk111 | /Hwk111/python_types/venv/SB_5410_Hwk4.2.py | 2,605 | 4.15625 | 4 | import random
# finds shortest path between 2 nodes of a graph using BFS
def bfs_shortest_path(graph: dict, start: str, goal: str):
# keep track of explored nodes
explored = []
# keep track of all the paths to be checked
queue = [[start]]
# return path if start is goal
if start == goal:
# return "That was easy! Start = goal"
return [start]
# keeps looping until all possible paths have been checked
while queue:
# pop the first path from the queue
path = queue.pop(0)
# get the last node from the path
node = path[-1]
if node not in explored:
neighbours = graph[node]
# go through all neighbour nodes, construct a new path and
# push it into the queue
for neighbour in neighbours:
new_path = list(path)
new_path.append(neighbour)
queue.append(new_path)
# return path if neighbour is goal
if neighbour == goal:
return new_path
# mark node as explored
explored.append(node)
# in case there's no path between the 2 nodes
return "A path doesn't exist "
# end def bfs_shortest_path(graph, start, goal):
def main():
graph = {"Omaha" : ["Dallas", "Houston", "Chicago"],
"Louisville" : ["Dallas", "Houston", "Baltimore", "Chicago"],
"Baltimore" : ["Jacksonville", "Louisville", "Houston", "Dallas", "Portland", "Chicago"],
"Portland" : ["Baltimore"],
"Jacksonville" : ["Dallas", "Houston", "Baltimore", "Chicago"],
"Belize City" : [],
"Dallas" : ["Houston", "Baltimore", "Jacksonville", "Louisville", "Chicago", "Omaha"],
"Houston" : ["Dallas" , "Baltimore", "Jacksonville", "Louisville", "Chicago", "Omaha"],
"Chicago" : ["Dallas", "Baltimore", "Jacksonville", "Louisville", "Omaha", "Houston"]
}
path=bfs_shortest_path(graph, 'Omaha', 'Louisville')
print("From Omaha to Louisville: " + str(path))
path1 = bfs_shortest_path(graph, 'Baltimore', 'Jacksonville')
#print("From Baltimore to Jacksonville: " + str(path1))
path2 = bfs_shortest_path(graph, 'Jacksonville', 'Portland')
print("From Baltimore to Jacksonville: " + str(path1) + " to Portland, Maine: " + str(path2))
path = bfs_shortest_path(graph, 'Belize City', 'Portland')
print("From Belize City to Portland, Maine: " + str(path))
# end def main():
if __name__ == "__main__":
main()
| true |
3e7fab66175f06fc91f0df355499eafc95d9d197 | borjamoll/programacion | /Python/Act_07/11.py | 660 | 4.21875 | 4 | #Escribe un programa que te pida una frase, y pase la frase como parámetro a una función.
# Ésta debe devolver si es palíndroma o no , y el programa principal escribirá el resultado por pantalla:
#salta lenin el atlas
#dabale arroz a la zorra el abad
print("Ripios")
palindromo=True
dato=str(input("Dime una palabra o numero: "))
def conversor(x,palindromo):
x=x.replace(" ", "") #Elimino los espacios para que compare los carácteres únicamente.
for z in x:
if str(x) != str(x)[::-1]:
palindromo=False
return(palindromo)
palindromo=conversor(dato,palindromo)
if palindromo==True:
print(dato, end=" es capicua. ")
| false |
bdfbd50066a4fba7c1cbdc0cf774845907450ea3 | chuzirui/vim | /link.py | 894 | 4.25 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class LinkedNode(object):
def __init__(self, value):
self.next = None
self.value = value
def insert_linked(Head, Node):
Node.next = Head.next
Head.next = Node
def print_list(Head):
while (Head):
print (Head.value)
Head = Head.next
def delete_node_list(Head, Node):
while (Head):
if (Head.next == Node):
Head.next = Node.next
return
Head = Head.next
def reverse_list(Head):
c2 = Head.next
Head.next = None
while (c2):
c3 = c2.next
c2.next = Head
Head = c2
c2 = c3
return Head
n1 = LinkedNode(1)
n2 = LinkedNode(2)
n3 = LinkedNode(3)
n4 = LinkedNode(4)
head = n1
insert_linked(head, n2)
insert_linked(head, n3)
insert_linked(head, n4)
print_list(head)
head = reverse_list(head)
print_list(head)
| false |
db8e97cdc0ae8faa35700bfb83502a1d8b0c4712 | Catarina607/Python-Lessons | /new_salary.py | 464 | 4.21875 | 4 |
print('----------------------------------')
print(' N E W S A L A R Y ')
print('----------------------------------')
salary = float(input('write the actual salary of the stuff: '))
n_salary = (26*salary)/100
new_salary = salary + n_salary
print(new_salary, 'is the actual salary')
print('the old salary is ', salary)
print(f'the new salary with + 26% is {new_salary}')
print(f'so the equation is like {salary} + 26% = {new_salary}')
| true |
200971a40d96428969d8266c603620ec6e59c0c6 | michaelvincerra/pdx_codex | /wk1/case.py | 852 | 4.4375 | 4 | """
>>> which_case('this_test_text')
'snake_case.'
>>> which_case('this_is_snake_case')
'snake_case.'
>>> which_case('ThisIsCamelCase')
'CamelCase.'
"""
def which_case(words):
print('Python uses two types of naming for variables and files.')
print('ThisIsCamelCase')
print('this_is_snake_case')
print('Snake or camel? Which case are you?')
words = str(input('Enter a file name using one of the above conventions: >> '))
# words.replace(' ', '')
for word in words:
if '_' in words:
print('That\'s snake_case. So_slithery_smooth!')
elif word.istitle() and ' ' not in words:
print('That\'s CamelCase. GoOnASafari!') # elif user_inp.title() in user_inp:
else:
print('That\'s neither. Thanks for playing. Ciao!')
break
which_case('Words_Are')
| false |
e1c6c077d75f28f7e5a93cfbafce19b01586a26d | michaelvincerra/pdx_codex | /wk1/dice.py | 419 | 4.6875 | 5 | """
Program should ask the user for the number of dice they want to roll
as well as the number of sides per die.
1. Open Atom
1. Create a new file and save it as `dice.py`
1. Follow along with your instructor
"""
import random
dice = input('How many dice?')
sides = input('How may sides?')
roll = random.randint(1, 6)
def dice():
for i in range(int(dice)):
print('Rolling dice.')
print('Roll', roll)
| true |
9faf1d8c84bdf3be3c8c47c8dd6d34832f4a2b1e | vmueller71/code-challenges | /question_marks/solution.py | 1,395 | 4.53125 | 5 | """
Write the function question_marks(testString) that accepts a string parameter,
which will contain single digit numbers, letters, and question marks,
and check if there are exactly 3 question marks between every pair of two
numbers that add up to 10.
If so, then your program should return the string true, otherwise it should
return the string false.
If there aren't any two numbers that add up to 10 in the string, then your
program should return false as well.
For example: if str is "arrb6???4xxbl5???eee5" then your program should
return true because there are exactly 3 question marks between 6 and 4, and
3 question marks between 5 and 5 at the end of the string.
Sample Test Cases
Input:"arrb6???4xxbl5???eee5"
Output:"true"
Input:"aa6?9"
Output:"false"
Input:"acc?7??sss?3rr1??????5ff"
Output:"true"
"""
def question_marks(testString):
# Your code goes here
has_3_question_marks = False
qm_found = 0
start_int = None
for c in testString:
if c.isdigit():
if start_int:
if start_int + int(c) == 10:
if qm_found == 3:
has_3_question_marks = True
else:
return False
start_int = int(c)
qm_found = 0
else:
if c == '?':
qm_found += 1
return has_3_question_marks
| true |
cf9a5b5e82b50692179b47f452a597289a26e3d8 | Juan4678/First-file | /Lección 11 de telusko.py | 757 | 4.375 | 4 | #Tipos de operadores
#OPERADORES ARITMÉTICOS
#Ejemplos
x=2
y=3
print(x,"+",y)
print(x+y)
print(x,"-",y)
print(x-y)
print(x,"*",y)
print(x*y)
print(x,"/",y)
print(x/y)
#OPERADORES DE ASIGNACIÓN
#Ejemplos
X=x+2
print(X)
X+=2
print(X)
X*=3
print(X)
a,b=5,6
print(a)
print(b)
#OPERADOR UNARIO
#Ejemplos
n=7
print(n)
print(-n)
n=-n
print(n)
#OPERADORES RELACIONALES
#Ejemplos
print(a<b)
print(a>b)
print(a==b)
a=6
print(a==b)
print(a<=b)
print(a>=b)
print(a!=b)
b=7
print(a!=b)
#OPERADORES LÓGICOS
#Ejemplos
a=5
b=4
print(a<8 and b<5)
print(a<8 and b<2)
print(a<8 or b<2)
x=True
print(x)
print(not x)
x=not x
print(x)
| false |
844abbd605677d52a785a796f70d3290c9754cd6 | Aishwaryasaid/BasicPython | /dict.py | 901 | 4.53125 | 5 | # Dictionaries are key and value pairs
# key and value can be of any datatype
# Dictionaries are represented in {} brackets
# "key":"value"
# access the dict using dict_name["Key"]
student = {"name":"Jacob", "age":25,"course":["compsci","maths"]}
print(student["course"])
# use get method to inform user if a key doesn't exist in the dictionary
print(student.get("phone","Not Found!"))
# add the dictionary with new key value pair
student["phone"]:["555-000"]
# update as well as add the key value
student.update({'name':'jane', 'age':'18','address':'New Avenue Park,US'})
# delete the key
del student["name"]
print(student)
# In dictionary unlike list, pop takes the key as an argument to delete that specific key-value pair
student.pop("age")
# Access the key of dictionary
print(student.keys())
# Access the value of dictionary
print(student.values())
| true |
cc0bbc28266bb25aa4822ac443fa8d371bb12399 | Akrog/project-euler | /001.py | 1,384 | 4.1875 | 4 | #!/usr/bin/env python
"""Multiples of 3 and 5
Problem 1
Published on 05 October 2001 at 06:00 pm [Server Time]
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
import sys
if (2,7) > sys.version_info or (3,0) <= sys.version_info:
import warnings
warnings.warn("Code intended for Python 2.7.x")
print "\n",__doc__
ceiling = 1000
#----------------
#Trivial solution: O(n)
#----------------
#result = sum([x for x in xrange(ceiling) if (0 == x%3) or (0 == x%5)])
#---------------
#Better solution: O(1)
#---------------
# The idea of this approach is that the sum of the numbers below N multiple of M
# is: M+2M+3M+4M+...+(N/M-1)*M = M * (1+2+3+4+...+(N-1))
# And we know that the addition of 1 to N-1 = (N-1)*N/2
# So we have that the sum of the numbers is: M * (((N-1) * N) / 2)
# For the complete solution we only have to add the sum of multipliers of 3 to
# the sum of multipliers of 5 and take out those of 15 as they were added twice.
def addMults(number, ceiling):
ceil = (ceiling-1)/number
addUpTo = (ceil * (ceil+1)) / 2
return number * addUpTo
result = addMults(3,ceiling) + addMults(5,ceiling) - addMults(15,ceiling)
print "The sum of all the multiples of 3 or 5 below {0} is {1}".format(ceiling,result)
| true |
7d3428fd768e5bf71b26f6e6472cf9efa8c79e8b | khyati-ghatalia/Python | /play_with_strings.py | 387 | 4.15625 | 4 | #This is my second python program
# I am playing around with string operations
#Defing a string variable
string_hello = "This is Khyatis program"
#Printing the string
print("%s" %string_hello)
#Printing the length of the string
print(len(string_hello))
#Finding the first instance of a string in a string
print(string_hello.index("K"))
#Reverse of a string
print(string_hello[::-1]) | true |
962c2ccc73adc8e1a973249d4e92e8286d307bf1 | nihalgaurav/Python | /Python_Assignments/Quiz assignment/Ques4.py | 385 | 4.125 | 4 | # Ques 4. Write a program that accepts a sentence and calculate the number of upper case letters and lower case letters.
s=raw_input()
d={ "UPPER_CASE" :0, "LOWER_CASE" :0}
for c in s:
if c.isupper():
d[ "UPPER_CASE" ]+=1
elif c.islower():
d[ "LOWER_CASE" ]+=1
else:
pass
print("UPPER CASE: ",d[ "UPPER_CASE" ])
print("LOWER CASE: ",d[ "LOWER_CASE" ]) | true |
b44cd8d204f25444d6b5ae9467ad90e539ace8b3 | nihalgaurav/Python | /Python_Assignments/Assignment_7/Ques1.py | 219 | 4.375 | 4 | # Ques 1. Create a function to calculate the area of a circle by taking radius from user.
r = int(input("Enter the radius of circle: "))
def area():
a = r * r * 3.14
print("\nArea of circle is : ",a)
area() | true |
ef4f49af3cb27908f9721e59222418ee63c99022 | antoshkaplus/CompetitiveProgramming | /ProjectEuler/001-050/23.py | 2,599 | 4.21875 | 4 | """
A number n is called deficient if the sum of its proper divisors
is less than n and it is called abundant if this sum exceeds n.
As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16,
the smallest number that can be written as the sum of two abundant
numbers is 24. By mathematical analysis, it can be shown that all
integers greater than 28123 can be written as the sum of two abundant
numbers. However, this upper limit cannot be reduced any further
by analysis even though it is known that the greatest number that
cannot be expressed as the sum of two abundant numbers is less than this limit.
Find the sum of all the positive integers which cannot be written as the sum
of two abundant numbers.
Every integer greater than 20161 can be written as the sum of two abundant numbers.
"""
bound = 20161
# begin finding abundant numbers
from math import sqrt
# returns list of primes in segment [1:n]
def find_primes(n):
primes = []
table = n*[True]
table[0] = False
for i, el in enumerate(table):
if el:
primes.append(i+1)
table[2*i+1:n:i+1] = len(table[2*i+1:n:i+1])*[False]
return primes
# add divisor to set
def add_divisor(res,key,val):
if key in res: res[key]+=val
else: res[key] = val
# add divisors from divs {prime:quantity} dictionary to res
def add_divisors(res,divs):
for key,val in divs.items(): add_divisor(res,key,val)
# returns list dictionary of {prime:quantity}
def find_prime_divisors(bound,primes):
table = [{} for i in range(bound)]
for i in range(bound):
b = int(sqrt(i+1))
div = 0
for p in primes:
if b < p: break
if (i+1)%p == 0:
div = p
break
if div:
add_divisor(table[i],div,1)
if len(table[(i+1)/div-1]) == 0: add_divisor(table[i],(i+1)/div,1)
else: add_divisors(table[i],table[(i+1)/div-1])
return table
primes = find_primes(int(sqrt(bound)))
table = find_prime_divisors(bound,primes)
def sum_of_divisors(divs):
sum = 1
for div,quantity in divs.items():
sum *= (1-div**(quantity+1))/(1-div)
return sum
sums = bound*[0]
for i in range(bound):
sums[i] = sum_of_divisors(table[i])
if table[i] != {}: sums[i] -= i+1
abundants = [i+1 for i in range(bound) if sums[i] > i+1]
# end abundant numbers
print "here"
is_sum_of_two_abundants = bound*[False]
for i,a in enumerate(abundants):
for b in abundants[i:]:
if a+b <= bound:
is_sum_of_two_abundants[a+b-1] = True
else: break
print "here"
print sum([i+1 for i,val in enumerate(is_sum_of_two_abundants) if not val])
| true |
cf1c83c8cabc0620b1cdd1bc8ecf971e0902806f | pgavriluk/python_problems | /reverse_string.py | 406 | 4.21875 | 4 | def reverse(string):
str_list=list(string)
length = len(string)
half = int(length/2)
for i, char in enumerate(str_list):
last_char = str_list[length-1]
str_list[length-1] = char
str_list[i] = last_char
length = length-1
if i >= half-1:
break;
return ''.join(str_list)
print(reverse('Hi, my name is Pavel!'))
| true |
918c366baca272bcaef30e1e0e1106769b1610fa | ramsayleung/leetcode | /200/ugly_number_ii.py | 1,318 | 4.15625 | 4 | """
source: https://leetcode.com/problems/ugly-number-ii/
author: Ramsay Leung
date: 2020-03-30
Write a program to find the n-th ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.
Example:
Input: n = 10
Output: 12
Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.
1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18k
1, 2, 3, 2*2,4,2*3,2*2*2,3*3,2*5,2*2*3,3*5,2*2*2*2,2*3*3,2*2*5,2*2*2*3, 2*2*2*2*2
Note:
1 is typically treated as an ugly number.
n does not exceed 1690.
"""
import bisect
# xxxxx i dp.append(i) if i/2 in dp or i/3 in dp or i/5 in dp
class Solution:
# @profile
def nthUglyNumber(self, n: int) -> int:
dp = [1]
# convert to dict to improve search performance. List search is O(n),
# dict search is O(1)
search = {1: 0}
i = 1
counter = 1
for i in dp:
if i*2 not in search:
bisect.insort(dp, i * 2)
search[i*2] = 0
if i*3 not in search:
bisect.insort(dp, i * 3)
search[i*3] = 0
if i*5 not in search:
bisect.insort(dp, i * 5)
search[i*5] = 0
counter += 1
if counter >= n:
return dp[n-1]
| false |
c963de87cbf668a579a6de35ed4873c07b64ee90 | ramsayleung/leetcode | /600/palindromic_substring.py | 1,302 | 4.25 | 4 | '''
source: https://leetcode.com/problems/palindromic-substrings/
author: Ramsay Leung
date: 2020-03-08
Given a string, your task is to count how many palindromic substrings in this string.
The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.
Example 1:
Input: "abc"
Output: 3
Explanation: Three palindromic strings: "a", "b", "c".
Example 2:
Input: "aaa"
Output: 6
Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
'''
# time complexity: O(N**2), N is the length of `s`
# space complexity: O(1)
class Solution:
def countSubstrings(self, s: str) -> int:
strLen = len(s)
result = 0
for i in range(strLen):
# when len of palidrome is odd, i means the middle number
result += self.countPalindromic(s, i, i)
# when len of palidrome is event, i means the middle left number, i+1 means the middle right number
result += self.countPalindromic(s, i, i + 1)
return result
def countPalindromic(self, s: str, left: int, right: int) -> int:
result = 0
while (left >= 0 and right < len(s) and s[left] == s[right]):
left -= 1
right += 1
result += 1
return result | true |
350ff920efd20882b4b138110612d4a6ad08b378 | RobertEne1989/python-hackerrank-submissions | /nested_lists_hackerrank.py | 1,312 | 4.40625 | 4 | '''
Given the names and grades for each student in a class of N students, store them in a nested list and
print the name(s) of any student(s) having the second lowest grade.
Note: If there are multiple students with the second lowest grade, order their names alphabetically and
print each name on a new line.
Example
records = [["chi", 20.0], ["beta", 50.0], ["alpha", 50.0]]
The ordered list of scores is [20.0, 50.0], so the second lowest score is 50.0.
There are two students with that score: ["beta", "alpha"].
Ordered alphabetically, the names are printed as:
alpha
beta
Input Format
The first line contains an integer,N, the number of students.
The 2N subsequent lines describe each student over 2 lines.
- The first line contains a student's name.
- The second line contains their grade.
Constraints
2 <= N <= 5
There will always be one or more students having the second lowest grade.
'''
students = []
students_f = []
scores = set()
for _ in range(int(input())):
name = input()
score = float(input())
students.append([score, name])
scores.add(score)
second_lowest = sorted(scores)[1]
for score, name in students:
if score == second_lowest:
students_f.append(name)
for name in sorted(students_f):
print(name)
| true |
a89e546c4a3f3cd6027c3a46e362b23549eee2d0 | RobertEne1989/python-hackerrank-submissions | /validating_phone_numbers_hackerrank.py | 1,136 | 4.4375 | 4 | '''
Let's dive into the interesting topic of regular expressions! You are given some input, and you are required
to check whether they are valid mobile numbers.
A valid mobile number is a ten digit number starting with a 7, 8 or 9.
Concept
A valid mobile number is a ten digit number starting with a 7, 8 or 9.
Regular expressions are a key concept in any programming language. A quick explanation with Python examples
is available here. You could also go through the link below to read more about regular expressions in Python.
https://developers.google.com/edu/python/regular-expressions
Input Format
The first line contains an integer N, the number of inputs.
N lines follow, each containing some string.
Constraints
1 <= N <= 10
2 <= len(Number) <= 15
Output Format
For every string listed, print "YES" if it is a valid mobile number and "NO" if it is not on separate lines.
Do not print the quotes.
'''
N = int(input())
a = ""
for i in range(N):
a = input()
if len(a) == 10 and a[0] in ['7', '8', '9'] and a.isnumeric():
print('YES')
else:
print('NO') | true |
8d3e58e5049ef80e24a22ea00340999334358eb2 | RobertEne1989/python-hackerrank-submissions | /viral_advertising_hackerrank.py | 1,709 | 4.1875 | 4 | '''
HackerLand Enterprise is adopting a new viral advertising strategy. When they launch a new product,
they advertise it to exactly 5 people on social media.
On the first day, half of those 5 people (i.e.,floor(5/2)=2) like the advertisement and each shares it with 3 of
their friends. At the beginning of the second day, floor(5/2) x 3 = 2 x 3 = 6 people receive the advertisement.
Each day, floor(recipients/2) of the recipients like the advertisement and will share it with 3 friends
on the following day.
Assuming nobody receives the advertisement twice, determine how many people have liked the ad by the end
of a given day, beginning with launch day as day 1.
Example
n = 5
Day Shared Liked Cumulative
1 5 2 2
2 6 3 5
3 9 4 9
4 12 6 15
5 18 9 24
The progression is shown above. The cumulative number of likes on the 5'th day is 24.
Function Description
Complete the viralAdvertising function in the editor below.
viralAdvertising has the following parameter(s):
int n: the day number to report
Returns
int: the cumulative likes at that day
Input Format
A single integer,n, the day number.
Constraints
1 <= n <= 50
'''
import math
import os
import random
import re
import sys
def viralAdvertising(n):
shared=5
cumulative=0
for d in range(1,n+1):
liked=shared//2
shared=liked*3
cumulative=cumulative+liked
return cumulative
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
result = viralAdvertising(n)
fptr.write(str(result) + '\n')
fptr.close()
| true |
dfaea68c6693f63cce8638bb978077536a7dcecc | medetkhanzhaniya/Python | /w3/set.py | 2,461 | 4.71875 | 5 | """
#CREATE A SET:
thisset={"a","b","c"}
print(thisset)
ONCE A SET CREATED
YOU CANNOT CHANGE ITS ITEMS
BUT YOU CAN ADD NEW ITEMS
#SETS CANNOT HAVE 2 ITEMS WITH SAME VALUE
thisset = {"apple", "banana", "cherry"}
print("banana" in thisset)
#out:true
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)
#add new item to set
thisset = {"apple", "banana", "cherry"}
tropical = {"pineapple", "mango", "papaya"}
thisset.update(tropical)
print(thisset)
#add elements from one set to another
#you can also add elements of a list to at set
#REMOVE ITEMS
thisset = {"apple", "banana", "cherry"}
thisset.remove("banana")
print(thisset)
#out:{'apple', 'cherry'}
#REMOVE LAST ITEM
thisset = {"apple", "banana", "cherry"}
x = thisset.pop()
print(x)
print(thisset)
#cherry
#{'banana', 'apple'}
#EMPTIES THE SET
thisset = {"apple", "banana", "cherry"}
thisset.clear()
print(thisset)
#out:set()
#DELETE THE SET COMPLETELY
thisset = {"apple", "banana", "cherry"}
del thisset
print(thisset)
#returns a new set with all items from both sets
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)
#out:{1, 2, 3, 'a', 'b', 'c'}
#inserts the items in set2 into set1
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set1.update(set2)
print(set1)
#union()и update()исключают повторяющиеся элементы.
#ВЫВОДИТ ЭЛЕМЕНТЫ КОТОРЫЕ ЕСТЬ И В СЕТ1 И В СЕТ2
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.intersection_update(y)
print(x)
#out:{'apple'}
#ДОБАВЛЯЕТ ОБЩИЙ ЭЛЕМЕНТ В НОВЫЙ СЕТ
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.intersection(y)
print(z)
#выводит все элементы кроме общих элементы
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.symmetric_difference_update(y)
print(x)
#out:{'microsoft', 'google', 'cherry', 'banana'}
#добавляет все необщие элементы в новый сет
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.symmetric_difference(y)
print(z)
#out:{'google', 'microsoft', 'banana', 'cherry'}
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "facebook"}
z = x.isdisjoint(y)
print(z)
""" | true |
b17cb584cf6c78c34f6e1c7b78670fb90a9b58dd | manumuc/python | /rock-paper-scissors-lizard-spock.py | 1,905 | 4.28125 | 4 | <pre>[cc escaped="true" lang="python"]
# source: https://www.unixmen.com/rock-paper-scissors-lizard-spock-python/
#Include 'randrange' function (instead of the whole 'random' module
from random import randrange
# Setup a dictionary data structure (working with pairs efficientlyconverter = ['rock':0,'Spock':1,'paper':2,'lizard':3,'scissors':4]
# retrieve the names (aka key) of the given number (aka value)
def number_to_name(number):
If (number in converter.values()):
Return converter.keys()[number]
else:
print ('Error: There is no "' + str(number) + '" in ' + str(converter.values()) + '\n')
# retrieve the number (aka value) of the given names (aka key)
def name_to_number(name):
If (name in converter.keys()):
Return converter[name]
else:
print ('Error: There is no "' + name + '" in ' + str(converter.keys()) + '\n')
def rpsls(name):
player_number = name_to_number(name)
# converts name to player_number using name_to_number
comp_number = randrange(0,5)
# compute random guess for comp_number using random.randrange()
result = (player_number - comp_number) % 5
# compute difference of player_number and comp_number modulo five
# Announce the opponents to each other
print 'Player chooses ' + name
print 'Computer chooses ' + number_to_name(comp_number)
# Setup the game's rules
win = result == 1 or result == 2
lose = result == 3 or result == 4
# Determine and print the results
if win:
print 'Player wins!\n'
elif lose:
print 'Computer wins!\n'
else:
print 'Player and computer tie!\n'
# Main Program -- Test my code
rpsls("rock")
rpsls("Spock")
rpsls("paper")
rpsls("lizard")
rpsls("scissors")
# Check my Helper Function reliability in case of wrong input
#number_to_name(6)
# Error in case of wrong number
#name_to_number('Rock')
# Error in case of wrong name
[/cc]</pre>
| true |
fb8a10f89fc38052190a480da6eeeacf88d6dd22 | govind-mukundan/playground | /python/class.py | 2,379 | 4.28125 | 4 | # Demo class to illustrate the syntax of a python class
# Illustrates inheritance, getters/setters, private and public properties
class MyParent1:
def __init__(self):
print ("Hello from " + str(self.__class__.__name__))
class MyParent2:
pass
# Inheriting from object is necessary for @property etc to work OK
# This is called "new style" classes
class MyClass(object, MyParent1, MyParent2): # Multiple inheritance is OK
"======== My Doc String ==========="
def __init__(self, param1=None): # __init__ is like a constructor, it is called after creating an object. By convention it's the first method of a class
MyParent1.__init__(self) # Initialize our parent(s), MUST be done explicitly
self.__private_prop1 = "I'm Private" # Declare and initialize our object (private) properties
self.public_prop1 = "I'm Public" # Declare and initialize our object (public) properties
self.__public_prop2__ = "I'm also Public" # Declare and initialize our object (public) properties
## self["name"] = param1 # To use this syntax you need to define the __setitem__() function
# Property1 is exposed using getters and setters. Similarly a "deleter" can also be declared using @prop_name.deleter
@property
def public_prop1(self):
print("Getting value")
return self.__public_prop1
@public_prop1.setter
def public_prop1(self, value):
print("Setting value")
self.__public_prop1 = value + "++setter++"
# Destructor
def __del__(self):
print("Don't delete me!")
# Context manager used along with the WITH keyword
# https://docs.python.org/2/reference/compound_stmts.html#with
# https://eli.thegreenplace.net/2009/06/12/safely-using-destructors-in-python/
if __name__ == "__main__":
o1 = MyClass("Govind")
o2 = MyParent1()
print(o1.public_prop1)
## print(o1.__private_prop1) --> Won't run
print(o1._MyClass__private_prop1) # However this works
# More about introspection -> https://docs.python.org/3/library/inspect.html
print(o1.__dict__) # because the interpreter mangles names prefixed with __name to _class__name
print(o1.__public_prop2__)
# Equivalence of Objects
ox = o1
if ox is o1:
print("ox and o1 point to the same memory location = " + str(id(ox)))
| true |
c0e4b60e7bdac2719ee37a944fcc4add4bbb1264 | Jhang512/driving | /driving.py | 378 | 4.21875 | 4 | country = input('What is your nationality: ')
age = input('How old are you: ')
age = int(age)
if country == 'taiwan':
if age >= 18:
print('You can learn driving')
else:
print('You cannot learn driving')
elif country == 'usa':
if age >= 16:
print('You can learn driving')
else:
print('You cannot learn driving')
else:
print('Please enter either usa or taiwan.....') | false |
d3b3a2f39945050d6dd423146c794965069ead21 | jdipietro235/DailyProgramming | /GameOfThrees-239.py | 1,521 | 4.34375 | 4 |
# 2017-05-17
# Task #1
# Challenge #239, published 2015-11-02
# Game of Threes
"""
https://www.reddit.com/r/dailyprogrammer/comments/3r7wxz/20151102_challenge_239_easy_a_game_of_threes/?utm_content=title&utm_medium=browse&utm_source=reddit&utm_name=dailyprogrammer
Back in middle school, I had a peculiar way of dealing with super boring classes. I would take my handy pocket calculator and play a "Game of Threes". Here's how you play it:
First, you mash in a random large number to start with. Then, repeatedly do the following:
If the number is divisible by 3, divide it by 3.
If it's not, either add 1 or subtract 1 (to make it divisible by 3), then divide it by 3.
The game stops when you reach "1".
While the game was originally a race against myself in order to hone quick math reflexes, it also poses an opportunity for some interesting programming challenges. Today, the challenge is to create a program that "plays" the Game of Threes.
"""
def start():
print("start")
print("this program will take a number\nand will reduce it to 0 by")
print("subtracting and dividing by 3")
kickoff()
def kickoff():
var = int(input("Submit a number greater than 1:\n"))
runner(var)
def runner(var):
if(var == 1):
print("Done!")
kickoff()
elif(var % 3 == 0):
varX = var / 3
print(str(varX) + " = " + str(var) + " / 3")
runner(varX)
else:
varX = var - 1
print(str(varX) + " = " + str(var) + " - 1")
runner(varX)
start()
| true |
330ba20a83c20ecb7df2e616379023f74631ee2c | olutoni/pythonclass | /control_exercises/km_to_miles_control.py | 351 | 4.40625 | 4 | distance_km = input("Enter distance in kilometers: ")
if distance_km.isnumeric():
distance_km = int(distance_km)
if distance_km < 1:
print("enter a positive distance")
else:
distance_miles = distance_km/0.6214
print(f"{distance_km}km is {distance_miles} miles")
else:
print("You have not entered an integer")
| true |
924d7324d970925b0f26804bc135ffd318128745 | olutoni/pythonclass | /recursion_exercise/recursion_prime_check.py | 332 | 4.21875 | 4 | # program to check if a number is a prime number using recursion
number = int(input("enter number: "))
def is_prime(num, i=2):
if num <= 2:
return True if number == 2 else False
if num % i == 0:
return False
if i * i > num:
return True
return is_prime(num, i+1)
print(is_prime(number))
| true |
10c70c24825c0b8ce1e9d6ceb03bd152f3d2d0c1 | slohmes/sp16-wit-python-workshops | /session 3/2d_arrays.py | 1,149 | 4.21875 | 4 | '''
Sarah Lohmeier, 3/7/16
SESSION 3: Graphics and Animation
2D ARRAYS
'''
# helper function
def matrix_print(matrix):
print '['
for i in range(len(matrix)):
line = '['
for j in range(len(matrix[i])):
line = line + str(matrix[i][j]) + ', '
line += '],'
print line
print ']'
# A regular array holds a single line of information:
array = [0, 0, 0, 0,]
# Which is a problem if we want to store a grid.
# We can solve this by storing arrays inside arrays-- essentially creating a matrix:
example_matrix = [
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
]
matrix_print(example_matrix)
# We can access an entire row in a matrix:
print example_matrix[0]
example_matrix[0] = [2, 0, 0, 0]
#matrix_print(example_matrix)
# We can also access single elements by specifying what row and column they're in:
example_matrix[1][2] = 4
matrix_print(example_matrix)
# This is the basis for manipulating pixels on a screen.
# With the right GUI (http://www.codeskulptor.org/#poc_2048_gui.py), it's also the basis for 2048!
# http://www.codeskulptor.org/#user34_cHRBjzx8rx_114.py
| true |
8aa48619ba0e0741d001f061041aa944c7ee6d05 | amysimmons/CFG-Python-Spring-2018 | /01/formatting.py | 471 | 4.28125 | 4 | # STRING FORMATTING
age = 22
like = "taylor swift".title()
name = "Amy"
print "My age is {} and I like {}".format(age, like)
print "My age is 22 and I like Taylor Swift"
print "My age is {1} and I like {0}".format(age, like)
print "My age is Taylor Swift and I like 22"
print "My name is {}, my age is {} and I like {}".format(name, age, like)
# # What would we expect?
# print "testing"
# print "xxx {name}, xxx{age}, xxx{like}".format(name=name, age=age, like=like)
| true |
297a5886f75bde1bb4e8d1923401512848dcc53f | abhinashjain/codes | /codechef/Snakproc.py | 2,698 | 4.25 | 4 | #!/usr/bin/python
# coding: utf-8
r=int(raw_input())
for i in xrange(r):
l=int(raw_input())
str=raw_input()
ch=invalid=0
for j in str:
if((j=='T' and ch!=1) or (j=='H' and ch!=0)):
invalid=1
break
if(j=='H' and ch==0):
ch=1
if(j=='T' and ch==1):
ch=0
if(invalid or ch):
print "Invalid\n"
else:
print "Valid\n"
'''
The annual snake festival is upon us, and all the snakes of the kingdom have gathered to participate in the procession. Chef has been tasked with reporting on the procession, and for
this he decides to first keep track of all the snakes. When he sees a snake first, it'll be its Head, and hence he will mark a 'H'. The snakes are long, and when he sees the snake
finally slither away, he'll mark a 'T' to denote its tail. In the time in between, when the snake is moving past him, or the time between one snake and the next snake, he marks with
'.'s.
Because the snakes come in a procession, and one by one, a valid report would be something like "..H..T...HTH....T.", or "...", or "HT", whereas "T...H..H.T", "H..T..H", "H..H..T..T"
would be invalid reports (See explanations at the bottom).
Formally, a snake is represented by a 'H' followed by some (possibly zero) '.'s, and then a 'T'. A valid report is one such that it begins with a (possibly zero length) string of '.
's, and then some (possibly zero) snakes between which there can be some '.'s, and then finally ends with some (possibly zero) '.'s.
Chef had binged on the festival food and had been very drowsy. So his report might be invalid. You need to help him find out if his report is valid or not.
Input
The first line contains a single integer, R, which denotes the number of reports to be checked. The description of each report follows after this.
The first line of each report contains a single integer, L, the length of that report.
The second line of each report contains a string of length L. The string contains only the characters '.', 'H', and 'T'.
Output
For each report, output the string "Valid" or "Invalid" in a new line, depending on whether it was a valid report or not.
Constraints
1 ≤ R ≤ 500
1 ≤ length of each report ≤ 500
Example
Input:
6
18
..H..T...HTH....T.
3
...
10
H..H..T..T
2
HT
11
.T...H..H.T
7
H..T..H
Output:
Valid
Valid
Invalid
Valid
Invalid
Invalid
Explanation
"H..H..T..T" is invalid because the second snake starts before the first snake ends, which is not allowed.
".T...H..H.T" is invalid because it has a 'T' before a 'H'. A tail can come only after its head.
"H..T..H" is invalid because the last 'H' does not have a corresponding 'T'.
'''
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.