blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
f67082924240fd2b8dd73006bde9e35a005342ba | yuryanliang/Python-Leetcoode | /100 medium/6/299 bulls-and-cows.py | 2,780 | 4.25 | 4 | """
You are playing the following Bulls and Cows game with your friend: You write down a number and ask your friend to guess what the number is. Each time your friend makes a guess, you provide a hint that indicates how many digits in said guess match your secret number exactly in both digit and position (called "bulls") and how many digits match the secret number but locate in the wrong position (called "cows"). Your friend will use successive guesses and hints to eventually derive the secret number.
Write a function to return a hint according to the secret number and friend's guess, use A to indicate the bulls and B to indicate the cows.
Please note that both secret number and friend's guess may contain duplicate digits.
Example 1:
Input: secret = "1807", guess = "7810"
Output: "1A3B"
Explanation: 1 bull and 3 cows. The bull is 8, the cows are 0, 1 and 7.
Example 2:
Input: secret = "1123", guess = "0111"
Output: "1A1B"
Explanation: The 1st 1 in friend's guess is a bull, the 2nd or 3rd 1 is a cow.
Note: You may assume that the secret number and your friend's guess only contain digits, and their lengths are always equal.
"""
# https://leetcode.com/problems/bulls-and-cows/
class Solution:
def getHint(self, secret, guess):
bull = 0
cow = 0
lookup ={}
for i, val in enumerate(secret):
if val == guess[i]:
bull +=1
else:
lookup[val] =lookup.get(val, 0)+1
for i, val in enumerate(secret):
if val != guess[i] and lookup.get(guess[i], 0)!=0:
cow +=1
lookup[guess[i]]-=1
return str(bull)+"A"+str(cow)+"B"
def get(self, secret, guess):
bull = 0
cow = 0
lookup = {}
for i, val in enumerate(secret):
if val == guess[i]:
bull +=1
else:
lookup[val]=lookup.get(val, 0) + 1
for i, val in enumerate(secret):
if val != guess[i] and lookup.get(guess[i], 0)!=0:
cow +=1
lookup[guess[i]]-=1
return str(bull)+"A"+str(cow)+"B"
class Solution:
def getHint(self, secret, guess):
d = {}
bull, cow = 0, 0
for index, s in enumerate(secret):
if guess[index] == s:
bull += 1
else:
d[s] = d.get(s, 0) + 1
for index, s in enumerate(secret):
if (guess[index] != s) & (d.get(guess[index], 0) != 0):
cow += 1
d[guess[index]] -= 1
return str(bull) + "A" + str(cow) + "B"
if __name__ == '__main__':
# secret = "1807"
# guess = "7810"
secret = "1123"
guess = "0111"
print(Solution().getHint(secret, guess))
| true |
a551c51e0aba623ab79b53dc7b9ea1c039f1e3cc | ZdenekPazdersky/python-academy | /Lesson8/8.49_prime_numbers.py | 2,704 | 4.46875 | 4 | # ####2DO
# Your goal in this task is to create two functions:
#
# 1. list_primes
# Function that will list all the prime numbers up to the specified limit, e.g. list_primes(10) will list all the prime numbers from 0 to 10 including. The function should return a set or a list of prime numbers found.
#
# Example of using list_primes() function:
#
# >>> list_primes(54)
# {11, 13, 17, 19, 2, 23, 29, 3, 31, 37, 41, 43, 47, 5, 53, 7}
# 2. is_prime
# Function that will tell, whether a number is prime. It will take one argument of type int and return a boolean value.
#
# Example of using is_prime() function:
#
# >>> is_prime(54)
# False
# >>> is_prime(53)
# True
# Algorithm to list prime numbers
# To generate a list of prime numbers, you will probably want to follow algorithm designed by Eratosthenes:
#
# Create a list of consecutive integers from 2 through n: (2, 3, 4, ..., n).
#
# Initially, let p equal 2, the smallest prime number.
#
# Enumerate the multiples of p (prime number) by counting from 2p (prime number multiplied by 2) to n (limit) in increments of p, and erase them from the list of generated numbers (these will be 2p, 3p, 4p, ...; the p itself should not be erased).
#
# Find the first number greater than p in the list that is not marked. If there was no such number, stop. Otherwise, let p now equal this new number (which is the next prime), and repeat from step 3.
#
# When the algorithm terminates, the numbers remaining not erased in the list are all the primes below n.
# #######
def list_primes(end):
_list = list(range(2, end + 1)) #list of all numbers in the range except 0,1
index = 0
while _list[index]:
prime = _list[index]
to_remove = prime
while to_remove <= end:
to_remove += prime #will remove multiplies from prime numbers
if to_remove in _list: #check if exist in the list to avoid error
_list.remove(to_remove)
index += 1
if index >= len(_list): #prevent to be out of list range
break
return _list
def is_prime(end_Nr):
return end_Nr in list_primes(end_Nr)
#print(list_primes(53))
print(is_prime(53))
# #Engeto solution
# #Comments: result of the 1st function is set -disadv unordered
# #result of the function is built new, total list number is being reduced - no need to use indexing
# def list_primes(n):
#
# nums = list(range(2,n+1))
# result = set()
#
# while nums:
# i = nums.pop(0)
# result.add(i)
# for num in nums:
# if num % i==0:
# nums.remove(num)
# return result
#
# def is_prime(n):
# return n in list_primes(n)
#
# print(is_prime(23))
# ################ | true |
461dee7e05ee938b79e15b20ef369149601d91ba | ZdenekPazdersky/python-academy | /Lesson1/1.7-List.py | 1,435 | 4.3125 | 4 | #2do
# Create script, which will:
#
# assign an empty list to variable candidates,
# print the content of variable candidates introducing it with a string 'Candidates at the beginning:',
# assign a list to variable employees, containing strigns: 'Francis', 'Ann', 'Jacob', 'Claire',
# print employees content introducing it with a string 'Employees at the beginning:',
# add the names 'Bruno' and 'Agnes' to the empty 'candidates' list,
# print the content of candidates introducing it with a string 'New names added to candidates:',
# insert the name 'Bruno' stored in the candidate list into the` employees' list at index 1,
# print the content of the employees variable introducing it with a string: 'New names added to employees':
# Create Candidate
candidates = []
# Print candidates at the beginning
print("Candidates at the beginning:", candidates)
# Create employees
employees = ["Francis", "Ann", "Jacob", "Claire"]
# Print employees at the beginning
print("Employees at the beginning:", employees)
# Add new candidates
#candidates = candidates + ["Bruno", "Agnes"]
candidates.append("Bruno")
candidates.append("Agnes")
# Print new candidates
print("New names added to candidates:", candidates)
# Insert name
employees.insert(1, candidates[0]) #To Insert Bruno from list candidates into employees list at index1
# Print the employees list after entering a new name
print("New names added to employees: ", employees) | true |
f6174ef98fe1c5fbe6b16402f882c82c8e9e39ea | ZdenekPazdersky/python-academy | /Lesson1/1_buying_cars.py | 929 | 4.375 | 4 | # ###2do
# #In the Python window you already have Mercedes and Rolls-Royce prices listed (don't forget to covert string to integer!). In addition, you have to create a variable that will ask the user for the extra cost. Then you will need to calculate:
# The price for two Mercedes,
# The Mercedes and Rolls-Royce prices,
# The price of two Rolls-Royce with extra equipment (each),
# Price for Mercedes with optional equipment.
# Finally, the program should print down everything clearly. Go ahead!
# ###
# Prices
mercedes = 150
rolls_royce = '400'
rolls_royce = int(rolls_royce)
extra_cost=int(input("Enter extra cost:"))
price_1=2*mercedes
price_2=mercedes+rolls_royce
price_3=2*(rolls_royce+extra_cost)
price_4=mercedes+extra_cost
print("PRICE TABLE:")
print("2xMercedes |", price_1)
print("Mercedes+Rolls-Royce |", price_2)
print("2x extra Rolls-Royce |", price_3)
print("extra Mercedes |", price_4) | true |
05b84ffa87c8d326935e1ac2aab5f0e027d9b5e0 | ZdenekPazdersky/python-academy | /Lesson7/7.41_reversed.py | 978 | 4.40625 | 4 | ####2DO
# Your task is to create a function that will imitate the built-in function reversed(). It will take any sequence as an input and will return a list of items from the original sequence in reversed order.
#
# Example of using the function:
#
# >>> reversed(range(10))
# [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
# >>> reversed(['New', 'Years', 'Eve'])
# ['Eve', 'Years', 'New']
# >>> reversed('Hello World')
# ['d', 'l', 'r', 'o', 'W', ' ', 'o', 'l', 'l', 'e', 'H']
#######
def my_reversed(seq):
rev_seq = []
for index in range(0, len(seq)):
rev_seq.append(seq[len(seq) - 1 - index])
return rev_seq
test = ['Eve', 'Years', 'New']
print(test, type(test))
print(my_reversed(test))
print(my_reversed(range(10)))
print(my_reversed('Hello world'))
# Engeto solution
def my_reversed(sequence):
return list(sequence[::-1])
def my_reversed(sequence):
result = []
for item in sequence:
result.insert(0, item)
return result
################
| true |
0c736360ff83966e361a231021f6b9e6b9482ed3 | mmaravilla28/tarea_3 | /calculadora.py | 2,689 | 4.125 | 4 | #definir clase CalculadoraBasica
class CalculadoraBasica:
#Menu de opciones
def Menu(self):
print('\n1)SUMAR 2)RESTAR 3)MULTIPLICAR 4)DIVIDIR 5)SALIR')
#constructor de la clase
def iniciar(self, num1, num2):
self.num1 = num1
self.num2 = num2
#función para sumar los números
def sumar(self):
print('La suma de {} + {} es = {}'.format(operacion.num1, operacion.num2, int(self.num1) + int(self.num2)))
#función para restar los números
def restar(self):
print('La resta de {} - {} es = {}'.format(operacion.num1, operacion.num2, int(self.num1) - int(self.num2)))
#función para multiplicar los números
def multiplicar(self):
print('La multiplicación de {} * {} es = {}'.format(operacion.num1, operacion.num2, int(self.num1) * int(self.num2)))
#función para dividir los números
def dividir(self):
if int(num2) == 0:
print('No se puede dividir por cero')
else:
print('La división de {} / {} es = {}'.format(operacion.num1, operacion.num2, int(self.num1) / int(self.num2)))
#se instancia el objeto operación con la clase CalculadoraBasica
operacion = CalculadoraBasica()
operacion.Menu()
opcion = input('\nSeleccione un operación para iniciar: ')
#mientras la opción selecciona este dentro del rango se ejecuta la operación
while (int(opcion) > 0 and int(opcion) < 5):
#se solicitan los dos núemros para realizar la operación seleccionada
num1 = input('\nDigite el primer número: ')
num2 = input('Digite el segundo número: ')
#se inicializan los valores de los dos numeros digitados
operacion.iniciar(num1, num2)
#se verifica la opción para realizar la operación respectiva
if int(opcion) == 1:
operacion.sumar()
operacion.Menu()
opcion = input('\nSeleccione un operación para iniciar: ')
elif int(opcion) == 2:
operacion.restar()
operacion.Menu()
opcion = input('\nSeleccione un operación para iniciar: ')
elif int(opcion) == 3:
operacion.multiplicar()
operacion.Menu()
opcion = input('\nSeleccione un operación para iniciar: ')
elif int(opcion) == 4:
operacion.dividir()
operacion.Menu()
opcion = input('\nSeleccione un operación para iniciar: ')
| false |
eb7e32e6c9d29fe746f5e48e3cc82bd0ae3f7018 | 4BPencil/hello-world | /salary_with_try_except_loops.py | 491 | 4.15625 | 4 | #asking for input
h=input("hours: ")
r=input("rate: ")
#nutrilizing input errors
try:
ih=float(h)
ir=float(r)
except:
ih=-1
ir=-1
#re-asking for input if there are some errors
while ih==-1 or ir==-1:
print("Please enter a numerical value")
h=input("hours: ")
r=input("rate: ")
try:
ih=float(h)
ir=float(r)
except:
ih=-1
ir=-1
#result
salary=ih*ir
isalary=int(salary)
print("Thanks, the salary is", isalary, "MAD")
| true |
2d7c28b85fb3133aaba47533de077cdd16e4a802 | yohanesusanto/Markovchaintextgenerator | /markov_chain_text_generator.py | 2,486 | 4.21875 | 4 | # https://blog.upperlinecode.com/making-a-markov-chain-poem-generator-in-python-4903d0586957
# I found this on the web where a text-file is read, first. Following this, for each word in
# the text-file as key, a Python-Dictionary of words-that-immediately-followed-the-key was
# constructed. We start from a random-initial-key and pick (at random) the next-word from
# the dictionary (using the first-word as key). This process repeats till sufficient words
# of text have been generated.
import random
import sys
import argparse
# have to remove multiple occurrences of spaces etc in the training text
def remove_values_from_list(the_list, val):
return [value for value in the_list if value != val]
# form a single string that contains the entire novel as training data...
INPUT_FILENAME = str(sys.argv[1])
#INPUT_FILENAME = 'thegreatgatsby'
training_text = open(INPUT_FILENAME, "r").read()
#training_text = open(INPUT_FILENAME, "r", encoding = "ISO-8859-1").read()
# split the string into its constituent words (got this part from the web)
training_text = ''.join([i for i in training_text if not i.isdigit()]).replace("\n", " ").split(' ')
# This process the list of poems. Double line breaks separate poems, so they are removed.
# Splitting along spaces creates a list of all words.
# remove blank-spaces
training_text = remove_values_from_list(training_text, '')
training_text = remove_values_from_list(training_text, ' ')
# the length of the generated text
generated_text_length = int(sys.argv[2])+0
#generated_text_length = 200
index = 1
chain = {}
# This loop creates a dictionary called "chain". Each key is a word, and the value of each key
# is an array of the words that immediately followed it.
for word in training_text[index:] :
key = training_text[index - 1]
if key in chain :
chain[key].append(word)
else:
chain[key] = [word]
index += 1
#random first word
word1 = random.choice(list(chain.keys()))
message = word1.capitalize()
# Picks the next word over and over until word count achieved
while len(message.split(' ')) < generated_text_length:
word2 = random.choice(chain[word1])
word1 = word2
message += ' ' + word2
#OUTPUT_FILENAME = str(sys.argv[3])
OUTPUT_FILENAME = 'output.txt'
# creates new file with output
with open(OUTPUT_FILENAME, "w") as file:
file.write(message)
#uncomment rows below to print it in the terminal
#output = open(OUTPUT_FILENAME,"r")
#print(output.read())
| true |
57367bee7da71ff6af5f18f68296240fda53b7d1 | gkimetto/PyProjects | /GeneralPractice/ListComprehension.py | 415 | 4.21875 | 4 |
x = [i for i in range(10)]
print(x)
squares = []
squares = [i**2 for i in range(10)]
print(squares)
inlist = [lambda i:i%3==0 for i in range(5)]
print(inlist)
# a list comprehension
cubes = [i**3 for i in range(5)]
print(cubes)
# A list comprehension can also contain an if statement to enforce
# a condition on values in the list.
# Example:
evens=[i**2 for i in range(10) if i**2 % 2 == 0]
print(evens) | true |
d6fca675a0adb8f5a09db74ccc24d3b540ceb578 | gkimetto/PyProjects | /GeneralPractice/OddOrEven.py | 2,323 | 4.375 | 4 | '''
Exercise 2:
Ask the user for a number. Depending on whether the number is even or odd,
print out an appropriate message to the user. Hint: how does an
even / odd number react differently when divided by 2?
Extras:
If the number is a multiple of 4, print out a different message.
Ask the user for two numbers: one number to check (call it num) and one
number to divide by (check). If check divides evenly into num,
tell that to the user. If not, print a different appropriate message.
'''
def get_number():
input_number=int(input("Enter a number to check : "))
return input_number
def check_odd_or_even(int_number):
str_number=str(int_number)
if int_number%2==0:
print "The number {} is an even number ".format(str_number)
else:
print "The number {} is an odd number ".format(str_number)
def extra_if_multiple_of_four(int_number):
int_number =int(int_number)
if (int_number%4 == 0):
#int_number=str(int_number)
print "The number {} is a multiple of 4. ".format(int_number)
else:
print "The number {} is NOT a multiple of 4.".format(int_number)
def get_two_numbers():
num =int(input("Please enter the first number :" ))
check = int(input("Please enter the second number :"))
if num%check ==0:
num= str(num)
check= str(check)
print "The number {} is a multiple of {}".format(num, check)
else:
num = str(num)
check = str(check)
print "The number {} is NOT a multiple of {}".format(num,check)
def main():
while(1):
print "Welcome to ODD or EVEN checker: "
print "-"*50
print "0.) Enter a number to Test."
print "1.) Check if number is ODD or EVEN."
print "2.) Check if it's a multiple of 4. "
print "3.) Enter 2 numbers."
print "4.) Quit."
choice = input("Make a Selection 0 - 4. [4 to Quit ]")
if choice == 0:
int_number=get_number()
elif choice == 1:
int_number = get_number()
check_odd_or_even(int_number)
elif choice ==2:
int_number = get_number()
extra_if_multiple_of_four(int_number)
elif choice ==3:
get_two_numbers()
else:
exit()
if __name__=="__main__":
main() | true |
b413b106ed1265d8fbfd7748c0d04678475d9c04 | Teju-28/321810304018-Python-assignment3 | /321810304018-Three strings comparision.py | 658 | 4.5 | 4 | #!/usr/bin/env python
# coding: utf-8
# ## Take three inputs from user and check:
#
# 1. all are equal
# 2. any two are equal
# In[1]:
str1=str(input("Enter first string:"))
str2=str(input("Enter second string:"))
str3=str(input("Enter third string:"))
if (str1==str2==str3):
print("All Strings are equal")
elif (str1==str2 and (str1!=str3 or str2!=str3)):
print("First and Second strings are equal")
elif (str1==str3 and (str1!=str2 or str3!=str2)):
print("First and Third strings are equal")
elif (str2==str3 and (str2!=str1 or str3!=str1)):
print("Second and Third strings are equal")
else:
print("All strings are not equal")
| true |
49f65af45d020264ca9c06467432b2c80784e5af | dongyuehanxue/python | /untitled/python_yunsuanfu.py | 2,623 | 4.5 | 4 | """
Python位运算符
& 按位与运算符:参与运算的两个值,如果两个相应位都为1,则该位的结果为1,否则为0
| 按位或运算符:只要对应的二个二进位有一个为1时,结果位就为1。
^ 按位异或运算符:当两对应的二进位相异时,结果为1
~ 按位取反运算符:对数据的每个二进制位取反,即把1变为0,把0变为1 。~x 类似于 -x-1
<< 左移动运算符:运算数的各二进位全部左移若干位,由 << 右边的数字指定了移动的位数,高位丢弃,低位补0。
>> 右移动运算符:把">>"左边的运算数的各二进位全部右移若干位,>> 右边的数字指定了移动的位数
"""
"""
Python逻辑运算符
and 布尔"与"
如果 x 为 true,x and y 返回 y 的计算值
如果 x 或 y为 False,x and y 返回 False
or 布尔"或"
如果 x 为 true,它返回 x 的值
如果 x 是0,它返回 y 的计算值,如果 y 是0,它返回 x 的计算值
not 布尔"非" - 如果 x 为 True,返回 False 。如果 x 为 False,它返回 True
"""
a = 0
b = 0
# a = 0
# b = 0
# if(a and b):
# print (a and b)
# print "a、b都是true"
# else:
# print (a and b)
if (a or b):
print(a or b)
print("a、b都为true,或有一个为true")
else:
print("a/b都为false")
# if True:
# print "ddd"
# else:
# print "qq"
"""
Python成员运算符
in 如果在指定的序列中找到值返回 True,否则返回 False
not in 如果在指定的序列中没有找到值返回 True,否则返回 False
"""
a = 1
list = [1, 2, 3, 4]
if (a in list):
print("变量a在list中")
if (a not in list):
print("变量a不在list中")
"""
Python身份运算符
身份运算符用于比较两个对象的存储单元
is 是判断两个标识符是不是引用自一个对象
x is y, 类似 id(x) == id(y) , 如果引用的是同一个对象则返回 True,否则返回 False
is not 是判断两个标识符是不是引用自不同对象
x is not y , 类似 id(a) != id(b)。如果引用的不是同一个对象则返回结果 True,否则返回 False
id() 函数用于获取对象内存地址
"""
a = 20
b = 20
if (a is b):
print("a/b有相同标识")
else:
print("a/b没有相同标识")
# a = 30
if (a is not b):
print("a/b没有相同标识")
else:
# print 默认输出是换行的,如果要实现不换行需要在变量末尾加上 end="":
print("a/b有相同标识")
# print("a/b有相同标识", a, end="")
# is 用于判断两个变量引用对象是否为同一个, == 用于判断引用变量的值是否相等 | false |
1dd8680331523d8688ae20e57dd58800f4d01a99 | luke-mao/Data-Structures-and-Algorithms-in-Python | /chapter2/example_vector.py | 1,705 | 4.5625 | 5 | """
textbook example: class Vector
"""
class Vector:
""" Represent a vector in a multi-dimensional space"""
def __init__(self, d):
if not d >= 1:
raise ValueError("Dimension number must >= 1")
self._coordinates = [0] * d
def __len__(self):
return len(self._coordinates)
def __getitem__(self, j):
if j < -len(self._coordinates) or j >= len(self._coordinates): # index can be negative
raise ValueError("Index out of bound")
return self._coordinates[j]
def __setitem__(self, j, val):
if j < -len(self._coordinates) or j >= len(self._coordinates): # index can be negative
raise ValueError("Index out of bound")
if not isinstance(val, (int, float)):
raise ValueError("Input value must be either int or float")
self._coordinates[j] = val
def __add__(self, other):
if len(self) != len(other):
raise ValueError("Dimension must be equal")
result = Vector(len(self)) # use the __init__
for j in range(len(self)):
result[j] = self[j] + other[j] # use __getitem__
return result
def __eq__(self, other):
return self._coordinates == other._coordinates
def __ne__(self, other):
return self._coordinates != other._coordinates
def __str__(self):
return "<{}>".format(','.join([str(i) for i in self._coordinates]))
if __name__ == '__main__':
v = Vector(5)
v[1] = 23
v[-1] = 45
v[2] = 50
print(str(v))
print(v[2])
u = v + v
print(str(u))
print(u == u)
# g = Vector(0)
| false |
8e9a5d0c7b5e4fd51b61170d49ec38caeedf3df3 | luke-mao/Data-Structures-and-Algorithms-in-Python | /chapter7/q1.py | 1,203 | 4.1875 | 4 | """
find the second-to-last node in a singly linked list.
the last node is indicated by a "next" reference of None.
Use two pointers: this idea is quite common in Leetcode
"""
from example_singly_linked_list import SinglyLinkedList
def find(linked_list):
# import a linked list, find the second-to-last node, print the value
# if the list is purely None, return None
# if the list only 1 element, return None
# for other: return the second-to-last node
if linked_list._head is None:
return None
elif linked_list._head._next is None:
return None
else:
prev = linked_list._head
current = prev._next
while current is not None:
prev = prev._next
current = current._next
return prev
if __name__ == '__main__':
q = SinglyLinkedList()
for i in range(20):
q.add(i)
q.show()
print(find(q)._element)
q2 = SinglyLinkedList()
q2.show()
if find(q2) is None:
print("None")
else:
print(find(q2))
q3 = SinglyLinkedList()
q3.add(3)
q3.show()
if find(q2) is None:
print("None")
else:
print(find(q2))
| true |
557bf6b8bd015627f607db208d919275ed3d275f | luke-mao/Data-Structures-and-Algorithms-in-Python | /chapter6/q13.py | 617 | 4.25 | 4 | """
a deque with sequence (1,2,3,4,5,6,7,8).
given a queue,
use only the deque and queue,
to shift the sequence to the order (1,2,3,5,4,6,7,8)
"""
from example_queue import ArrayQueue
from example_double_ended_queue import ArrayDoubleEndedQueue
D = ArrayDoubleEndedQueue()
for i in range(1, 8+1): D.add_last(i)
Q = ArrayQueue()
print("initially")
D.show()
Q.show()
print()
# shift the order
for _ in range(3): D.add_last(D.delete_first())
Q.enqueue(D.delete_first())
D.add_last((D.delete_first()))
D.add_last(Q.dequeue())
for _ in range(3): D.add_last(D.delete_first())
print("finally")
D.show()
Q.show() | true |
49e88e6fe9c032dd82cec7a297c9a1b45c51d311 | luke-mao/Data-Structures-and-Algorithms-in-Python | /chapter1/q1.py | 712 | 4.40625 | 4 | def is_multiple(n, m):
'''
if n = m * i, then return True, else return False
'''
if n == 0 and m == 0:
return True
elif m == 0:
return False
elif n % m == 0:
return True
else:
return False
if __name__ == '__main__':
print("{}: {} is a multiple of {}".format(is_multiple(4, 8), 4, 8))
print("{}: {} is a multiple of {}".format(is_multiple(8, 4), 8, 4))
print("{}: {} is a multiple of {}".format(is_multiple(0, 0), 0, 0))
print("{}: {} is a multiple of {}".format(is_multiple(0, 5), 0, 5))
print("{}: {} is a multiple of {}".format(is_multiple(5, 0), 5, 0))
print("{}: {} is a multiple of {}".format(is_multiple(-2, 2), -2, 2)) | false |
470b2df2a6bc64b4d49ede0eaf8e7e37e24df276 | luke-mao/Data-Structures-and-Algorithms-in-Python | /chapter6/q21.py | 1,326 | 4.375 | 4 | """
use a stack and queue to display all subsets of a set with n elements
"""
from example_stack import ArrayStack
from example_queue import ArrayQueue
def subset_no_recursion_use_array_queue(data):
"""
stack to store elements yet to generate subsets,
queue store the subsets generated so far.
method: quite similar to the recursion method,
so the queue dequeue everything and append the same, and the one with new element
"""
s = ArrayStack()
q = ArrayQueue()
for each in data: s.push([each])
while not s.is_empty():
new = s.pop()
q.enqueue(new)
while q.first() != new:
out = q.dequeue()
q.enqueue(out)
q.enqueue(out+new)
q.enqueue([]) # manually input the empty set
q.show() # or can combine and return as a long list
def subset_with_recursion(data):
if data == []:
return [[]]
else:
subsets_of_remaining = subset_with_recursion(data[:-1])
add_the_last_value = [each + [data[-1]] for each in subsets_of_remaining ]
return sorted(subsets_of_remaining + add_the_last_value)
if __name__ == '__main__':
# result = subset_with_recursion([1,2,3])
# for each in result: print(each)
subset_no_recursion_use_array_queue([1,2,3]) | true |
94ff02e3cac8ae2fcd69ad2f9dde568f470a4650 | luke-mao/Data-Structures-and-Algorithms-in-Python | /chapter7/q3.py | 814 | 4.125 | 4 | """
describe a recursive algorithm that count the number of nodes
in a singly linked list
method:
similar to the counting of the height of a tree,
quite simple and straightforward
"""
from example_singly_linked_list import SinglyLinkedList
def count(node):
"""give the head element, count the number"""
if node is None:
return 0
else:
return 1 + count(node._next)
if __name__ =='__main__':
list1 = SinglyLinkedList()
for i in range(5): list1.add(i)
print("length: ", count(list1._head))
list2 = SinglyLinkedList()
for i in range(20): list2.add(i)
print("length: ", count(list2._head))
list3 = SinglyLinkedList()
list3.add(1)
print("length: ", count(list3._head))
list4 = SinglyLinkedList()
print("length: ", count(list4._head))
| true |
0297636bbc9549fdf551e3bf55740326e9c05f34 | je-clark/decoratorsexamples | /advanced_decorated_function.py | 1,445 | 4.21875 | 4 | # This is an advanced example for decorators. Not only can we access information
# about the function and control its execution, but the decorator can take arguments
# so that it can be reused for multiple functions
from random import choice, randint
def add_description(operation = ""): # Contains details about the decorator parameters
def wrap(func): # Contains the original function
def inner_wrap(a,b): # Contains the original function's arguments
influence = choice(["angel on shoulder","devil on shoulder"])
if influence == "devil on shoulder":
modifier = randint(1,10)
else:
modifier = 0
# We can call the original function, with arguments
# (even customized ones), in here
print(f"The {operation} of {a} and {b} is {func(a,b+modifier)}")
return # Since we call the function inside the inner wrap
# a blank return statement is fine
return inner_wrap # wrap() returns inner_wrap()
return wrap # The decorator returns the wrap
@add_description(operation = "sum")
def add(a, b):
return(a+b)
@add_description(operation="difference")
def subtract(a,b):
return(a-b)
add(1,5)
subtract(6,3) | true |
ebea4a362f1872bd045bd5cd66f63c84586d31d8 | ymsonnazelle/MITx-6.00.1x | /odd.py | 440 | 4.28125 | 4 | '''
Week-2:Exercise-Odd
Write a Python function, odd, that takes in one number and returns True when the number is odd and False otherwise.
You should use the % (mod) operator, not if.
This function takes in one number and returns a boolean.
'''
#code
def odd(x):
'''
x: int
returns: True if x is odd, False otherwise
'''
# Your code here
while x % 2 != 0:
return True
break
return False
| true |
3949de29e6514620371c592cb0a851ca575f7c0f | serviru/algo | /Lesson_1/4.py | 1,006 | 4.21875 | 4 | """
4. Написать программу, которая генерирует в указанных пользователем границах
● случайное целое число,
● случайное вещественное число,
● случайный символ.
Для каждого из трех случаев пользователь задает свои границы диапазона.
Например, если надо получить случайный символ от 'a' до 'f',
то вводятся эти символы. Программа должна вывести на экран любой
символ алфавита от 'a' до 'f' включительно.
"""
from random import random
m1 = int(input())
m2 = int(input())
n = int(random() * (m2-m1+1)) + m1
print(n)
m1 = float(input())
m2 = float(input())
n = random() * (m2-m1) + m1
print(round(n,3))
m1 = ord(input())
m2 = ord(input())
n = int(random() * (m2-m1+1)) + m1
print(chr(n))
| false |
d6ab975cd8404bb702b4bc7bd4a931914dea1ab9 | Constantino/Exercises | /Python/fill_it_nice.py | 796 | 4.15625 | 4 | from sys import argv
def quick_sort(List):
if len(List) > 1:
pivot = len(List)/2
numbers = List[:pivot]+List[pivot+1:]
left = [e for e in numbers if e < List[pivot]]
right =[e for e in numbers if e >= List[pivot]]
return quick_sort(left)+[List[pivot]]+quick_sort(right)
return List
def get_numbers():
List = []
while True:
try:
number = raw_input("Type a number or 'q' to quit: ")
if number == "q":
break
number = float(number)
List.append(number)
except ValueError:
print "That's not a number!"
return List
List = get_numbers()
print "\nNumbers_list: ", List
sorted_list = quick_sort(List)
print "sorted_list: ", sorted_list
print "\nHighest number: ", sorted_list[-1]
print "lowest number: ", sorted_list[0]
| true |
9d43b7e00a1fdd19d9d3f6e17517347dbcee3b67 | leihuagh/python-tutorials | /books/AutomateTheBoringStuffWithPython/Chapter13/PracticeProjects/P4_PDFbreaker.py | 1,497 | 4.21875 | 4 | # Say you have an encrypted PDF that you have forgotten the password to, but you
# remember it was a single English word. Trying to guess your forgotten password
# is quite a boring task. Instead you can write a program that will decrypt the
# PDF by trying every possible English word until it finds one that works.
#
# Create a list of word strings by reading dictionary.txt. Then loop over each word in
# this list, passing it to the decrypt() method. If this method returns the integer
# 0, the password was wrong and your program should continue to the next password.
# If decrypt() returns 1, then your program should break out of the loop and print
# the hacked password. You should try both the uppercase and lowercase form of
# each word.
#
# Note:
# - Dictionary text file can be downloaded from http://nostarch.com/automatestuff/
import PyPDF4
FILE = "../allminutes_encrypted.pdf"
# Get dictionary
with open("dictionary.txt") as file:
words = file.read().splitlines()
# Load encrypted PDF
pdfReader = PyPDF4.PdfFileReader(open(FILE, "rb"))
if not pdfReader.isEncrypted:
print("FileError: PDF is not encrypted")
raise RuntimeError
# Try each word in dictionary (upper and lower case)
for word in words:
# Print password, if found
if pdfReader.decrypt(word) or pdfReader.decrypt(word.lower()):
print("The password is either %s or %s" % (word, word.lower()))
break
else:
continue
if word == words[-1]:
print("Failed to break PDF.")
| true |
01146104e5b2d6fb2000615363f9103a9ba7c385 | fedeweit-2/Programming | /problemset_08_weithaler/priority_queue.py | 1,552 | 4.25 | 4 | # Implementation of the unbounded Priority Queue ADT using a Python list # with new items appended to the end.
class PriorityQueue:
# Create an empty unbounded priority queue.
def __init__(self):
self._qList = list()
# Returns True if the queue is empty.
def is_empty(self):
return len(self) == 0
# Returns the number of items in the queue.
def __len__(self):
return len(self._qList)
# Adds the given item to the queue.
def enqueue(self, item, priority):
# Create a new instance of the storage class and append it to the list.
entry = _PriorityQEntry(item, priority)
self._qList.append(entry)
# Removes and returns the first item in the queue.
def dequeue(self):
assert not self.is_empty(), "Cannot dequeue from an empty queue."
# Find the entry with the highest priority.
highest = self._qList[0].priority
highest_index = 0
for i in range(len(self)):
# See if the ith entry contains a higher priority (smaller integer).
if self._qList[i].priority < highest:
highest = self._qList[i].priority
highest_index = i
# Remove the entry with the highest priority and return the item.
entry = self._qList.pop(highest_index)
return entry.item
# Private storage class for associating queue items with their priority.
class _PriorityQEntry(object):
def __init__(self, item, priority):
self.item = item
self.priority = priority
| true |
ef566a5ea5da4dc682bd2948db1b60cc5ca4d5b1 | bouzidnm/python_intro | /notes_27Feb2019.py | 2,620 | 4.75 | 5 | ## Notes for 27 Feb 2019
## For loops; .append(); .keys(); .values()
## Used to iterate over a sequence of values; to simplify redundant code
## Print out each item of a list individually
my_list = ['A', 'B', 'C', 'D', 'E']
## Two types of for loops
### Easy way: prints item
for i in my_list: # 'i is a variable that changes after every loop
print(i)
# line after a colon (:) is indented
## range() function allows you to loop a specified number of times
for i in range(5): # loop 5 times; remember it starts at 0!
print(i)
### Other way: prints index of list
for i in range(5):
print(my_list[i]) # now it prints elements of the list instead of 0:4
## Exercises
# Practice 1
names = ['Leo', 'Jen', 'Matt', 'Chris', 'Jess', 'Megan', 'Tom', 'Will']
# Print list by item
for i in names:
print(i)
# Print list by index
for i in range(len(names)): # could also be range(8)
print(names[i])
# Practice 2
names = ['Leo', 'Jen', 'Matt', 'Chris', 'Jess', 'Megan', 'Tom', 'Will']
ages = [43, 28, 48, 37, 21, 32, 22, 50]
# Print name and corresponding age with index
for i in range(8):
print(names[i], ages[i])
# Use a for loop to print out a string for each person in the list
for i in range(8):
print('{} is {} years old.'.format(names[i], ages[i]))
## .append() function; adds an item to the end of an existing list
## Format: list_name.append('thing to append')
names = [] # create an empty list
names.append('Sam')
print(names) # now there's one
names.append('Pat')
print(names) # now there's two
names.append('Julie')
print(names) # now there's three
## Back to Dictionaries
grades = {'A':9, 'B':12, 'C':11, 'D':5, 'F':2}
.keys() # returns keys of dictionary
.values() # returns values of dictionary
## Format: dict_name.keys(); dict_name.values()
# Create list of keys of dictionary
list = [] # empty list
for i in grades.keys(): # empty parentheses; loop by item
list.append(i)
print(list) # notice indenting. Un-indenting stops the for loop
## Filling dictionaries the short way
## Recall: long way is dict['key1'] = 'value1'; dict['key2'] = 'value2'; etc.
# Initialize dictionary
grades = {}
for i in range(5):
grades[keys[i]] = values[i]
print(grades)
## This only works if the lists have the same length
# Practice 3
keys = ['brand', 'model', 'year']
values = [['BMW', 'Nissan', 'Toyota'], ['M3', 'Skyline', 'Supra'], [2005, 1999, 2002]]
# Create empty dictionary called legend_cars
legend_cars = {}
# Use a for loop to fill dictionary with list of keys and values
for i in range(len(keys)):
legend_cars[keys[i]] = values[i]
# print the dictionary
print(legend_cars) | true |
410bd8f7ae4f92900d83942c680df24852cbe029 | kevinlong206/learning-python | /70sum.example.py | 360 | 4.1875 | 4 |
# there is a list comprehension in this one
# but it the entire list needs to be created
# before sum can run on the list
s1 = sum([n**2 for n in range(10**6)])
# these are the same, s3 just has redunant parenthesis
# this is a generator expression
s2 = sum((n**2 for n in range (10**6)))
s3 = sum(n**2 for n in range(10**6))
print(s1)
print(s2)
print(s3)
| true |
e1be6d365efe0a2972c48dff9551d9d53fb53778 | drafski89/useful-python | /file_handling/file_handling.py | 1,577 | 4.4375 | 4 | # Purpose: Demonstrate basic file handling with Python 2
# Declare the input and output file names (same directory)
# Note: Possible to declare the full path if reading from another directory
INPUT_FILE_NAME = "input.txt"
OUTPUT_FILE_NAME = "output.txt"
# Open the input file as "r" reading
with open(INPUT_FILE_NAME, "r") as input_file:
# Print successful opening
print "\nWe have opened the input file: " + INPUT_FILE_NAME
# Open the output file as "w" writing
# Also possible to open file as "a" append
with open(OUTPUT_FILE_NAME, "w") as output_file:
# Print successful opening
print "We have opened the output file: " + OUTPUT_FILE_NAME + "\n"
# For each line in the input file
# The count is the current line count
for count, line in enumerate(input_file):
# Print the line count and the line read from the input file
print "The line count is: " + str(count)
print "The raw line read in is: " + line
# The line read in will have a trailing new line character
# To remove, perform a strip
line = line.strip()
# Print the stripped line
print "The strip line read in is: " + line
# Write the line read to the output file
output_file.write(line)
# Print successful writing to the output file
print "Wrote the line to the output file. \n"
# No need to exit the files
# Python will handle closing the files correctly
print "Program complete!\n" | true |
68021c77c0ee0ad4339ea6f035207dae6ea9a485 | drafski89/useful-python | /loops/for.py | 305 | 4.1875 | 4 | # Basic example of implementing a for-loop
# Create a variable called count to hold the current count
count = 1
print x
# For loop
# for [variable] in range (start amount, stop amount, increment amount)
for count in range(1, 12, 1):
# Add 1 to count and print the result
count = count + 1
print count | true |
5f4a1d080a21abda6e4845432c751bb691c6378b | GitOrangeZhang/pythonDemo2 | /src/one/test7.py | 270 | 4.1875 | 4 | str='abcdefghij'
#查看字符串长度
# print(len(str))
#
# print(str[:])
#
# print(str.startswith('b'))
# print(str.endswith('j'))
#给定一个字符串str1,返回使用空格或者\t分割后的倒数第二个字符
str1 = 'my name is zhang cheng'
print(str1.split()) | false |
e1d807afe73812d5149402af15cac11853f59233 | o9nc/CSE | /Jazmeene Hangman.py | 1,127 | 4.15625 | 4 | import random
# import string
"""
A general guide for Hangman
1. Make a word bank - 10 items
2. Pick a random item from list
3. Add a guess to the list of letters guessed
4. Reveal letters already guessed
5. Create the win condition
"""
movie_list = ["Love in basketball", "Vampire diaries", "Insidious", "Split", "The originals", "Get rich or die trying",
"Jumanji 2", "chucky", "Anabelle", "The perfect game"]
movie = movie_list[random.randint(0, len(movie_list) - 1)]
print(movie)
letters_guessed = []
guess_left = 10
current_guess = ""
while guess_left > 0 and current_guess != "quit":
# Prints out the output
output = []
for letter in movie:
if letter in letters_guessed:
output.append(letter)
else:
output.append("*")
print("".join(list(output)))
# Takes a guess and adds it to letters guessed
current_guess = input("type a letter:")
letters_guessed.append(current_guess)
print(letters_guessed)
# Handles incorrect guesses
if current_guess not in movie:
guess_left -= 1
print("%d guess left" % guess_left)
| true |
d854cfb16d1bdb14f8d9e70f84718d40557b371b | SuperLavrik/Class_work | /work_6.py | 558 | 4.125 | 4 | def is_year(year):
return year %4 ==0 and year %100 != 0 or year %400 == 0
# if year %4 ==0 and year %100 != 0 or year %400 == 0:
# return True
#
# else :
# return False
# x = 4
# y = 101
# if 3 <= x <= 100 and x !=4 or y >= 100 and y <= 200 :
# print ("inside")
# else :
# print("outside")
year = 2024
print (year)
if is_year(year):
print ("leap year! ")
else :
print("regular year! ")
# year = 2000
# if year %4 ==0 and year %100 != 0 or year %400 == 0:
# print ("leap year! ")
# else :
# print("regular year! ")
| false |
a99987bd4112710b8d4e4e10c9de1e9c7e3710ba | humengdoudou/a_func_a_day_in_python | /test_random_20180329.py | 1,275 | 4.40625 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
#
# This is the python code for testing random function in python lib.
#
# Author: hudoudou love learning
# Time: 2018-03-29
import random
# random lib test
print(random.random()) # randomly generate a float in [0,1)
print(random.uniform(1, 5)) # randomly generate a float in [min, max)
print(random.randint(1, 5)) # randomly generate an int in [min, max]
print(random.randrange(10)) # randomly generate an int in [0, max)
print(random.randrange(1, 10)) # randomly generate an int in [min, max)
print(random.randrange(1, 10, 2)) # randomly generate an int in [min, max), step size: N, so int is min + K * N
print(random.choice("abc")) # randomly select a char from string
print(random.choice([1, 2, 3])) # randomly select an element from list
print(random.sample("abcdefg", 3)) # random select N chars from string, the N chars to be a new list
print(random.sample([1, 2, 3, 4, 5, 6], 3)) # random select N elements from list, the N elements to be a new list
list_number = [1, 2, 3, 4, 5]
random.shuffle(list_number)
print("shuffle(list):", list_number) # random shuffle a list
| true |
8dbdc538a049d3e4552a1ddc9e328975bd4abbe6 | cvhs-cs-2017/practice-exam-lucasrosengarten | /Range.Function.py | 291 | 4.34375 | 4 | """Use the range function to print the numbers from 1-20"""
x = (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20)
print (x)
"""Repeat the exercise above counting by 2's"""
a = (2,4,6,8,10,12,14,16,18,20)
print (a)
"""Print all the multiples of 5 between 10 and 200 in DECENDING order"""
| true |
c6c6d77afa2d449f6763a5bb23130d419a37a84a | Olugbenga-GT/Python-Chapter-three | /Cubes _and _Squares.py | 597 | 4.5625 | 5 | # 3.7 (Table of Squares and Cubes) In Exercise 2.8, you wrote a script to calculate the
# squares and cubes of the numbers from 0 through 5, then printed the resulting values in
# table format. Reimplement your script using a for loop and the f-string capabilities you
# learned in this chapter to produce the following table with the numbers right aligned in
# each column.
# Exercises 113
# number square cube
# 0 0 0
# 1 1 1
# 2 4 8
# 3 9 27
# 4 16 64
# 5 25 125
print(f'number', f'square', f'cube' )
for number in range(1, 6):
print(f'{number:>4}', f'{number**2:>6}', f'{number**3:>6}')
| true |
399a79413492afd93a739cab16fe2e8a67d08d20 | Tusharsharma118/python-learning | /basics/enhanced_calculator_with menu.py | 873 | 4.15625 | 4 | number1 = input('Enter First Number:')
number2 = input('Enter Second Number:')
def menu():
print('1 - Add \n2 - Subtract \n3 - Multiply \n4 - Divide \n5 - Exit')
def calculator(choice, number1, number2):
num1 = int(number1)
num2 = int(number2)
if choice == 1:
print (num1 + num2)
elif choice == 2:
print (num1 - num2)
elif choice == 3:
print (num1 * num2)
elif choice == 4:
print (num1 / num2)
elif choice == 5:
print('Exiting...')
else:
print('Wrong Choice!')
menu()
choice = int(input('Enter Your Choice:'))
calculator(choice,number1, number2)
while choice != 5 :
number1 = input('Enter First Number:')
number2 = input('Enter Second Number:')
menu()
choice = int(input('Enter Your Choice:'))
calculator(choice, number1, number2)
| false |
877fcdfb0769400495a89e19e70e4d3404fca59e | deepikavashishtha/pythonLearning | /gen.py | 525 | 4.3125 | 4 | """Modules for demonstrating generator execution"""
def take(count, iterable):
"""
This method takes items from iterable
:param count:
:param iterable:
:return: generator
Yields: At most 'count' items from 'iterable'
"""
counter = 0
for item in iterable:
if counter == count:
return
counter += 1
yield item
def run_take():
items = [2, 4, 6, 8, 10]
for item in take(3, items):
print(item)
if __name__=='__main__':
run_take()
| true |
bd09846b2d246ce7e11ebf73af0254c249690554 | utkarshsaraf19/python-object-oriented-programming | /08_docstrings/eigth_class.py | 1,263 | 4.375 | 4 | import math
class Point:
"""Represents the point in two dimensional coordinate"""
def __new__(cls):
"""
Constructor class which is called before object is created
"""
print("Creating instance")
return super(Point, cls).__new__(cls)
# default values initializer
def __init__(self, x=0, y=0):
"""
Initialize the values of coordinate to (zero,zero) if not explicitly specified
:param x: x coordinate
:param y: y coordinate
"""
self.move(x, y)
def move(self, x, y):
"""
Move the point to specified location
:param x: point location on x axis
:param y: point location on y axis
:return: None
"""
self.x = x
self.y = y
def reset(self):
"""
rest the point ot (0,0)
:return:
"""
self.move(0, 0)
def calculate_difference(self, another_point):
"""
calculate the distance between two point using pythagorean theorem
:param another_point: another instance of point class
:return: distance between two points
"""
return math.sqrt(((self.x - another_point.x) ** 2) + ((self.y - another_point.y) ** 2))
| true |
3b227b93f6e65cd6c6ff748afec1474172627bb8 | jp-tran/dsa | /problems/subsets/evaluate_expression.py | 1,291 | 4.4375 | 4 | """
Given an expression containing digits and operations (+, -, *),
find all possible ways in which the expression can be evaluated
by grouping the numbers and operators using parentheses.
Soln: If we know all of the ways to evaluate the left-hand
side (LHS) of an expression and all of the ways to evaluate
the right-hand side (RHS), we can determine all of the ways
to evaluate the entire expression.
Time complexity: O(N * 2^N)
Space complexity: O(2^N)
"""
def diff_ways_to_evaluate_expression(input):
# base case
if input.isdigit():
return [int(input)]
result = []
for i in range(len(input)):
char = input[i]
if char.isdigit():
continue
LHS = diff_ways_to_evaluate_expression(input[:i])
RHS = diff_ways_to_evaluate_expression(input[i+1:])
for left_part in LHS:
for right_part in RHS:
if char == '+':
result.append(left_part + right_part)
elif char == '-':
result.append(left_part - right_part)
else:
result.append(left_part * right_part)
return result
def main():
print("Expression evaluations: " +
str(diff_ways_to_evaluate_expression("1+2*3")))
print("Expression evaluations: " +
str(diff_ways_to_evaluate_expression("2*3-4-5")))
main()
| true |
113e00314debeb37a36fcf3e82b203f5d5a3dd34 | yaswanth12365/coding-problems | /Ways to sort list of dictionaries by values in Python.py | 893 | 4.5625 | 5 | # Python code demonstrate the working of sorted()
# and itemgetter
# importing "operator" for implementing itemgetter
from operator import itemgetter
# Initializing list of dictionaries
lis = [{ "name" : "Nandini", "age" : 20},
{ "name" : "Manjeet", "age" : 20 },
{ "name" : "Nikhil" , "age" : 19 }]
# using sorted and itemgetter to print list sorted by age
print "The list printed sorting by age: "
print sorted(lis, key=itemgetter('age'))
print ("\r")
# using sorted and itemgetter to print list sorted by both age and name
# notice that "Manjeet" now comes before "Nandini"
print "The list printed sorting by age and name: "
print sorted(lis, key=itemgetter('age', 'name'))
print ("\r")
# using sorted and itemgetter to print list sorted by age in descending order
print "The list printed sorting by age in descending order: "
print sorted(lis, key=itemgetter('age'),reverse = True)
| true |
d658869baf27a2d2dc76621f91fbece0700f136c | yaswanth12365/coding-problems | /Python program to interchange first and last elements in a list.py | 342 | 4.25 | 4 | # Python3 program to swap first
# and last element of a list
# Swap function
def swapList(list):
# Storing the first and last element
# as a pair in a tuple variable get
get = list[-1], list[0]
# unpacking those elements
list[0], list[-1] = get
return list
# Driver code
newList = [12, 35, 9, 56, 24]
print(swapList(newList))
| true |
886af12ca48a2c80ab930372a4c03897c6cc5b70 | wangjiliang1983/test | /crashcourse/ex08_08_albumwhile.py | 448 | 4.15625 | 4 | def make_album(singer, album):
album_dict = {'singer': singer, 'album': album}
return album_dict
while True:
print("\nPlease give me the singer name and album name:")
print("(Enter 'q' to quit)")
singer = input("Please enter the singer name: ")
if singer == 'q':
break
album = input("Please enter album name: ")
if album == 'q':
break
album_dict = make_album(singer,album)
print(album_dict) | true |
f8bfeceaa6e54f795b199327b66439031eca81f5 | rayallen20/Problem-Solving-with-Algorithms-and-Data-Structures-Using-Python | /Chapter1. Introduction/code/input.py | 268 | 4.1875 | 4 | aName = input('Please enter your name ')
print("Your name in all capitals is ", aName.upper(), "and has length ", len(aName))
sRadius = input("Please enter the radius of the circle ")
radius = float(sRadius)
diameter = 2 * radius
print("diameter is %E\n" % diameter)
| true |
ae4cf9a310cb91aa9e3f5c3f8f59178816f898c2 | lukapejic23/pythonintro | /big_fibonacci.py | 276 | 4.34375 | 4 | def big_fibonacci():
previous_num, result = 0, 1
desiredlength = int(input("enter the number of digits : "))
while len(str(result)) < desiredlength:
previous_num, result = result, previous_num + result
return result
print(big_fibonacci()) | true |
009c7bb85317759c5b43e03e579f3186251f5d1e | Platforuma/Beginner-s_Python_Codes | /9_Loops/32_For_Loop--Counting-char-in-string.py | 466 | 4.28125 | 4 | '''
Write a Python program that accepts a string and calculate the number of
digits and letters.
Sample Data : Python 3.2
Expected Output :
Letters 6
Digits 2
'''
string = input("Enter a string: ")
digit = length = 0
for char in string:
if char.isdigit():
digit = digit + 1
elif char.isalpha():
length = length + 1
else:
pass
print("Letters in String: ", length)
print("Digits in String: ", digit)
| true |
d2f76c0be047088b29d7ea7097a8b4e0ea4c8ce4 | Platforuma/Beginner-s_Python_Codes | /8_Conditional_Statements/18_if_Dictionary--Month-Days.py | 2,510 | 4.34375 | 4 | '''
Write a Python program to convert month name to a number of days.
Expected Output:
List of months: January, February, March, April, May, June, July, August
, September, October, November, December
Input the name of Month: February
No. of days: 28/29 days
'''
month = input('Enter a month: ')
print('----Using multiple if statemetns----')
if month=='January' or month=='january':
print('No of Days: 31 Days')
elif month=='February' or month=='february':
print('No of Days: 28/29 Days')
elif month=='March' or month=='march':
print('No of Days: 31 Days')
elif month=='April' or month=='april':
print('No of Days: 30 Days')
elif month=='May' or month=='may':
print('No of Days: 31 Days')
elif month=='June' or month=='june':
print('No of Days: 30 Days')
elif month=='July' or month=='july':
print('No of Days: 31 Days')
elif month=='August' or month=='august':
print('No of Days: 31 Days')
elif month=='September' or month=='september':
print('No of Days: 30 Days')
elif month=='October' or month=='october':
print('No of Days: 31 Days')
elif month=='November' or month=='november':
print('No of Days: 30 Days')
elif month=='December' or month=='december':
print('No of Days: 31 Days')
else:
print('Enter the month from "January, February, March, April, May, June, July, August, September, October, November, December"')
print(' ' )
#using Dictionary
print('----Using Dictionary----')
month_day = {'January' : '31 Days', 'january' : '31 Days',
'February' : '28/29 Days', 'february' : '28/29 Days',
'March' : '31 Days', 'march' : '31 Days',
'April' : '30 Days', 'april' : '30 Days',
'May' : '31 Days', 'may' : '31 Days',
'June' : '30 Days', 'june' : '30 Days',
'July' : '31 Days', 'july' : '31 Days',
'August' : '31 Days', 'august' : '31 Days',
'September' : '30 Days', 'september' : '30 Days',
'October' : '31 Days', 'october' : '31 Days',
'November' : '30 Days', 'november' : '30 Days',
'December' : '31 Days', 'december' : '31 Days'}
if month in month_day.keys():
print('No. of days: ', month_day[month])
else:
print('Enter the month from "January, February, March, April, May, June, July, August, September, October, November, December"')
| true |
c10a2dcde5720729a9f65896926ccc379a198563 | Platforuma/Beginner-s_Python_Codes | /6_Dictionary/1_Dictionary--adding-3-dicts.py | 756 | 4.21875 | 4 | '''
Write a Python script to concatenate following dictionaries to create a new one.
Sample Dictionary :
dic1={1:10, 2:20}
dic2={3:30, 4:40}
dic3={5:50,6:60}
Expected Result :
{1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
'''
dic1={1:10, 2:20}
print('dic1: ', dic1)
dic2={3:30, 4:40}
print('dic2: ', dic2)
dic3={5:50,6:60}
print('dic3: ', dic3)
new_dic = {}
print(' ')
#updating individually
print('----Updating Individually----')
new_dic.update(dic1)
new_dic.update(dic2)
new_dic.update(dic3)
print('New_Dic: ', new_dic)
print(' ')
#using for loop
print('----Updating using for loop----')
new_dic2 = {}
for d in (dic1,dic2,dic3):
new_dic2.update(d)
print('New_Dic: ',new_dic2)
| false |
1cb8ef9470f34c0afaa29c2f2b63b4a76b1c5416 | marcelosdm/python-alura | /app.py | 1,870 | 4.15625 | 4 | # -*- coding: UTF-8 -*-
def cadastrar(nomes):
print 'Digite um nome'
nome = raw_input()
nomes.append(nome)
def listar(nomes):
print 'Listando nomes'
for nome in nomes:
print nome
def remover(nomes):
print 'Qual nome você deseja remover?'
nome = raw_input()
nomes.remove(nome)
def alterar(nomes):
print ('Qual nome você deseja alterar?')
nome_alterar = raw_input()
if(nome_alterar in nomes):
posicao = nomes.index(nome_alterar)
print ('Digite o novo nome:')
nome_novo = raw_input()
nomes[posicao] = nome_novo
def procurar(nomes):
print ('Digite o nome a procurar:')
nome_procurar = raw_input()
if(nome_procurar in nomes):
print ('Nome %s foi encontrado') % (nome_procurar)
else:
print ('O nome %s não foi cadastrado') % (nome_procurar)
def procurar_rgx(nomes):
print('Digite a expressão regular')
regex = raw_input()
nomes_concat = ' '.join(nomes)
resultado = re.findall(regex, nomes_concat)
print(resultado)
def menu():
nomes = []
escolha = ''
while(escolha != '0'):
print ''
print '--------------------'
print 'Digite 1 para cadastrar'
print 'Digite 2 para listar'
print 'Digite 3 para remover'
print 'Digite 4 para alterar'
print 'Digite 5 para procurar'
print 'Digite 6 para regex'
print 'Digite 0 para encerrar'
print '--------------------'
escolha = raw_input()
if(escolha == '1'):
cadastrar(nomes)
if(escolha == '2'):
listar(nomes)
if(escolha == '3'):
remover(nomes)
if(escolha == '4'):
alterar(nomes)
if(escolha == '5'):
procurar(nomes)
if(escolha == '6'):
procurar_rgx(nomes)
menu() | false |
38c52b307d8135e8ee48d71215fe91edbda459bf | TomKite57/advent_of_code_2020 | /python/headers/day2.py | 1,701 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
Day 2 of Advent of Code 2020
This script will read a file formatted as such:
int1-int2 char: string
and will process the code according to two criteria
1) int1 <= string.count(char) <= int2
2) (string[int1-1], string[int2-1]).count(char) == 1
Tom Kite - 02/12/2020
"""
from aoc_tools.advent_timer import Advent_Timer
def process_line_input(line):
line = line.strip()
nums, letter, password = line.split(' ')
num_a, num_b = nums.split('-')
letter = letter.strip(':')
return [int(num_a), int(num_b), letter, password]
def readfile(filename):
with open(filename) as file:
lines = file.readlines()
data = [process_line_input(x) for x in lines]
return data
def valid_password_part1(code):
num1, num2, letter, password = code
count = password.count(letter)
return num1 <= count <= num2
def valid_password_part2(code):
num1, num2, letter, password = code
letters = password[num1-1] + password[num2-1]
return letters.count(letter) == 1
def part1(filename):
data = readfile(filename)
valid = [valid_password_part1(x) for x in data]
print("There are {} valid passwords, and {} invalid."
.format(valid.count(1), valid.count(0)))
def part2(filename):
data = readfile(filename)
valid = [valid_password_part2(x) for x in data]
print("There are {} valid passwords, and {} invalid."
.format(valid.count(1), valid.count(0)))
if __name__ == "__main__":
timer = Advent_Timer()
print("Part 1:")
part1("../../data/day2.dat")
timer.checkpoint_hit()
print("\nPart 2:")
part2("../../data/day2.dat")
timer.checkpoint_hit()
timer.end_hit()
| true |
f025a098e554f22e773293e2af3086f3c4c60233 | pallegithub/Python | /Assignment5_case3.py | 220 | 4.1875 | 4 | def multiplication(num):
for i in range(1,11):
print(num,"X",i,"=",num*i)
number = int(input("Enter any number==>"))
print("Multiplication Table for",number)
print("")
multiplication(number)
print("") | false |
ea668e1782babe68ed94acd935f12034030bb7c9 | pallegithub/Python | /Assignment5_case5.py | 471 | 4.28125 | 4 | def max(num1,num2,num3):
if num1>=num2 and num1>=num3:
print("Maximum of",num1,",",num2,",",num3,"is",num1)
elif num2>=num1 and num2>=num3:
print("Maximum of",num1,",",num2,",",num3,"is",num2)
else:
print("Maximum of",num1,",",num2,",",num3,"is",num3)
number1 = int(input("Enter Number1==>"))
number2 = int(input("Enter Number2==>"))
number3 = int(input("Enter Number3==>"))
print("")
max(number1,number2,number3) | false |
d6bcd3d1109cc2db021ae1e6850cfad606f11e05 | pallegithub/Python | /Assignment5_case8.py | 251 | 4.15625 | 4 | def factorial(n):
if n == 0:
print("")
return 1
else:
recurse = factorial(n-1)
result = n * recurse
print(result)
return result
n=int(input("Enter the number=======>"))
factorial(n)
| true |
49dc5f99bdc0a52cebad58b4c102456ad0383451 | estoicodev/holbertonschool-higher_level_programming-1 | /0x0B-python-input_output/2-read_lines.py | 516 | 4.34375 | 4 | #!/usr/bin/python3
"""This module defines the read_lines function"""
def read_lines(filename="", nb_lines=0):
"""Reads n lines of a text file (UTF8) and prints it to stdout
Args:
filename (str): Filename
nb_lines (int): number of lines to read
"""
with open(filename, encoding='utf-8') as file:
if nb_lines <= 0:
for line in file:
print(line, end="")
else:
for line in range(nb_lines):
print(file.readline(), end="")
| true |
1bc0031510add098424fd3a602ed2c68445f64c6 | nicolasilvac/MCOC-NivelacionPython | /27082109/000619.py | 1,325 | 4.125 | 4 | import numpy as np
a = np.zeros(3) #crea una matriz de 1 fila y 3 columnas
print a
#[ 0. 0. 0.]
print type(a[0]) #entrega el tipo de elemento numero 0 del array a
#<type 'numpy.float64'>
z = np.zeros(10)
print z
#[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
z.shape = (10, 1) #cambia la forma del array
print z
#[[ 0.]
# [ 0.]
# [ 0.]
# [ 0.]
# [ 0.]
# [ 0.]
# [ 0.]
# [ 0.]
# [ 0.]
# [ 0.]]
x = np.linspace(2, 10, 5) #crea un arreglo del 2 al 10 dividido en 5 elementos
print x #sirve para usarlos como ejes
#[ 2. 4. 6. 8. 10.]
y = np.array([10, 20]) #crea una matriz con una fila con 10 20
print y
#[10 20]
b_list = [1,2,3,4,5,6,7]
b = np.array([b_list]) #crea la lista b_list como un arreglo
print b
#[[1 2 3 4 5 6 7]] matriz, no lista
c_list = [[1,2,3,4,5,6,7],[11,22,33,44,55,66,77]]
c = np.array([c_list])
print c
#[[[ 1 2 3 4 5 6 7]
# [11 22 33 44 55 66 77]]] crea una matriz de 2 filas y 7 columnas
np.random.seed(0)
x1 = np.random.randint(10, size = 6) #crea un arreglo de 6 elementos con numeros aleatorios de 0 a 10
print x1
#[5 0 3 3 7 9]
print x1[1]
# 0
print x1[0:2] #retorna desde el elemento 0 al elemento 2-1
#[5 0]
print x1[0:3] #retorna desde el elemento 0 al elemento 3-1
#[5 0 3]
print x1[-1]
#9 retorna el ultimo elemento
| false |
6504a26d94a200a40a376726a549f90017fb5784 | nairaaoliveira/ProgWeb | /Exercicios_Python/Lista 3_Python/q17_Lista3_Ex_Python.py | 702 | 4.125 | 4 | '''
17. A partir de dois números fornecidos pelo usuário, escreva uma das seguintes mensagens:
Os dois são pares
Os dois são impares
O primeiro é par e o segundo é ímpar
O primeiro é ímpar e o segundo é par
'''
def RetornaMensagem(n1, n2):
if (n1 % 2 == 0) and (n2 % 2 == 0):
return "Os dois são pares"
elif (n1 % 2 != 0) and (n2 % 2 != 0):
return "Os dois são impares"
elif (n1 % 2 == 0) and (n2 % 2 != 0):
return "O primeiro é par e o segundo é ímpar"
elif (n1 % 2 != 0) and (n2 % 2 == 0):
return "O primeiro é ímpar e o segundo é par"
n1 = int(input("NUMERO 1: "))
n2 = int(input("NUMERO 2: "))
print(RetornaMensagem(n1, n2))
| false |
759e320069935d34f7434e46fe0f667162b53f26 | nairaaoliveira/ProgWeb | /Exercicios_Python/Lista 5_Python/q01_Lista 5_Ex_Python.py | 386 | 4.34375 | 4 | '''1. Faça uma função que recebe uma quantidade desejada de itens e retorna uma
lista carregada com essa quantidade. Faça outra função para exibir esses itens
esperados por espaço em branco.'''
def ListaQuant(quant):
L = [12, 9, 5]
i = 0
while i < 3:
print(len(L[quant]))
break
quant = int(input("Número : "))
ListaQuant(quant)
| false |
31bc6174231c4eddfc6d46e9ce624b9e89e5b9f9 | starryKey/LearnPython | /03-高级语法/17-协程/Example01.py | 1,889 | 4.15625 | 4 | # 案例01
list1 = [i for i in range(6)]
# list1是可迭代的,但不是迭代器
for index in list1:
print(index)
# range是个迭代器
for ind in range(3):
print(ind)
# isinstance案例
# 判断某个变量是否是一个实例
# 判断是否可迭代
from collections import Iterable
# 是可迭代的
list2 = [1,2,3,4,5]
print(isinstance(list2, Iterable))
# from collections import Iterator
from collections import Iterator
# 但不是迭代器
print(isinstance(list2, Iterator))
#iter 函数
s = "Hello world"
print(isinstance(s, Iterable))
print(isinstance(s, Iterator))
# 将可迭代的对象转为迭代器
s_iter = iter(s)
print(isinstance(s_iter, Iterable))
print(isinstance(s_iter, Iterator))
# 生成器
#直接使用生成器
list3 = [x * x for x in range(5)]# 放在中括号中是列表生成器
list4 = (x * x for x in range(5))# 放在小括号中就是生成器
print(type(list3))
print(type(list4))
# 函数案例
def Test1():
print("Step 1")
print("Step 2")
print("Step 3")
return None
Test1()
print("***" * 20)
# 生成器案例
# 在Test2函数中,yield用于返回
def Test2():
print("Step 1")
yield "ts"
print("Step 2")
yield "hh"
print("Step 3")
yield "ll"
g = Test2()
ger = next(g)
print(ger)
print(next(g))
print(next(g))
# for循环调用生成器
#普通写法
def fib(max):
n,a,b = 0, 0, 1
while n < max:
print(b)
a,b = b, a + b
n += 1
return "Done"
print(fib(5))
# 生成器写法
def fib(max):
n,a,b = 0, 0, 1
while n < max:
#print(b)
yield b
a,b = b, a + b
n += 1
return "Done"
# gg = fib(5)
#
# for i in range(6):
# rst = next(gg)
# print(rst)
"""
生成器的典型用法是在for循环中使用
比较常用的典型生成器是range
"""
ge = fib(10)
for i in ge:
print(i)
| false |
8732c89f39d09ae65d70f900e2ab925c346d600f | debajit13/100Days-of-Code | /Practice/Sum_of_first_&_last_digit.py | 324 | 4.125 | 4 | def sum(n): #calculate sum of the first and last digit
last_digit = n%10
first_digit = n
while(first_digit > 10):
first_digit = first_digit//10
s = first_digit + last_digit
return s
print("_____SUM OF FIRST AND LAST DIGIT_____")
number = int(input("Enter the number : "))
print(sum(number))
| true |
f9c6385b3b4024830c34dd69cd813a906e253bc3 | ramondfdez/57Challenges | /1_InputProcessingOutput/6_RetirementCalculator.py | 1,295 | 4.625 | 5 | # Your computer knows what the current yearis, which means
# you can incorporate that into your programs. You just have
# to figure out how your programming language can provide
# you with that information.
# Create a program that determines how many years you have
# left until retirement and the year you can retire. It should
# prompt for your current age and the age you want to retire
# and display the output as shown in the example that follows.
#
# Example Output
# What is your current age? 25
# At what age would you like to retire? 65
# You have 40 years left until you can retire.
# It's 2015, so you can retire in 2055.
#
# Constraints
# • Again, be sure to convert the input to numerical data
# before doing any math.
# • Don’t hard-code the current year into your program.
# Get it from the system time via your programming language.
from datetime import date
edad_actual = input("What is your current age? ")
edad_jubilacion = input("At what age would you like to retire? ")
anos_restantes = int(edad_jubilacion) - int(edad_actual)
ano_actual = date.today().year
ano_jubilacion = ano_actual + anos_restantes
print("You have " + str(anos_restantes) + " years until you can retire. ")
print("It's " + str(ano_actual)+ ", so you can retire in " + str(ano_jubilacion)) | true |
a5e7632f74441340f70c9be95fda130df0b0f128 | ramondfdez/57Challenges | /7_WorkingWithFiles/44_ProductSearch.py | 1,522 | 4.21875 | 4 | # Create a program that takes a product name as input and
# retrieves the current price and quantity forthat product. The
# product data is in a data file in the JSON format and looks
# like this:
# {
# "products" : [
# {"name": "Widget", "price": 25.00, "quantity": 5 },
# {"name": "Thing", "price": 15.00, "quantity": 5 },
# {"name": "Doodad", "price": 5.00, "quantity": 10 }
# ]
# }
# Print out the product name, price, and quantity if the product
# is found. If no product matches the search, state that no
# product was found and start over.
#
# Example Output
# What is the product name? iPad
# Sorry, that product was not found in our inventory.
# What is the product name? Widget
# Name: Widget
# Price: $25.00
# Quantity on hand: 5
#
# Constraints
# • The file is in the JSON format. Use a JSON parserto pull
# the values out of the file.
# • If no record is found, prompt again.
import json
path = "Files/44_json.json"
def buscarJson(producto, path):
encontrado = False
file = open(path, "r")
text = json.load(file)
for p in text["products"]:
if p["name"].upper() == producto.upper():
print("Name: " + p["name"])
print("Price: " + str(p["price"]))
print("Quantity on hand: " + str(p["quantity"]))
encontrado = True
return encontrado
while True:
producto = input("What is the product name? ")
if (buscarJson(producto, path)):
break
else:
print("Sorry, that product was not found in our inventory.") | true |
9acd2a0ca2f4a748b78c5e01956821ce6eb66b7f | ramondfdez/57Challenges | /1_InputProcessingOutput/3_PrintingQuotes.py | 880 | 4.40625 | 4 | # Quotation marks are often used to denote the start and end
# of a string. But sometimes we need to print out the quotation
# marks themselves by using escape characters.
# Create a program that prompts for a quote and an author.
# Display the quotation and author as shown in the example
# output.
#
# Example Output
# What is the quote? These aren't the droids you're looking for.
# Who said it? Obi-Wan Kenobi
# Obi-Wan Kenobi says, "These aren't the droids
# you're looking for."
#
# Constraints
# • Use a single output statement to produce this output,
# using appropriate string-escaping techniques for quotes.
# • If your language supports string interpolation or string
# substitution, don’t use it for this exercise. Use string
# concatenation instead.
quote = input("What is the quote? ")
autor = input("Who said it? ")
print(autor + " says, " + "\" " + quote + "\" ") | true |
5bad112b200e163bc45bc8371d13b0f41b0f13e0 | ramondfdez/57Challenges | /7_WorkingWithFiles/46_WordFrequencyFinder.py | 1,255 | 4.3125 | 4 | # Knowing how often a word appears in a sentence or block
# of text is helpful for creating word clouds and other types
# of word analysis. And it’s more useful when running it
# against lots of text.
# Create a program thatreads in a file and counts the frequency of words in the file. Then construct a histogram displaying
# the words and the frequency, and display the histogram to
# the screen.
#
# Example Output
# Given the text file words.txt with this content
# badger badger badger badger mushroom mushroom
# snake badger badger badger
# the program would produce the following output:
# badger: *******
# mushroom: **
# snake: *
#
# Constraint
# • Ensure that the most used word is at the top of the report
# and the least used words are at the bottom.
file = open("Files/words.txt")
def buscar (palabra, lista):
cont = 0
for i in lista:
if i == palabra:
return cont
else:
cont += 1
return -1
text = file.read()
lista = text.split(" ")
cont = 0
for palabra in lista:
encontrado = buscar(palabra, lista)
while( encontrado!= -1):
lista.pop(encontrado)
cont += 1
encontrado = buscar(palabra, lista)
print( palabra + ": " + str(cont))
cont = 0 | true |
f6e368eb5ae65130f7c0b7b26b64fbaf4d4f726c | ramondfdez/57Challenges | /2_Calculations/12_ComputingSimpleInterest.py | 1,364 | 4.3125 | 4 | # Computing simple interest is a great way to quickly figure
# out whether an investment has value. It’s also a good way
# to get comfortable with explicitly coding the order of operations in your programs.
# Create a program that computes simple interest. Prompt for
# the principal amount, the rate as a percentage, and the time,
# and display the amount accrued (principal + interest).
# The formula for simple interest is
# A = P(1 + rt), where P is
# the principal amount, r is the annual rate of interest, t is the
# number of years the amount is invested, and A is the amount
# at the end of the investment.
#
# Example Output
# Enter the principal: 1500
# Enter the rate of interest: 4.3
# Enter the number of years: 4
# After 4 years at 4.3%, the investment will
# be worth $1758.
#
# Constraints
# • Prompt for the rate as a percentage (like 15, not .15).
# Divide the input by 100 in your program.
# • Ensure that fractions of a cent are rounded up to the
# next penny.
# • Ensure that the output is formatted as money
principal = input("Enter the principal: ")
interest = input("Enter the rate of interest: ")
years = input("Enter the number of years: ")
amount = int(principal)* (1 + float(interest)/100 * int(years))
print("After " + str(years) + " years at " + str(interest) + "%, the investment will be worth $" + str(round(amount,2))) | true |
1ea4a6f2876cf5613140319832f031efa1ec3870 | ramondfdez/57Challenges | /6_DataStructures/38_FilteringValues.py | 1,189 | 4.40625 | 4 | # Sometimes input you collect will need to be filtered down.
# Data structures and loops can make this process easier.
# Create a program that prompts for a list of numbers, separated by spaces. Have the program print out a new list containing only the even numbers.
#
# Example Output
# Enter a list of numbers, separated by spaces: 1 2 3 4 5 6 7 8
# The even numbers are 2 4 6 8.
#
# Constraints
# • Convert the input to an array. Many languages can
# easily convert strings to arrays with a built-in function
# that splits apart a string based on a specified delimiter.
# • Write your own algorithm—don’trely on the language’s
# built-in filter or similar enumeration feature.
# • Use a function called filterEvenNumbers to encapsulate the
# logic for this. The function takes in the old array and
# returns the new array.
def filterEvenNumbers(lista):
pares = []
for i in lista:
if (int(i) % 2) == 0:
pares.append(i)
return pares
entrada = input("Enter a list of numbers, separated by spaces: ")
numeros = list(entrada.split(" "))
lista = filterEvenNumbers(numeros)
salida = ' '.join(lista)
print("The even numbers are " + salida)
| true |
c41227cc0a11d76294c67a8362ba93b1d7562c42 | mohanraoroutu/PythonTraining | /Regex.py | 2,110 | 4.25 | 4 | # Example of w+ and ^ Expression
import re
xx = "mohan1678,education is fun"
r1 = re.findall(r"^\w+",xx)
print(r1)
# Example of \s expression in re.split function
import re
xx = "guru99,education is fun"
r1 = re.findall(r"^\w+", xx)
print((re.split(r'\s','we are splitting the words')))
print((re.split(r's','split the words')))
# Using regular expression methods
# re.match(), re.search(), re.findall()
import re
list = ["guru99 get", "guru99 give", "guru Selenium"]
for element in list:
z = re.match("(g\w+)\W(g\w+)", element)
if z:
print((z.groups()))
patterns = ['software testing', 'guru99']
text = 'software testing is fun?'
for pattern in patterns:
print('Looking for "%s" in "%s" ->' % (pattern, text), end=' ')
if re.search(pattern, text):
print('found a match!')
else:
print('no match')
abc = 'guru99@google.com, careerguru99@hotmail.com, users@yahoomail.com'
emails = re.findall(r'[\w\.-]+@[\w\.-]+', abc)
for email in emails:
print(email)
# Example of w+ and ^ Expression
import re
xx = "guru99,education is fun"
r1 = re.findall(r"^\w+", xx)
print(r1)
# Example of \s expression in re.split function
import re
xx = "guru99,education is fun"
r1 = re.findall(r"^\w+", xx)
print(re.split(r'\s', 'we are splitting the words'))
print(re.split(r's', 'split the words'))
# Using re.findall for text
import re
list = ["guru99 get", "guru99 give", "guru Selenium"]
for element in list:
z = re.match("(g\w+)\W(g\w+)", element)
if z:
print(z.groups())
patterns = ['software testing', 'guru99']
text = 'software testing is fun?'
for pattern in patterns:
print('Looking for "%s" in "%s" ->' % (pattern, text)),
if re.search(pattern, text):
print('found a match!')
else:
print('no match')
abc = 'guru99@google.com, careerguru99@hotmail.com, users@yahoomail.com'
emails = re.findall(r'[\w\.-]+@[\w\.-]+', abc)
for email in emails:
print(email)
# Example of re.M or Multiline Flags
import re
xx = """guru99
careerguru99
selenium"""
k1 = re.findall(r"^\w", xx)
k2 = re.findall(r"^\w", xx, re.MULTILINE)
print(k1)
print(k2)
| false |
1cf1bff4094a457338c7a323d27381ea688c5aa2 | liuyang2239336/xuexi | /PythonTest/demo4.py | 620 | 4.21875 | 4 | # 1. 输入用户名和密码
# 2. 去判断登录是否成功- 如果登录成功-打印登录成功;反之,打印失败!
# 能够看懂就可以
username = input("请输入用户名:")
password = input("请输入密码:")
if username == "" and password == "":
print("用户名或者面不能为空!")
exit() # 退出程序
# db的作用就是模拟数据
db = {"username":"test", "password":"test"}
# 如何去判断输入的密码和db里面的密码一致
if username == db.get("username") and password == db.get("password"):
print("登录成功!")
else:
print("登录失败!") | false |
acf0cd446796519b7c0d70fb3b4c4b136462fec2 | arpan-k09/INFOSYS-PYTHON-PROG | /palindrome.py | 317 | 4.1875 | 4 | #PF-Assgn-31
def check_palindrome(word):
str1 = word
str2 = "".join(reversed(str1))
print(str2)
if str1==str2:
return True
else:
return False
status=check_palindrome("malayalam")
if(status):
print("word is palindrome")
else:
print("word is not palindrome") | false |
a86966cedb820536a599aaec9cbe373c3f7a659f | arpan-k09/INFOSYS-PYTHON-PROG | /6_1.py | 389 | 4.28125 | 4 | #PF-Assgn-40
def is_palindrome(word):
s = word.lower()
string = "".join(reversed(s))
if string == s:
return True
else:
return False
#Provide different values for word and test your program
result=is_palindrome("MadAMa")
print(result)
if(result):
print("The given word is a Palindrome")
else:
print("The given word is not a Palindrome") | true |
4b8cf0ab6a4a0e6a4baa6118840c963513b3dbd9 | GarciaFrida/Python_Projects_DC | /multiple.py | 956 | 4.25 | 4 | #Create a program that will ask for a username and then a password.
#If the username or password length is less than 6 charecters give a too short message.
#if the username or password length is greater than 12 charecters give a too long message
#Have the user confirm the password in again.
#If the passwords match give a sucess message
#if the passwords do not match give a mismatch message
#If the password is only numbers give a message that says it cannot be a number.
#challange have only one print statement in the whole program.
user_name = input("""
Please Enter Username:
""")
password = input("""
Please Enter Password:
""")
if len(user_name) < 6 and len(password) < 6:
print("Too Short")
elif len(user_name) > 6 and len(password) > 6:
print("Too Long")
print("""
Please Confirm Password:
""")
password_confirmation = input()
if password_confirmation == password:
print("Success")
else:
print("Please try again")
| true |
e8afc6fd440c9102c0c60ac608e4c8d2ad29c966 | GarciaFrida/Python_Projects_DC | /hello.py | 730 | 4.5 | 4 | my_name = "Frida"
#my_name is the variable name and it prints out the statement "Frida" which is my name
my_favorite_drink = "beet juice"
my_favorite_dessert = "cookie"
my_favorite_meal = "french fries and a big fat juicy burger"
#print(my_name)
#print(my_favorite_drink)
#print(my_favorite_dessert)
#print(my_favorite_meal)
#I've commented out these multiple prints because I wanted to get fancy, but if I want to I can add them again
print("Hello Everyone, I'm " + my_name + ". I enjoy drinking " + my_favorite_drink + " while eating " + my_favorite_meal + " and I finish this off with a " + my_favorite_dessert + " . ")
#this takes all my variables and concatenates them into a sentence which the console then prints out
| true |
a7eae1870e22708722fe5ebb8d5a8ae208eea9a0 | GarciaFrida/Python_Projects_DC | /name_welcome.py | 412 | 4.40625 | 4 | #Create a program that asks for your name and the returns it back to you with a greeting.
#Use Variables when possible
#Create a program that will ask for you age and then put 3 lines down and say "wow" at the end.
#Only 2 strings can be used.
print("Hi there, please insert your name ")
user_name = input()
print("Welcome" , user_name)
ask_age = "what is your age? "
wow_msg = "wow"
age = int(input())
| true |
6bf763f1050fb481c74265266eddba815411b32a | rtate7/CSS-225-Module-4 | /time.py | 421 | 4.21875 | 4 | # Edited for debugging by Robert Tate on 1/22/21
#
# Gets current time and wait time from user and prints the time
# when the wait will be completed
currentTimeStr = input("What is the current time (in hours 0-23)? ")
waitTimeStr = input("How many hours do you want to wait? ")
currentTimeInt = int(currentTimeStr)
waitTimeInt = int(waitTimeStr)
finalTimeInt = (currentTimeInt + waitTimeInt) % 24
print(str(finalTimeInt))
| true |
c00c0f0befdb7c80ed1d2fc8f46af15f8f8f8497 | enchantress085/Python-Basic | /Functions_loops/even_odd_num.py | 1,290 | 4.3125 | 4 | # -*- coding: utf-8 -*-
"""
Odd or even Number using for loops
"""
for n in range(1, 20): #-- [2,3,4,5,6,7,8,9.....]
for x in range(2,n):#-- [],[2],[2,3],[2,3,4]....
if n % x == 0:
print(f'{n} Equals {x} * {n//x} >')
break
else:
print(f"{n} is a prime Number >")
#-- Even Number
for num in range(1, 30):
if num % 2 == 0:
print(f"Found an even number, {num} ")
continue
print(f"Found a number, {num}")
"""
#-- IF statement Even or odd using format
format() method returns the formatted string.
format() method takes any number of parameters.
But, is divided into two types of parameters:
Positional parameters - list of parameters that can
be accessed with index of
parameter inside
curly braces {index}
Keyword parameters - list of parameters of type
key=value, that can be accessed
with key of parameter inside curly
braces {key}
"""
num = int(input("Enter a number: "))
if num %2 == 0:
print("{0} is even ".format(num))
else:
print("{0} is Odd".format(num))
| true |
2bf0cd37388de534df591c7deaad55e45bafdbc5 | enchantress085/Python-Basic | /Functions/f_argument.py | 1,092 | 4.5 | 4 | """
You can call a function by using the following
types of formal arguments −
1.Required arguments
2.Keyword arguments
3.Default arguments
4.Variable-length arguments
"""
print("\n")
print("--------Required arguments-------\n")
def me(st):
print ("Print : ", st)
return
me("MD. Golam Maulla Shaju")
print("\n")
print("--------Keyword arguments-------\n")
def me1(st):
print ("Resulr print : ",st)
return
me1(st = 'GM Shaju')
print("--------@nd-------\n")
def me2(name,institute):
print ("print name : ",name)
print("print institute : ",institute)
return
me2('Shaju', 'Daffodil International Univercity')
print("\n")
print("--------Default arguments-------\n")
def meinfo(name, age = 22):
print ("Name : ",name)
print ("age : ",age)
return
meinfo('shaju', 21)
meinfo('Rakib')
print("\n")
print("--------Variable length arguments-------\n")
def printinfo(arg, *vartuple):
print("Output is : ")
print(":>",arg,"\n")
for var in vartuple:
print(":>",var,"\n")
return
printinfo('shaju')
printinfo('Raju', 'Rakib', 'Shovon', 'Janena')
| false |
a431d456c7bff65f589faf3675b398599b44a543 | enchantress085/Python-Basic | /advance_set.py | 976 | 4.46875 | 4 | """
A set is an unordered collection of items.
Every element is unique (no duplicates) and
must be immutable (which cannot be changed).
However, the set itself is mutable.
We can add or remove items from it.
Sets can be used to perform mathematical set
operations like union, intersection,
symmetric difference etc.
"""
# ----- Empty set
a = {}
print(type(a))
a = set()
print(type(a))
# -- change a set
my_set = {1, 3}
print(my_set)
my_set.add(2)
print(my_set)
# Multiple elements add
my_set.update([4,5,6])
print(my_set)
# -- add list and set
my_set.update([7,8], {9,10})
print(my_set)
"""
Set Union, Intersection , Difference, Symmetric Difference
"""
# --- set union
set_one = {1,2,3,4,5}
set_two = {1,3,5,7,9,11}
#print(set_one.union(set_two))
print(set_one | set_two)
# -- set intersection
#print(set_one.intersection(set_two))
print(set_one & set_two)
#-- set difference
#print(set_one.difference(set_two))
print(set_one - set_two)
| true |
bfdc139dac8ca8b94e190e2dd501f540934dc64f | sebaheredia/HO-python | /Ej1c.py | 771 | 4.125 | 4 |
# Importamos la libreria con las funciones que se van a utilizar
import numpy as np
# Aqui se define el numero a descomponer en numeros primos
n=2*3*5*7
print("n = ",n)
# El primer divisor de prueba se define 2, ya que todo numero es divisible por 1
i=2
# aux es un valor auxiliar que seria el ultimo cociente de la descomposicion con el ultimo numero primo
aux=n
# La condicion i <= n/2 se debe a que no va a haber ningun numero primo mayor a n/2
while i <= n/2:
# print("i = ",i)
if aux%i==0:
aux=aux/i
max_div=i
print("max_div = ",max_div)
print("aux = ",aux)
# Se sube e 1 el divisor propuesto
i=i+1
# Se imprime el ultimo valor del maximo divisor
print("max_div = ",max_div)
| false |
52aba787d8f08ce8b0b4da76027d837bb6cfb922 | Maopos/Basic_Python | /008_Sentencias_de_control/8.04_Condiciones_multiplies.py | 309 | 4.15625 | 4 | # Evaluacion de condiciones multiples.
print()
numero = int(input('Escriba un numero: '))
print()
if numero % 5 == 0 and numero >= 20 and numero <= 40:
print('El numero {} es divisible entre 5 y se halla entre 20 y 40'.format(numero))
else:
print('El numero no cumple los requerimientos.')
print() | false |
ae52b915af1beb863ad16ffb7674f31209196aa8 | Maopos/Basic_Python | /005_Tipos_de _Datos/5.03_complejos_complex.py | 677 | 4.125 | 4 | # Numeros Complejos
print()
numero_complejo = 2 - 3j #forma literal
print('Contenido variable compleja: ', numero_complejo)
print('El tipo de dato de numero_complejo es: ', type(numero_complejo))
print()
numero_complejo = complex(2, -3)
print('Contenido variable compleja: ', numero_complejo)
print('El tipo de dato de numero_complejo es: ', type(numero_complejo))
print()
print('== Operaciones aritmeticas con numeros complejos ==')
suma = 2 -3j + (1 +5j)
print('Suma: ', suma)
resta = 2 -3j - complex(1, 5)
print('Resta: ', resta)
producto = 2 -3j * complex(1, 5)
print('Producto: ', producto)
division = 2 -3j / complex(1, 5)
print('Producto: ', division)
print() | false |
b64e882d9ce63c2869fe0a387a0bf83ad7202876 | Maopos/Basic_Python | /005_Tipos_de _Datos/5.06_tuplas_tuple.py | 2,199 | 4.125 | 4 | # Tipo de dato compuesto - Tupla - estatico
print()
punto = (2, 5)
print('Tipo de dato', type(punto))
print(punto)
print('Cantidad de elementos:', len(punto))
print()
# Acceso a los elementos de una Tupla
x = punto[0]
y = punto[1]
print('El valor de x es: ', x)
print('El valor de y es: ', y)
print()
# Desempaquetamiento:
abscisa, ordenada = punto
print('El valor de x es: ', abscisa)
print('El valor de y es: ', ordenada)
print()
# Acceso con indice negativo
ultimo_elemento = punto[-1]
penultimo_elemento = punto[-2]
print('El valor de x es: ', penultimo_elemento)
print('El valor de y es: ', ultimo_elemento)
print()
# Inmutabilidad
# punto[0] = 3 // Genera Type error
punto = (3, 7) # Se puede reemplazar el contenido de la varible
print(punto)
print()
# Iteracion de una tupla
primos = (2, 3, 5, 7, 11, 13, 17, 19)
print('Cantidad de elementos: ', len(primos))
print()
print('== Iteracion con while ==')
i = 0
while i < len(primos):
print(f'El elemento en el indice {i} es igual a {primos[i]}')
i += 1
print()
print('== iteracion con ciclo for ==')
for i in range(len(primos)):
print(f'El elemento en el indice {i} es igual a {primos[i]}')
print()
print('== Iteracion de una tupla con enumerate ==')
print(primos)
for i, v in enumerate(primos):
print(f'{i}: {primos[i]}')
print()
# Mecanismos alternativos para crear tuplas
# Modo A:
numeros = 1, 2, 3
print('Tipo de datos de la variable numeros: ', type(numeros))
print('Cantidad de elementos: ', len(numeros))
for i, v in enumerate(numeros):
print(f'{i}: {numeros[i]}')
print()
numeros = 1,
print('Tipo de datos de la variable numeros: ', type(numeros))
print('Cantidad de elementos: ', len(numeros))
for i, v in enumerate(numeros):
print(f'{i}: {numeros[i]}')
print()
# Modo B:
numeros = tuple([9])
print('Tipo de datos de la variable numeros: ', type(numeros))
print('Cantidad de elementos: ', len(numeros))
for i, v in enumerate(numeros):
print(f'{i}: {numeros[i]}')
print()
print('== Operaciones clase tuple ==')
colores = 'negro', 'blanco', 'negro', 'azul', 'negro', 'rojo', 'azul', 'verde'
print(colores.count('negro'))
print(colores.index('rojo'))
print() | false |
064ddfe004bda126d3128c2c0f499dda2c5e3bd3 | Maopos/Basic_Python | /009_Ciclos/Ejercicios/9.08_cant_digitos_letras_txt.py | 507 | 4.1875 | 4 | # Ejercicio 9.8: Contar la cantidad de dígitos y letras que tiene un texto.
print()
texto = input('Escribe un texto: ')
print()
digitos = 0
letras = 0
spaces = 0
otros = 0
for i in texto:
if i.isnumeric():
digitos += 1
elif i.isalpha():
letras += 1
elif i.isspace():
spaces += 1
else:
otros += 1
print('Caracteres: ', len(texto))
print('Digitos: ', digitos)
print('Letras: ', letras)
print('Espacios: ', spaces)
print('Otros: ', otros)
print() | false |
3a692657fc46dfbd42609d9b2cbb2db41969449a | Maopos/Basic_Python | /020_Problemas_map_reduce_filter_zip/001_map.py | 530 | 4.34375 | 4 | ''' Problema #1:
Utilizar la función incorporada map() para crear una función que retorne una lista con la longitud de cada palabra (separadas por espacios) de una frase. La función recibe una cadena de texto y retornará una lista. '''
print('======================')
print()
frase = 'Bienvenidos a Python utilizando map'
cantidad_letras = list(map(lambda x: len(x), frase.split()))
cantidad_letras_2 = list(map(len, frase.split()))
print(cantidad_letras)
print(cantidad_letras_2)
print()
print('======================') | false |
923a2750ce32aa7d85faff4dd2ca3b54dec3626f | Maopos/Basic_Python | /010_Errores_y_excepciones/10.03_indices_listas.py | 650 | 4.1875 | 4 | # Acceso de elementos de una lista
print('======================')
print()
lenguajes = ['Python', 'C#', 'Html', 'Css', 'Java', 'C', 'JavaScript']
print('Cantidad de lenguajes: ', len(lenguajes))
print('Primer elemento: ', lenguajes[0])
print()
indice = 7
try:
print('Ultimo elemento: ', lenguajes[indice])
except IndexError:
print('El indice %i no existe...' % indice)
print('Terminó el programa.')
print()
print('=== Intento de acceso a indices negativos ===')
indice = -8
try:
print('Ultimo elemento: ', lenguajes[indice])
except:
print('El indice %i no existe...' % indice)
print()
print('======================') | false |
f154da00adc92b4aee4b2782e23da8360820e5cd | maoriko/w3resource | /6 get list and tuple input.py | 316 | 4.34375 | 4 | # Write a Python program which accepts a sequence of comma-separated numbers from user and generate a list and a tuple with those numbers.
input_list = input("to get list please enter your numbers seperated with comma: ")
list = input_list.split(",")
tuple = tuple(list)
print('List :', list)
print('Tuple:', tuple) | true |
7296f0582bf06e594301717eb27c51d2cfbafc3b | anniboo/hw-and-les | /lesson 2.py | 934 | 4.15625 | 4 | friends = 'Максим Леонид1'
print(friends)
print(len(friends))
print(friends.find('Лео'))
print(friends.split())
friends = 'Максим;Леонид1'
print(friends.split(';'))
print(friends.isdigit())
number = '123'
print(number.isdigit())
print(friends.upper())
print(friends.lower())
# Форматирование строк
name = 'Leo'
age = 30
#1. конкатенация
hello_str = 'Привет, ' + name + ' тебе ' + str(age) + ' лет'
print (hello_str)
#2.% s - сюда попадает строка, а в "d" попадает число
hello_str = 'Привет %s тебе %d лет'%(name, age)
print (hello_str)
#3(
hello_str = 'Привет {} тебе {} лет'.format(name, age)
print (hello_str)
friend_name = 'Max'
friends = ['Max','Leo','Kate']
roles = ('admin','guest','user')
#while
i = 0
while i < len(friends) :
friend = friends[i]
print(friend)
i+=1
#for
for friend in friends :
| false |
28027fb02ced983b8365a26bae6b7b9ef4f4d39f | abhishekbisneer/Python_Code | /Exercise-24.py | 1,364 | 4.46875 | 4 | #Exercise 24 (and Solution)
'''
This exercise is Part 1 of 4 of the Tic Tac Toe exercise series.
The other exercises are: Part 2, Part 3, and Part 4.
Time for some fake graphics! Let’s say we want to draw game boards that look like this:
--- --- ---
| | | |
--- --- ---
| | | |
--- --- ---
| | | |
--- --- ---
This one is 3x3 (like in tic tac toe).
Obviously, they come in many other sizes (8x8 for chess, 19x19 for Go, and many more).
Ask the user what size game board they want to draw,
and draw it for them to the screen using Python’s print statement.
Remember that in Python 3, printing to the screen is accomplished by
print("Thing to show on screen")
Hint: this requires some use of functions, as were discussed previously on this blog and elsewhere on the Internet, like this TutorialsPoint link.
'''
'''
def dots(n):
lines=" --- "
print(lines*n)
def bars(n):
n=n+1
bars="| "
print(bars*n)
if __name__=="__main__":
n=int(input("please provide the number: \n>>>"))
for i in range(1,n+1):
dots(n)
bars(n)
dots(n)
'''
#print("------------------------------------------------------------")
a="---".join(" ")
b=" ".join("||||")
print(("\n".join((a,b,a,b))))
'''
a = '---'.join(' ')
b = ' '.join('||||')
print('\n'.join((a, b, a, b, a, b, a)))
''' | true |
09277ed6f52083f817f9bdc9226d7b14836b92a5 | abhishekbisneer/Python_Code | /Exercise-26.py | 2,855 | 4.15625 | 4 | #Check Tic Tac Toe Solutions
#Exercise 26
'''
This exercise is Part 2 of 4 of the Tic Tac Toe exercise series.
The other exercises are: Part 1, Part 3, and Part 4.
As you may have guessed, we are trying to build up to a full tic-tac-toe board.
However, this is significantly more than half an hour of coding, so we’re doing it in pieces.
Today, we will simply focus on checking whether someone has WON a game of Tic Tac Toe,
not worrying about how the moves were made.
If a game of Tic Tac Toe is represented as a list of lists, like so:
game = [[1, 2, 0],
[2, 1, 0],
[2, 1, 1]]
where a 0 means an empty square, a 1 means that player 1 put their token in that space,
and a 2 means that player 2 put their token in that space.
Your task this week: given a 3 by 3 list of lists that represents a Tic Tac Toe game board,
tell me whether anyone has won, and tell me which player won, if any.
A Tic Tac Toe win is 3 in a row - either in a row, a column, or a diagonal.
Don’t worry about the case where TWO people have won -
assume that in every board there will only be one winner.
Here are some more examples to work with:
winner_is_2 = [[2, 2, 0],
[2, 1, 0],
[2, 1, 1]]
winner_is_1 = [[1, 2, 0],
[2, 1, 0],
[2, 1, 1]]
winner_is_also_1 = [[0, 1, 0],
[2, 1, 0],
[2, 1, 1]]
no_winner = [[1, 2, 0],
[2, 1, 0],
[2, 1, 2]]
also_no_winner = [[1, 2, 0],
[2, 1, 0],
[2, 1, 0]]
'''
def row_check(l):
for r in range(0,2):
if 0 not in l[r]:
if l[r][0]==l[r][1] and l[r][1]==l[r][2]:
return "row wins"
return "row fails"
def col_check(l):
for c in range(0,2):
if (l[0][c]!=0) and (l[1][c]!=0) and (l[2][c]!=0):
if l[0][c]==l[1][c] and l[1][c]==l[2][c]:
return "Col wins"
return "Col fails"
def diagnol_check(l):
if (l[0][0]!=0) and (l[1][1]!=0) and (l[2][2]!=0):
if l[0][0]==l[1][1] and l[1][1]==l[2][2]:
return "Diagnol wins"
return "Diagnol fails"
#winner_is_2
L1= [[2, 2, 0],
[2, 1, 0],
[2, 1, 1]]
#winner_is_1
L2= [[1, 2, 0],
[2, 1, 0],
[2, 1, 1]]
#winner_is_also_1
L3= [[0, 1, 0],
[2, 1, 0],
[2, 1, 1]]
#no_winner
L4= [[1, 2, 0],
[2, 1, 0],
[2, 1, 2]]
#also_no_winner
L5= [[1, 2, 0],
[2, 1, 0],
[2, 1, 0]]
def consol(*lists):
biglist=[]
for items in lists:
biglist.append(lists)
return biglist
if __name__=="__main__":
biglist=[]
biglist.append(consol(L1,L2,L3,L4,L5))
#consol(L1,L2,L3,L4,L5)
print(len(biglist))
print(biglist)
for i in range(0,len(biglist)):
l=[]
l=biglist[i]
print("--------------------------------------")
print("LIST {}".format(i+1))
print(row_check(l))
print(col_check(l))
print(diagnol_check(l))
| true |
e12517c6df4f7796b63bdc26efef650d43c127c6 | abhishekbisneer/Python_Code | /Exercise-33.py | 1,210 | 4.625 | 5 | #Birthday Dictionaries
#Exercise 33 (and Solution)
'''
This exercise is Part 1 of 4 of the birthday data exercise series.
The other exercises are: Part 2, Part 3, and Part 4.
For this exercise, we will keep track of when our friend’s birthdays are,
and be able to find that information based on their name.
Create a dictionary (in your file) of names and birthdays.
When you run your program it should ask the user to enter a name, and return the birthday of that person back to them. The interaction should look something like this:
>>> Welcome to the birthday dictionary. We know the birthdays of:
Albert Einstein
Benjamin Franklin
Ada Lovelace
>>> Who's birthday do you want to look up?
Benjamin Franklin
>>> Benjamin Franklin's birthday is 01/17/1706.
'''
bday={'Arjun':'26-Oct-1986','Abhishek':'14-Jan-1986'}
def userinput(bday):
#k=list(bday.keys())
print("Welcome to the birthday dictionary. We know the birthdays of:")
for i in bday:
print(i)
user_in=input("Who's birthday do you want to look up?\n>>>")
if user_in in bday:
print("{} Birthday is on {}".format(user_in,bday[user_in]))
else:
print("\n {}'s Birthday is not available".format(user_in))
if __name__=="__main__":
userinput(bday) | true |
77a3451304bd206bd2ef1da261fa8dc55c14f3d1 | sandruskyi/CursoPythonOW | /EjerciciosVariables/ejerCadenas.py | 691 | 4.125 | 4 | #!/usr/bin/env python
"""
#1. Crear un programa que lea por teclado una cadena y un carácter, e inserte el carácter entre cada letra de la cadena. Ej: separar y , debería devolver s,e,p,a,r,a,r
cad = input("Cadena")
car = input("Caracter")
print(car.join(cad))
#2. Crear un programa que lea por teclado una cadena y un carácter, y reemplace todos los dígitos en la cadena por el carácter. Ej: su clave es: 1540 y X debería devolver su clave es: XXXX
cad = input("Cadena")
car = input("Caracter")
for i in range(len(cad)):
p = cad[i]
cad = cad.replace(p, car)
print(cad)
"""
#3. Crea un programa python que lea una cadena de caracteres y muestre la siguiente información:
| false |
96f6a4af0f3d01f702cc3785c70d2ae712206015 | SnyderMbishai/python_exercises | /reverse.py | 372 | 4.125 | 4 |
def reverse_string():
string = input("Write a sentence of your own choice: ")
new_string = []
string = string.split()
l = len(string)-1
for i in string:
new_string.append(string[l])
l -= 1
return (' '.join(new_string))
print(reverse_string())
#a simpler way
string2=input("sentence here: ")
print (' '.join( (string2.split()[::-1])))
| true |
9f50209768c777ae643c87f4e036ffabed413545 | SnyderMbishai/python_exercises | /arithmetic.py | 761 | 4.15625 | 4 | """Create a program that reads two integers, a and b, from the user.Your program should
compute and display:
• The sum of a and b
• The difference when b is subtracted from a
• The product of a and b"""
from math import log10
def arithmetic():
a = int(input("Enter a number: "))
b = int(input("Enter another number: "))
sm = a+b
sub = a-b
product = a*b
quotient = a/b
remainder = a%b
log = log10(a)
power = a**b
print ("Sum of a and b is: %.2f \nDifference of a and b is: %.2f \nProduct of a and b is: %.2f"%(sm, sub, product))
print("quotient: %.2f"% quotient)
print("remainder: %.2f"% remainder)
print("log: %.2f"% log)
print("power: %.2f"% power)
arithmetic()
| true |
fc8e802b9f6a17e1ab0d7b60063e5088c80f7e6e | eduardmak/learnp | /lesson2/homework/lines.py | 775 | 4.4375 | 4 | # Написать функцию, которая принимает на вход две строки.
# Если строки одинаковые, возвращает 1.
# Если строки разные и первая длиннее, возвращает 2.
# Если строки разные и вторая строка 'learn', возвращает 3.
def function(stroka1, stroka2):
if stroka1 == stroka2:
return 1
elif stroka2 == "learn":
return 3
elif len(stroka1) <= len(stroka2):
return 2
else:
return("Пизец,в задание ничего не сказано!")
inp = input("Введи первую строку! ")
inp2 = input("Введи вторую строку! ")
print(function(inp, inp2))
| false |
53584396541214a896e050f167ba024c47cbf905 | AngryCouchPotato/AlgoExpert | /arrays/LongestPeak.py | 1,405 | 4.40625 | 4 | # Longest Peak
#
# Write a function that takes in an array of integers and returns
# the length of the longest peak in the array.
#
# A peak is defined as adjacent integers in the array that are strictly
# increasing until they reach a tip ( the highest value in the peak),
# at which point they become strictly decreasing. At least three integers
# are required to form a peak.
# For example, the integers 1, 4, 10, 2 form a peak, but the integers 4, 0, 10
# don't and neither do the integers 1, 2, 2, 0. Similarly, the integers 1, 2, 3
# don't form a peak because there aren't any strictly decreasing integers after the 3.
#
# Sample Input
# array = [1, 2, 3, 3, 4, 0, 10, 6, 5, -1, -3, 2, 3]
# Sample Output
# 6 // 0, 10, 6, 5, -1, -3
#
def longestPeak(array):
if array == None or len(array) < 3:
return 0
peaks = []
for i in range(1, len(array) - 1):
if array[i] > array[i - 1] and array[i] > array[i + 1]:
peaks.append(i)
maxLength = 0
if len(peaks) == 0:
return maxLength
for p in peaks:
curLength = 1
l = p
r = p
while l > 0 and array[l - 1] < array[l]:
curLength += 1
l -= 1
while r < (len(array) - 1) and array[r] > array[r + 1]:
curLength += 1
r += 1
if curLength > maxLength:
maxLength = curLength
return maxLength | true |
f88a0df1e2462fa7f8914f4dd2477603f9acc51b | JpryHyrd/python_2.0 | /Lesson_2/7.py | 474 | 4.34375 | 4 | """
7. Напишите программу, доказывающую или проверяющую, что для множества
натуральных чисел выполняется равенство: 1+2+...+n = n(n+1)/2,
где n - любое натуральное число.
"""
def mn():
a = 1 + 2 + 3 + 4 + 5
n = 5
if a == n * (n + 1) / 2:
print("Формула верна!")
else:
print("Что-то не то...")
mn()
| false |
ef9b1893fc0559fed7835ae8f434577db66302cc | nchullip/Group-Project-I-Data-Analysis | /GetCountryList.py | 863 | 4.34375 | 4 | # Importing Dependencies
import pandas as pd
import numpy as np
def get_country_list(data_file, num):
################################################
# This function takes the Data file as input and returns
# a list of countries with the most population.
#
# Argument: data_file - CSV file
# num - Integer
################################################
# Read the file and store into Pandas data frame
population_data = pd.read_csv(data_file)
# Filtering the DataFrame to use only required information
country_yr_df = population_data[["Country Name","2018"]]
# Sorting the DataFrame
country_yr_df = country_yr_df.sort_values(["2018"],ascending=False)
country_df = country_yr_df[:num]
# Converting DataFrame to List
country_list = country_df['Country Name'].tolist()
return country_list | true |
50799ccd441cbb2651a1e265d81def7c9b083d4d | guhaneswaran/Django-try | /scratch_7.py | 782 | 4.125 | 4 | # Instance variables - changes depends on the object. Defined inside __init__
# Class Variables - is fixed. Defined outside __init__ inside the class
# Namespace- the space where we create and store object/variable
# Class namespace - to store all the class variable
# Instance namespace - to store all the instance variable
class Car:
wheels = 4
def __init__(self):
self.mil = 10 # Instance variables
self.company = 'BMW' # Instance variables
c1 = Car()
c2 = Car()
c1.mil = 8 # Changing instance variable
print( c1.mil , c1.company , c1.wheels)
print( c2.mil , c2.company , c2.wheels)
Car.wheels = 5 # changing class variable
print( c1.mil , c1.company , c1.wheels)
print( c2.mil , c2.company , c2.wheels) | true |
4eafb7b0b9bd65b3f7cb8184dd33250f056cf10f | guhaneswaran/Django-try | /scratch_8.py | 1,387 | 4.15625 | 4 | # Methods:
# Instance method , class method , static method
# Instance method - two types Accessor method and Mutator method
# Accessor method - Just fetch the value of instance variable
# Mutator method - Change the value of the instance variable
class Student:
school = 'Telusko' # Class variable
def __init__(self , m1, m2,m3):
self.m1 = m1
self.m2 = m2
self.m3 = m3
def avg(self): # instance method as it works with the object
return ( self.m1 + self.m2 + self.m3)/3
# CAN USE GETTERS AND SETTERS
def get_m1(self): # GETTERS - only gets the value and doesnt change hence Accessor
return self.m1
def set_m1(self , value): # we can use constructors to pass the value or setters
self.m1 = value # SETTERS - change the values hence Mutators
@classmethod # This is a decorator used for class method
def getSchool(cls): # working with class variable we use cls. This is a CLASS METHOD
return cls.school
@staticmethod # This is a decorator used for static method
def info(): # This is static method. Doing something extra notthing to do with class or instance
print("This is a Student class ...")
s1 = Student(34, 65, 77)
s2 = Student(23, 65 , 12)
print(s1.avg())
print(s2.avg())
print(Student.getSchool())
Student.info() | true |
e36fe2b79f4190942303519cef67a3ddc26a7982 | VendrickNZ/GuessTheNumber | /GuessTheNumber.py | 1,677 | 4.3125 | 4 | import random
"""The computer generates a random number and the user tries to guess it."""
def random_number():
"""picks a random number from a range function and
returns the range bounds and chosen number"""
range = number_range()
low = range[0]
high = range[1]
return (random.randrange(low, high), low, high)
def number_range():
"""creates a range of numbers that the chosen number will lie within"""
low = random.randint(0, 20)
high = random.randint(21, 50)
return (low, high)
def guess_the_number():
"""The user attempts to guess the number chosen"""
game_over = False
number_and_range = random_number()
chosen_number = number_and_range[0]
low = number_and_range[1]
high = number_and_range[2]
chances = 3
while game_over == False:
guessed_number = int(input(f"Choose a number between {str(low)} and {str(high)}: "))
if guessed_number < low or guessed_number > high:
print(f"Number chosen not in range, try again")
elif guessed_number == chosen_number and chances > 0:
print(f"Congratulations {str(guessed_number)} was correct!")
game_over = True
elif chances <= 1:
print(f"No chances remaining \nThe number was {chosen_number} \nGame Over")
game_over = True
else:
chances -= 1
print(f"Chances remaining: {chances}")
if (chosen_number - low) and (high - chosen_number) >= 5: # whether it should decrease range
low += (chosen_number - low) // 2 # decreases the range
high -= (high - chosen_number) // 2
guess_the_number()
| true |
973095bd95e959ab76aaa94a2cc19ced49761efd | marshalloffutt/lists | /places.py | 650 | 4.5625 | 5 | places = ["Mars", "Egypt", "Venice", "Tokyo", "Vancouver"]
# Print places
print(places)
# Print sorted places in alphabetical order
print(sorted(places))
# Print original places
print(places)
# Print sorted places in reverse alphabetical order
print(sorted(places, reverse=True))
# Show that original list is unchanged
print(places)
# Use reverse() to change the order of the list
places.reverse()
print(places)
# Use reverse() to change the order of list again
places.reverse()
print(places)
# Use sort() to alphabetize the list
places.sort()
print(places)
#Use sort() to to to reverse alphabetize
places.sort(reverse = True)
print(places) | true |
1504c91c99c544ff2fd4baa478f7ac6a048d7132 | pallavim98/ProxyCloud | /Threading/threading_example.py | 1,789 | 4.78125 | 5 | # Python program to illustrate the concept
# of threading
# importing the threading module
import threading
def print_cube(num):
"""
function to print cube of given num
"""
print("Cube: {}".format(num * num * num))
def print_square(num):
"""
function to print square of given num
"""
print("Square: {}".format(num * num))
if __name__ == "__main__":
# creating thread
t1 = threading.Thread(target=print_square, args=(10,))
t2 = threading.Thread(target=print_cube, args=(10,))
# starting thread 1
t1.start()
# starting thread 2
t2.start()
# wait until thread 1 is completely executed
t1.join()
# wait until thread 2 is completely executed
t2.join()
# both threads completely executed
print("Done!")
""" NOTE : threading.Thread(arg1 , arg2) -> this is using the constructor of the threading class to create
an object called Thread -> if confused think of it as just a simple structure and an instance of that structure
As per what i read from the documentation file the arguments we will use are:
name => name of the thread so that it can be uniquely identified
target => target of the thread so that it can run thatt function in the seperate thread
args => arguments for that function
SIMPLE ain't it ?? ;)
The threading class now contains other methods like start() and join().
SO :
Once the threads start, the current program (you can think of it like a main thread) also keeps on executing.
In order to stop execution of current program until a thread is complete, we use join method.
t1.join()
t2.join()
As a result, the current program will first wait for the completion of t1 and then t2.
Once, they are finished, the remaining statements of current program are executed.
""" | true |
eae3a2e937b369a24d403bc317d22b985e72fc02 | fadedphoenix7/ProgramacionEstructurada | /Unidad 2-Estructuras de Control/Ejercicio4.py | 1,047 | 4.21875 | 4 |
#Autor:Jorge Chí 03/Febrero/19
#Entradas: numero (a redondear).
#Salidas: numero (redondeado).
#Procedimiento general: Se ingresa un numero. Si es negativo se pide de nuevo.
#Se redondea el numero a la centena más cercana
#se inicia la variable que guarda el número
numero = int( 0 )
while 1 :
print( "Ingresa un numero que quieras redondear a la centena mas cercana:" )
numero = int( input( ) )
if ( numero < 0 ) :
print( "ERROR, numero menor que 0" )
else :
break
#Proceso : si el número es 100 o menor que 100 se imprime el redondeo 100. sino,
#se hace el proceso de redondeo a la siguiente centena cercana
if (numero <= 100 ) :
print( "El redondeo es: 100." )
else :
numero = int( int(( int(( numero + 50 )) / 100) ) * 100 )
print( "El redondeo es:",numero )
# QA Reviso: Raul Rivadeneyra
# Entradas: 1, 50, 23501, 540
# Salidas: Ok, Ok, Error, Error
# Se redondea hacia arriba (ceil), no a la centena mas cercana, 23501 claramente está mas cerca a 23500 que 23600
# Corregido
| false |
18fcd3a4caf16cd7d9283d4f7f8db8fab953b052 | adityatanwar800/FSDP2019 | /Day03/intersection.py | 257 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 5 18:16:29 2019
@author: Aditya Tanwar
"""
lst1=input("enter the value").split()
set1=set(lst1)
lst2=input("enter the value for set 2").split()
set2=set(lst2)
set3=set1.intersection(set2)
lst=list(set3)
print(lst) | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.