blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
f1f4160266f43db225f1814c7443f4e7413cf287 | gouthamganesan/Automate-the-boring-stuff-with-Python-practice-Projects | /Practice Projects/strongPass.py | 656 | 4.1875 | 4 | # A python program to check if a password is strong
# strongPass.py
import re
def checkStrength(password):
conditions = [r'.{8,}', r'[A-Z]*', r'[a-z]*', r'[0-9]*']
for condition in conditions:
regex = re.compile(condition)
match = regex.search(password)
if not match:
return 0
return 1
while True:
password_inp = input('Enter the password ( Leave blank to exit ) ')
if not password_inp:
break
strength = checkStrength(password_inp)
if strength == 1:
print('Superb! thats a hard one to crack!')
else:
print('Sorry, Thats an easy one, try another combination')
| true |
359933dd611d397553b85cc52332ed29909c48b8 | Tejas-Naik/Python-refresh-Mosh | /5strings.py | 1,728 | 4.125 | 4 | # If you want to have an uphostrophe in the str you use "" in the outside
course = "Python's course for Beginners"
print(course)
# If you want to have "" in the sentence we use '' in the outside
course = 'Python for "Beginners!"'
print(course)
# if you want to type a big string like the message in the email we use """ message """
message = """OK what does he say about the current state?
[Mentor] Koose — Today at 10:27 AM
great
Tejas Naik — Today at 10:27 AM
OK Cool
what are u working on now?
[Mentor] Koose — Today at 10:28 AM
flask
but taking a break now
i was working on some Ui stuffs
Tejas Naik — Today at 10:28 AM
OK Great
Adobe?
[Mentor] Koose — Today at 10:29 AM
yh and UI Briefs
Tejas Naik — Today at 10:29 AM
you are doing a lot of things bro!!
[Mentor] Koose — Today at 10:34 AM
doing what i can'
Tejas Naik — Today at 10:36 AM
ALL The best You can do everything you want!
Tejas Naik — Today at 2:26 PM
I want to discuss about the slideshow images on the index page of MOBILE view
Tejas Naik — Today at 4:41 PM
Hello"""
print(message)
# getting the characters from the string we use the [] and we provide the index in that
# The index starts with 0 in Python
course = 'Python for Beginners'
letter_p = course[0]
letter_last = course[-1]
print(letter_p)
print(letter_last)
# To get the series of letters from the string we use the [start:end]
# the indexig works as upto but not including so that it won't take the last letter
chars_python = course[0:6] # remember that indexing start from 0
print(chars_python)
| false |
733551095fd532659c8faa6b7afb2ab88969dc08 | Tejas-Naik/Python-refresh-Mosh | /8arithmatic_operations.py | 685 | 4.53125 | 5 | # To perform arithmetic operations in python we can use
# -integers 10
# -Floats 10.123
# This is the addition
print(10 + 3)
# This is the subtraction
print(10 - 3)
# This is the multiplication
print(10 * 3)
# This is the normal division when you devide 10/3 returns 3.333333333333333333
print(10 / 3)
# This is the integer division
print(10 // 3)
# This is the modulo operator when you devide 10/3 returns 1 the reminder
print(10 % 3)
# The power rule
print(10 ** 3) # 10^3
# Augmented assignment operator (if you want to add 3 to the variable x(10))
x = 10
# Simple way
x = x + 3
# Augmented assignment
x += 3
print(x)
x -= 3
print(x)
x *= 3
print(x)
x /= 3
print(x)
| true |
131b625f0cd2f6f91074e6cd0d50bf4a334c9bb9 | Tejas-Naik/Python-refresh-Mosh | /12logical_operator.py | 797 | 4.53125 | 5 | # The logical operator is used when you wanna check more than one condition.
# Example - Loan eligibility - High Income & good credit score.
high_income = True
good_credit_score = False
# The 'and' operator
if high_income and good_credit_score:
# these lines of code gets executed if both the conditions are True
print("You are welcome to take loan!")
else:
print("Better luck next time!!")
# The 'or' operator
# Example - Loan sanction - High Income or good credit score.
if high_income or good_credit_score:
# these lines of code get's executed if one of the condition is True
print("Loan Sanctioned")
else:
print("your loan is under process!")
# The 'not' operator is used to reverse the operation
if not high_income:
print("You should make your income high!!")
| true |
f82564f3938b51dc96ce9e1037edaa3261ac4169 | VakinduPhilliam/Python_File_IO | /Python_File_CSV_Writer.py | 2,032 | 4.125 | 4 | # Python File CSV
# csv CSV File Reading and Writing.
# The so-called CSV (Comma Separated Values) format is the most common import and export format for spreadsheets and databases.
# CSV format was used for many years prior to attempts to describe the format in a standardized way in RFC 4180.
# The lack of a well-defined standard means that subtle differences often exist in the data produced and consumed by different applications.
# These differences can make it annoying to process CSV files from multiple sources.
# Still, while the delimiters and quoting characters vary, the overall format is similar enough that it is possible to write a single module
# which can efficiently manipulate such data, hiding the details of reading and writing the data from the programmer.
# The csv module implements classes to read and write tabular data in CSV format.
# It allows programmers to say, write this data in the format preferred by Excel, or read data from this file which was generated by Excel,
# without knowing the precise details of the CSV format used by Excel.
# Programmers can also describe the CSV formats understood by other applications or define their own special-purpose CSV formats.
# The csv modules reader and writer objects read and write sequences.
# Programmers can also read and write data in dictionary form using the DictReader and DictWriter classes.
# csv.writer(csvfile, dialect='excel', **fmtparams).
# Return a writer object responsible for converting the users data into delimited strings on the given file-like object.
# csvfile can be any object with a write() method. If csvfile is a file object, it should be opened with newline=''
import csv
with open('eggs.csv', 'w', newline='') as csvfile:
spamwriter = csv.writer(csvfile, delimiter=' ',
quotechar='|', quoting=csv.QUOTE_MINIMAL)
spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
| true |
37cbf698cc950483f420f012524cc14a2899aa99 | KaioPlandel/Estudos-Python-3 | /Exercicios/ex022.py | 331 | 4.15625 | 4 | #pergunte o nome. mostre o nome com as letras M e m, quantas letras tem tirando os espaços e quantas letras tem o primeiro nome.
nome = str(input('Digite no nome Completo: '))
print(nome.upper())
print(nome.lower())
print(len(nome.strip()) - nome.count(" "))
primeiroNome = nome.split()
nome1 = primeiroNome[0]
print(len(nome1))
| false |
62524c0e81216e623780e3d984cf16659ca8a0c7 | paulopradella/Introducao-a-Python-DIO | /Aula_8/Aula8_4.py | 1,218 | 4.40625 | 4 | #lambda (função anônima, é uma forma de simplificar algo que
# será utilizado mais de uma vez no código
#é mais eficiente com coisas que se resolve com uma linha,
#para coisa mais complexas não é bom
contador_letras = lambda lista:[len(x) for x in lista]
#vai fazer mesma coisa do outro contdor, masfica mais simples no código
lista_animais = ['cachorro', 'gato', 'elefante']
total_letras = contador_letras(lista_animais)
print(total_letras)
soma = lambda a, b: a + b
subtracao = lambda a, b: a - b
multiplicacao = lambda a, b: a * b
divisao = lambda a, b: a / b
print(soma(5, 10))
print(subtracao(5, 10))
print(multiplicacao(5, 10))
print(divisao(5, 10))
#criar um dicionário com lambda
calculadora = {
'soma': lambda a, b: a + b,
'subtracao': lambda a, b: a - b,
'multiplicacao': lambda a, b: a * b,
'divisao': lambda a, b: a / b
}
soma = calculadora['soma']
subtracao = calculadora['subtracao']
multiplicacao = calculadora['multiplicacao']
divisao = calculadora['divisao']
print('A soma é: {}'.format(soma(5, 10)))
print('A subtração é: {}'.format(subtracao(5, 10)))
print('A multiplicaçao é: {}'.format(multiplicacao(5, 10)))
print('A divisão é: {}'.format(divisao(5, 10)))
| false |
f083af9fb14cd1a9a7f0ee7902c9f2748f296a9e | IyappanSamiraj/Python-Basic- | /Given Number is Odd or Even.py | 304 | 4.3125 | 4 | #get the input
num=int(input())
#Condition is satisfied only the number is divisible by 2
if num%2==0:
print('Even')
#If else condition Is satisfied at if condition not satisfied
elif num<0:
print('Invalid')
#In if and elif Condition not satisfied Default else printed
else:
print('Odd')
| true |
96a0f98fde29054da4cb9c5665a93c6dd20e261c | Alexmallick/data-structures-HW | /class_practice.py | 420 | 4.125 | 4 | listofN=[7,5,4,1,9,0,3,-2,21,-6,13]
sortedList=sorted(listofN)
print(listofN)
print(sortedList)
print(listofN==sortedList)
def bubbleSort(list1):
for i in range(len(list1)-1):
for i in range(len(list1)-1):
first=list1[i]
second=list1[i+1]
if first>second:
swap=first
list1[i]=second
list1[i+1]=swap
return list1
| true |
73a2cadd00f7ac397ba553ac6f2c186f8fa7eb6d | richwan-git/shopee_competition | /OOP with python/Sample Code/demo - 13 (Example) - Try Except.py | 669 | 4.34375 | 4 | #==================================================================
# Try ... Except
#==================================================================
#=== simple use of try ... except ===
userInput = input("Please enter your birth year: ")
try:
birthYear = int(userInput)
print("Your age is: " + str(2018 - birthYear))
except:
print("You need to enter a number")
#=== Keep checking until a correct input is received ===
errFlag = True
while errFlag:
try:
birthYear = int(input("Please enter your birth year: "))
errFlag = False
except:
print("You must enter an integer")
print("Your age is " + str(2017 - birthYear))
| true |
af0165fb2114d0d1c1f2e1a014ee4a6ab6373969 | profarav/python101 | /011_guessigngame.py | 395 | 4.21875 | 4 | import random
number = random.randint(1,10)
x = 1
guess = int(input("Try and guess my number between 1 and 10, you only have 3 chances:") )
while x < 3:
if guess == number:
print("Congrats you guessed the number in under 3 tries")
break
else:
guess = int(input("Try again!:"))
x = x + 1
if x >= 3:
print("Sorry you don't have any chances left")
| true |
56031f73479663e760d26ca1e80133099c05f72d | profarav/python101 | /008_calculator.py | 480 | 4.40625 | 4 | print("This is a calculator for 2 numbers and simple operators")
num1 = float(input("Enter your first number: "))
num2 = float(input("Enter your second number: "))
operator = str(input("Enter the operator you want to multiply them by ex. //, *, + , -, **: "))
if operator == "*":
print(num1*num2)
elif operator == "+":
print(num1+num2)
elif operator == "**":
print(num1**num2)
elif operator == "-":
print(num1-num2)
elif operator == "/":
print(num1/num2)
| true |
5d40a13e499c745df4803d211d2191cd35f7fc3d | rldonaway/MIDS-alg-ds | /python/scramble.py | 2,759 | 4.34375 | 4 | # Assignment 2, #1
#
# a. Given two messages, A and B, which have the same length, we can
# create a new message by taking the first character from A, then the first
# character from B, then the second character from A, then the second
# character from B, and so on. We’ll call this the interleave of A and B.
# For example, if A is the text “abcde” and B is the text “12345” the
# interleave of A and B is “a1b2c3d4e5”.
# Write a function, interleave(), that takes two strings of the same length
# and returns the interleave of the two.
# b. To make a message even harder to read, we can perform several
# interleaves in a row. Assume that the length of a message is a power of
# 2. We define the scramble of the message recursively as follows:
# 1. The scramble of a single character is just that character.
# 2. The scramble of a longer message is found by taking the scramble
# of the first half of the message and the scramble of the second half
# of the message, and interleaving them.
def interleave(msg_a, msg_b):
len_a = len(msg_a)
len_b = len(msg_b)
if len_a != len_b:
raise ValueError("messages are not the same length")
result = ""
for i in range(len_a):
result += msg_a[i]
result += msg_b[i]
return result
# print(interleave("abc", "123"))
def length_power_two(message):
msg_len = len(message)
power_of_two = 1;
while power_of_two < msg_len:
power_of_two = 2 * power_of_two
for i in range(msg_len, power_of_two):
message += "."
return message
# print(length_power_two(""))
# print(length_power_two("a"))
# print(length_power_two("ab"))
# print(length_power_two("abc"))
# print(length_power_two("abcd"))
# print(length_power_two("abcde"))
# print(length_power_two("abcdef"))
def scramble(message):
if len(message) < 1:
return message
return scramble_recur(length_power_two(message))
def scramble_recur(message):
msg_len = len(message)
if msg_len < 2:
return message
half_msg_len = msg_len // 2
first_half = message[:half_msg_len]
second_half = message[half_msg_len:]
return interleave(scramble_recur(first_half), scramble_recur(second_half))
# print(scramble(""))
# print(scramble("1"))
# print(scramble("12"))
# print(scramble("1234"))
# print(scramble("12345678"))
# print(scramble("hello"))
# print(scramble("Madam I'm Adam"))
def scramble_file():
file_to_scramble = open("input.txt", "r")
scrambled_file = open("output.txt", "w")
for line in file_to_scramble.readlines():
scrambled = scramble(line[:-1])
scrambled_file.write(scrambled + "\n")
scrambled_file.close()
file_to_scramble.close()
if __name__ == "__main__":
scramble_file() | true |
e12b19ad61770268bab58a2e8db244acc4faa3e4 | janash/sample_python_package | /molecool/molecule.py | 2,897 | 4.3125 | 4 | """
Functions for calculating molecule properties.
"""
import numpy as np
from .measure import calculate_distance
from .atom_data import atom_weights
def build_bond_list(coordinates, max_bond=1.5, min_bond=0):
"""Calculate bonds in a molecule base on a distance criteria.
The pairwise distance between atoms is computed. If it is in the range
`min_bond` to `max_bond`, the atoms are counted as bonded.
Parameters
----------
coordinates : array-like
The coordinates of the atoms.
max_bond : float (optional)
The maximum distance for two points to be considered bonded. The default
is 1.5
min_bond : float (optional)
The minimum distance for two points to be considered bonded. The default
is 0.
Returns
-------
bonds : dict
A dictionary where the keys are tuples of the bonded atom indices, and the
associated values are the bond length.
"""
if min_bond < 0:
raise ValueError("Bond length can not be less than zero.")
if len(coordinates) < 1:
raise ValueError("Bond list can not be calculated for coordinate length less than 1.")
# Find the bonds in a molecule
bonds = {}
num_atoms = len(coordinates)
for atom1 in range(num_atoms):
for atom2 in range(atom1, num_atoms):
distance = calculate_distance(coordinates[atom1], coordinates[atom2])
if distance > min_bond and distance < max_bond:
bonds[(atom1, atom2)] = distance
return bonds
def calculate_molecular_mass(symbols):
"""Calculate the mass of a molecule.
Parameters
----------
symbols : list
A list of elements.
Returns
-------
mass : float
The mass of the molecule
"""
mass = 0
for atom in symbols:
mass += atom_weights[atom]
return mass
# Using the atomic_weights dictionary, write a function which calculates the center of mass of a molecule.
def calculate_center_of_mass(symbols, coordinates):
"""Calculate the center of mass of a molecule.
The center of mass is weighted by each atom's weight.
Parameters
----------
symbols : list
A list of elements for the molecule
coordinates : np.ndarray
The coordinates of the molecule.
Returns
-------
center_of_mass: np.ndarray
The center of mass of the molecule.
Notes
-----
The center of mass is calculated with the formula
.. math:: \\vec{R}=\\frac{1}{M} \\sum_{i=1}^{n} m_{i}\\vec{r_{}i}
"""
total_mass = calculate_molecular_mass(symbols)
mass_array = np.zeros([len(symbols), 1])
for i in range(len(symbols)):
mass_array[i] = atom_weights[symbols[i]]
center_of_mass = sum(coordinates * mass_array) / total_mass
return center_of_mass
| true |
9010f5b77bebb403863220375a79f86ca8a81ae9 | fr42k/leetcode | /solutions/0110-balanced-binary-tree/balanced-binary-tree.py | 1,261 | 4.1875 | 4 | # Given a binary tree, determine if it is height-balanced.
#
# For this problem, a height-balanced binary tree is defined as:
#
#
# a binary tree in which the left and right subtrees of every node differ in height by no more than 1.
#
#
#
# Example 1:
#
#
# Input: root = [3,9,20,null,null,15,7]
# Output: true
#
#
# Example 2:
#
#
# Input: root = [1,2,2,3,3,null,null,4,4]
# Output: false
#
#
# Example 3:
#
#
# Input: root = []
# Output: true
#
#
#
# Constraints:
#
#
# The number of nodes in the tree is in the range [0, 5000].
# -104 <= Node.val <= 104
#
#
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
_, ans = self.dnb(root)
return ans
def dnb(self, root):
if not root:
return 0, True
l_depth, l_b = self.dnb(root.left)
if not l_b:
return l_depth + 1, False
r_depth, r_b = self.dnb(root.right)
depth = max(l_depth, r_depth) + 1
if not r_b:
return depth, False
return depth, abs(l_depth - r_depth) <= 1
| true |
ee30b9b5a0ccefe42b349fc0ad6b0768ec7c62b4 | fr42k/leetcode | /solutions/0733-flood-fill/flood-fill.py | 2,149 | 4.21875 | 4 | # An image is represented by an m x n integer grid image where image[i][j] represents the pixel value of the image.
#
# You are also given three integers sr, sc, and color. You should perform a flood fill on the image starting from the pixel image[sr][sc].
#
# To perform a flood fill, consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color), and so on. Replace the color of all of the aforementioned pixels with color.
#
# Return the modified image after performing the flood fill.
#
#
# Example 1:
#
#
# Input: image = [[1,1,1],[1,1,0],[1,0,1]], sr = 1, sc = 1, color = 2
# Output: [[2,2,2],[2,2,0],[2,0,1]]
# Explanation: From the center of the image with position (sr, sc) = (1, 1) (i.e., the red pixel), all pixels connected by a path of the same color as the starting pixel (i.e., the blue pixels) are colored with the new color.
# Note the bottom corner is not colored 2, because it is not 4-directionally connected to the starting pixel.
#
#
# Example 2:
#
#
# Input: image = [[0,0,0],[0,0,0]], sr = 0, sc = 0, color = 0
# Output: [[0,0,0],[0,0,0]]
# Explanation: The starting pixel is already colored 0, so no changes are made to the image.
#
#
#
# Constraints:
#
#
# m == image.length
# n == image[i].length
# 1 <= m, n <= 50
# 0 <= image[i][j], color < 216
# 0 <= sr < m
# 0 <= sc < n
#
#
class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
q = collections.deque([(sr, sc)])
old_c = image[sr][sc]
if old_c == color:
return image
d = [0, 1, 0, -1, 0]
while q:
(r, c) = q.popleft()
image[r][c] = color
for i in range(4):
next_r = r + d[i]
next_c = c + d[i + 1]
if next_r >= 0 and next_r < len(image) and next_c >= 0 and next_c < len(image[next_r]) and image[next_r][next_c] == old_c:
q.append((next_r, next_c))
return image
| true |
7677e00892b0bd72a82527f98d5e812ef7bafd85 | fr42k/leetcode | /solutions/1050-construct-binary-search-tree-from-preorder-traversal/construct-binary-search-tree-from-preorder-traversal.py | 1,529 | 4.1875 | 4 | # Return the root node of a binary search tree that matches the given preorder traversal.
#
# (Recall that a binary search tree is a binary tree where for every node, any descendant of node.left has a value < node.val, and any descendant of node.right has a value > node.val. Also recall that a preorder traversal displays the value of the node first, then traverses node.left, then traverses node.right.)
#
# It's guaranteed that for the given test cases there is always possible to find a binary search tree with the given requirements.
#
# Example 1:
#
#
# Input: [8,5,1,7,10,12]
# Output: [8,5,10,1,7,null,12]
#
#
#
#
# Constraints:
#
#
# 1 <= preorder.length <= 100
# 1 <= preorder[i] <= 10^8
# The values of preorder are distinct.
#
#
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def bstFromPreorder(self, preorder: List[int]) -> TreeNode:
if len(preorder) == 0:
return None
r = TreeNode(preorder[0])
stk = [r]
for x in preorder[1:]:
tmp = None
while len(stk) > 0 and stk[-1].val < x:
tmp = stk[-1]
stk = stk[:-1]
if tmp:
tmp.right = TreeNode(x)
stk.append(tmp.right)
else:
stk[-1].left = TreeNode(x)
stk.append(stk[-1].left)
return r
| true |
4055a59af5c1bb6ea6d1d828d17f3af82efd495e | fr42k/leetcode | /solutions/0101-symmetric-tree/symmetric-tree.py | 1,348 | 4.1875 | 4 | # Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
#
#
# Example 1:
#
#
# Input: root = [1,2,2,3,4,4,3]
# Output: true
#
#
# Example 2:
#
#
# Input: root = [1,2,2,null,3,null,3]
# Output: false
#
#
#
# Constraints:
#
#
# The number of nodes in the tree is in the range [1, 1000].
# -100 <= Node.val <= 100
#
#
#
# Follow up: Could you solve it both recursively and iteratively?
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSymmetric(self, root: Optional[TreeNode]) -> bool:
if not root:
return True
if not root.left and not root.right:
return True
if not root.left or not root.right:
return False
if root.left.val != root.right.val:
return False
return self.isSym(root.left.left, root.right.right) and self.isSym(root.left.right, root.right.left)
def isSym(self, p, q):
if not p and not q:
return True
if not p or not q:
return False
if p.val != q.val:
return False
return self.isSym(p.left, q.right) and self.isSym(p.right, q.left)
| true |
3406cfb54b39a1a4abba41814870ad0022fd88e8 | tommyso/uip-prog3-python | /Volumen.py | 2,300 | 4.28125 | 4 | from abc import abstractmethod
from math import pi
class Figura(object):
def __init__(self, radio, altura, volumen):
self.radio = radio
self.altura = float(altura)
self.volumen = float(volumen)
@abstractmethod
def tipo_figura(self):
pass
class Esfera(Figura):
def calcularVolumen(self):
self.radio = float(input("\nValor del radio de la esfera: "))
self.volumen = (4*pi*self.radio*self.radio)/3
print("El volumen de su esfera es de", str(self.volumen), "m^3")
def tipo_figura(self):
return 'esfera'
class Cilindro(Figura):
def calcularVolumen(self):
self.radio = float(input("\nValor del radio del cilindro: "))
self.altura = float(input("Valor de la altura del cilindro: "))
self.volumen = pi*self.radio*self.radio*self.altura
print("El volumen de su cilindro es de", str(self.volumen), "m^3")
def tipo_figura(self):
return 'cilindro'
class Cono(Figura):
def calcularVolumen(self):
self.radio = float(input("\nValor del radio del cono: "))
self.altura = float(input("Valor de la altura del cono: "))
self.volumen = (pi*self.radio*self.radio*self.altura)/3
print("El volumen de su cono es de", str(self.volumen), "m^3")
def tipo_figura(self):
return 'cono'
if __name__ == '__main__':
seguir = 's'
print("\tCalculación de Volumenes")
print("\nOpciones: Esfera, Cilindro, Cono")
while(seguir == 'S' or seguir == 's'):
esf = Esfera
cil = Cilindro
con = Cono
respuesta = input("Escriba el nombre de una figuras en las opciones para calcular su Volumen: ")
while respuesta not in ('esfera', 'cilindro', 'cono'):
print("\nFigura no reconocida.")
respuesta = input("Introduzca otra figura: ")
if respuesta.lower() == 'esfera':
esf.calcularVolumen(Esfera)
elif respuesta.lower() == 'cilindro':
cil.calcularVolumen(Cilindro)
elif respuesta.lower() == 'cono':
con.calcularVolumen(Cono)
seguir = str(input("\nPara otra figura: oprima S. Para terminar programa: oprima otra tecla."))
print("\n") | false |
f15f377208e9377344824c9efb5a15cda3a833fa | meaj/Project-Euler-Solutions | /Python/proj_euler_019.py | 1,052 | 4.3125 | 4 | """
This program finds the number of Sundays on the first of the month in the 20th century
By Kevin Moore
"""
lst_month_lengths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
def calculate(int_start_year, int_stop_year):
int_num_sundays = 0
int_num_days = 1 # start on day 1 since the year does not start on day 0
for year in range(int_start_year, int_stop_year):
for month in lst_month_lengths:
# Calculates total number of days passed
int_num_days += month
# Handles leap years
if year % 4 == 0 and month == 28:
# Handles century case
if year % 100 == 0 and year % 400 != 0:
int_num_days -= 1
int_num_days += 1
# If the number of days at this point in the calcluation evenly
# divides into 7,the first day of the month is a Sunday
if int_num_days % 7 == 0:
int_num_sundays += 1
return int_num_sundays
def main():
print(calculate(1901, 2000))
main() | false |
2ac5f9c8bdc863b6531809bd3e194d6ec761eb11 | meaj/Project-Euler-Solutions | /Python/proj_euler_007.py | 709 | 4.15625 | 4 | '''
This program finds the 10,001st prime number
By Kevin Moore
'''
from proj_euler_000 import is_prime
'''
Nth Prime Generation Function
This function will generate the nth prime by counting the number of primes generated until int_val is reached
'''
def generate_prime_n(int_val):
prime_count = 0
test_val = 1
# test numbers for primality until the int_val prime is encountered
while (prime_count < int_val):
# if a prime number is encountered, increase the prime count
if is_prime(test_val):
prime_count += 1
test_val += 1
return test_val - 1
def main():
val = 10001
print("The #" + str(val) + " prime is " + str(generate_prime_n(val)))
main() | true |
d5e3ce67d8ed38fc54cbc8152bca2acc630886f7 | zunayed/puzzles_data_structures_and_algorithms | /practice_problems_python/1.1_unqiue_char_string.py | 453 | 4.21875 | 4 | # Implement an algorithm to determine if a string has all
# unique characters. What if you cannot use additional data structures?
def has_unique_char(string):
"""
O(n) complexity where n is the length of the string
"""
found_items = []
for item in string:
if item in found_items:
return False
found_items.append(item)
return True
print has_unique_char('abcdef')
print has_unique_char('abcdefa')
| true |
0bf8bf2ecaf0d8be1f2529a1852dcc7e18c4b6d4 | Sene68/python_study | /basic_data_types/find_the_runner_up_score.py | 513 | 4.15625 | 4 | # Given the participants' score sheet for your University Sports Day, you are required to find the runner-up score.
# You are given n scores. Store them in a list and find the score of the runner-up.
def print_score(n,arr):
arr = sorted(arr, reverse=True)
rank1 = arr[0]
rank2 = False
for i in arr:
if(i < rank1 and rank2 == False):
rank1 = i
rank2 = True
print(rank1)
if __name__ == '__main__':
n = int(4)
arr = [1,-1,-2,-1]
print_score(n,arr) | true |
8cc0afcb95dc5a1b352790b579ce4556c9dbe1bf | EvgeniyBudaev/python_learn | /oop/abstract_class_and_ABC.py | 1,165 | 4.375 | 4 | from abc import ABC
from abc import abstractmethod
import math
class Shape(ABC):
def __init__(self):
super().__init__()
@abstractmethod # наследник такие методы обязан переопределить
def draw(self):
pass
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
#pass
print('calc perimeter')
def drag(self):
print('Basic dragging functionality')
# s = Shape() нельзя создать экземпляр класса
class Triangle(Shape):
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def draw(self):
print(f'Drawing triangle with sides={self.a}, {self.b}, {self.c}')
def area(self):
s = (self.a + self.b + self.c) / 2
return math.sqrt(s*(s - self.a) * (s - self.b) * (self.c))
def perimeter(self):
super().perimeter()
return self.a + self.b + self.c
def drag(self):
super().drag()
print('Additional actions')
t = Triangle(10, 10, 10)
print('perimeter: ', t.perimeter()) # calc perimeter \n 30
print(t.drag()) # Basic dragging functionality \n Additional actions
| false |
565a4fa04bebd90ed037c9c2dcdd155831619b24 | EvgeniyBudaev/python_learn | /base/nested_list/nested_list.py | 544 | 4.375 | 4 | # Вложенные списки
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(len(nested_list)) # длинна 3
print(len(nested_list[0])) # длинна первого списка равна 3
for inner_list in nested_list:
print(inner_list)
for inner_list in nested_list:
for number in inner_list:
print(number) # получили все элементы
result = [number for number in inner_list for inner_list in nested_list]
print(result)
[[print(number) for number in inner_list] for inner_list in nested_list] | false |
593d214c8dc2ebb21b386f3cf23cada52ac46aac | AbolfazlAslani/BTD_DTB | /BTD_DTB/main.py | 842 | 4.375 | 4 | from BTD import binary_to_decimal
from DTB import decimal_to_binary
cmd = ">"
user_input = input(f"If you want to convert binary to decimal please type in BTD \nand if you want to convert decimal to binary please type in DTB {cmd} ")
while user_input != "BTD" and user_input != "DTB":
print("don't forget to type in with uppercase and don't type anything else please try again options = <BTD> and <DTB>")
user_input = input(f"{cmd} ")
if user_input == "BTD" :
btd_input = input(f"Allright you want to convert binary to decimal\nplease type in your binary digits {cmd} ")
print(binary_to_decimal(btd_input))
elif user_input =="DTB" :
dtb_input = input(f"Allright you want to convert decimal to binary\nplease type in your decimal digits {cmd} ")
print("Your Answer is : ", decimal_to_binary(int(dtb_input))) | true |
4778eaab60622dc95ecddfd1019fc772abfb714d | AdriHilmie29/python_coding | /monthly_payment.py | 595 | 4.5625 | 5 | # A bank is charging 6% interest per year for a loan. Monthly payments will be made for a certain period of time. Calculate the monthly payment amount a person needs to pay by
# asking the user to enter the loan amount and time period.
interestRate = 1.06
initialLoan = input('Enter initial loan: RM')
initialLoan = int(initialLoan)
timePeriod = input('Enter time period (in months):')
timePeriod = int(timePeriod)
print(' ')
print('Interest rate: 6%')
monthlyPayment = initialLoan*interestRate/timePeriod
print('Monthly payment =', monthlyPayment)
print(' ')
input('Press ENTER to exit')
| true |
cb6fe681825fae19a402b412cfb36eb97ef07a55 | nnennandukwe/py_challenges | /prime_numbers.py | 482 | 4.21875 | 4 |
def is_prime():
#check if number is prime
#if prime, true
#if not prime, false
print("Let's find out if your number is prime!")
n = int(input("Give a positive integer: "))
if n == 1:
print("1 is not a prime number.")
print(is_prime())
elif n <= 0:
print("0 and negative numbers are not positive integers.")
print(is_prime())
elif n == "":
print("please provide a number.")
print(is_prime())
elif n % 2 == 0:
print("True")
else:
print("False")
is_prime() | true |
b9fecf8374f00e89e9eb332bef9adb61a2d7522a | marcus666-byte/marcus-pyhon | /bye.py | 227 | 4.125 | 4 | print ("Hello guys! How are you?")
print ("I am hungry!")
print ("5+6")
input ("What is your name")
radius =int(input("Please enter radius\n"))
pi=3.14
are_of_circle=pi * radius * radius
print("area of circle" , are_of_circle) | true |
bac0c6becc592634bd28520dddedef90c87d3d73 | omridaniel/Python-Maze-Solver | /maze_solver_main_python3.py | 1,578 | 4.40625 | 4 | '''
Programmer: Omri Daniel
Date: 11/11/2018
Desc: This program solves a maze of arbitrary size.
'''
from maze import*
import pygame
#---------------------------------------#
# Main Program #
#---------------------------------------#
while True:
fname = input("Enter filename: ")
if fname.isalpha: break
maze = load_maze(fname)
# generate random start and goal locations
Sx,Sy = pick_random_location(maze)
maze[Sy][Sx] = 'S'
Gx,Gy = pick_random_location(maze)
maze[Gy][Gx] = 'G'
print ('\nHere is the maze with start and goal locations:')
print_maze(maze)
# now, find the path from S to G
find_path(maze, Sx, Sy)
print ('\nHere is the maze with the path from start to goal:')
maze[Sy][Sx]='S'
print_maze(maze)
'''
Questions - answer the questions and add them as long strings in your Python file.
In order to demonstrate an understanding of this problem and solution, you should be able to answer the following questions:
1) What happens if instead of searching in the order North, East, South, West, FIND PATH searches North, South, East, West?
Doesnt matter depends where start and end are.
2) When FIND-PATH returns False, does that mean there is no path from the start to the goal?
There is always a path but returnng false means it is going the wrong way or trying to make an invalid move.
3) Can parts of the maze be searched by FIND-PATH more than once? How does the algorithm deal with this situation?
Yes once a dead end is reached it results in backtracking and goes back on the moves to research the possible options
''' | true |
ea24c30709fd4d837ea93fdcb7c10ed0efee65ce | SplashPORTO/Cybers3c | /Exercicio_5.py | 1,422 | 4.1875 | 4 | #!/usr/local/bin/python3.9.1
# Programa solicita duas letras por ordem alfabetica e retorna ai utilizador a letra do meio se não for impar
# Importar as Livrarias Python necessarias
import random, string # Importar para criar numeros aleatorios e trabalhar com strings
import pyfiglet #_ESPECIAL_ Importo um tipo de letra. Primeiro usei o pip3 para instalar este modulo
ascii_banner = pyfiglet.figlet_format("Pinto 5")
print (ascii_banner)
print ('')
###### Inicio do Exercico ######
# Colocar todos os carectares em Letras maiculas para ter só uma fonte.
caracteres = string.ascii_uppercase
# Pedimos ao utilizador duas leras e colocamos nas variaveis
l1 = input("Qual a sua primeira Letra? \n").upper()
l2 = input("Qual a segunda Letra? \n").upper()
# Damos feedback ao utilizador
print ("As letras escolhidas são: ", l1," ",l2 )
# Onde fazemos o cauculo da posição da letra
posi1 = caracteres.find(l1)
posi2 = caracteres.find(l2)
encontraLetra = (posi1 + posi2)/2
# Usamos o if para caso seja Par (maior que um) ou impar e damos informação ao utilizaodr
if posi1 > posi2:
encontraLetra = encontraLetra + 0.5
print ("A letra que fica mais a meio da primeira e segunda letra é: ", caracteres[int(encontraLetra)])
else:
print ("A letra que fica mais a meio da primeira e segunda letra é: ", caracteres[int(encontraLetra)])
| false |
48863ce930104a796a5a9ae3a3fe07c71d0dcfe5 | SplashPORTO/Cybers3c | /NunoPinto1.py | 1,383 | 4.3125 | 4 | #!/usr/local/bin/python3.9
#Declaro Variaveis que vou usar
a = 1
b = 2
# Cumprimento ao Professor
print ("\nOlá Professor \n Fabio\n")
#Numero do Exercico de aula
print("Exercicios da aula n.1")
#Operação Aritmética entre 2 variáveis tipo integer
print("Aritmética entre 2 variáveis: ")
print ('a = 1 \nb = 2 \n(a + b) =',(a + b))
print ('\n')
#Operação Relacional entre 2 variáveis tipo integer
print ("Relacional entre 2 variáveis: ")
print ('a = 1 \nb = 2 \n(a < b) =',(a < b))
print ('\n')
#Operação binaria entre 2 variáveis tipo integer
print ("Binario entre 2 variáveis do tipo inteiro: ")
c = (bin(a) + bin(b))
print ("a = 1 \nb = 2 \nBinario de (a + b) = ",(c))
print ("Binario de a and b = ", (bin(a|b)))
print ("Binario de 1 = ", (bin(1)))
print ("Binario de 2 = ", (bin(2)))
print ("Binario de 3 = ", (bin(3)))
print ('\n')
#Operação relacional 2 variáveis tipo integer
print ("Relacional entre a > b : ")
m = (a > b)
print (m)
print ('\n')
#Operação associação entre 2 variáveis
print ("Operacao associacao entre variaveis para retornar Verdadeiro ou Falso")
print ("\nValor guardados na lista")
lista = [10,20,30,40,50,60,70,80,90,100]
print (lista)
print ("\nValor escolhido 50 que tera retorno Verdadeiro")
ln = 50 in lista
print (ln)
print( "\nValor escolhido 200 que tera retorno Falso")
ln = 200 in lista
print (ln)
print ("\n")
| false |
422e0000f65739869dfa7b8c7b9d2900b2f77bb5 | nazlysabbour1/stats-toolkit-python | /src/classical/workout/categorical.py | 1,873 | 4.125 | 4 | """ Statistical tests for evaluating distribution of 1 or 2 categorical
variables with at least one having more than two levels
functions:
1. one_categorical_hypothesis
2. two_categorical_hypothesis
"""
import numpy as np
import scipy.stats
def one_categorical_hypothesis(counts: np.ndarray, nobs: np.ndarray) -> tuple:
"""Applying chi square test goodness of fit
Ho: the observed counts of the input groups follow population distribution
HA: the observed counts of groups do not follow population distribution
(not random pick form population)
Args:
counts (np.ndarray): input group observed counts
nobs (np.ndarray): input group total count
Returns:
tuple: chi square value, p value
"""
p_expected = sum(counts) / sum(nobs)
expected_counts = nobs * p_expected
chi_square = sum((counts-expected_counts)**2/expected_counts)
df = len(nobs) - 1
p_value = scipy.stats.chi2.sf(chi_square, df)
return chi_square, p_value
def two_categorical_hypothesis(observed: np.ndarray) -> tuple:
"""Applying chi square independence test to compare two variables
Ho: two variables are independent
Ha: two variables are dependent
Args:
observed (np.ndarray): 2d array the rows represent first variable
the columns represent second variable
Returns:
tuple: chi square value, p value
"""
nrow, ncol = observed.shape
row_totals = np.sum(observed, axis=1).reshape(nrow, 1)
column_totals = np.sum(observed, axis=0).reshape(ncol, 1)
total = np.sum(observed)
expected = column_totals.T * (row_totals/total)
print(expected.shape)
chi_square = np.sum((observed-expected)**2/expected)
df = (nrow - 1) * (ncol - 1)
p_value = scipy.stats.chi2.sf(chi_square, df)
return chi_square, p_value
| true |
83be76bd5f81a851391730bc8bcd7071eb2259ce | yusurov/python | /exercice2.py | 209 | 4.1875 | 4 | #!/usr/bin/env python
annee = int(input("type the year : "))
if (annee%4 == 0) and ( annee%100!=0 or annee%400==0 ):
print("c'est une annee bisextile")
else:
print("c'est une annee ne pas bisextile")
| false |
671f6c59a71f3fb961bc58539a50ff2d8c2fc676 | Nyamador/Algorithmspy | /more/algorithms.py | 1,789 | 4.1875 | 4 | #Linked list implementation in Python
# Sorting
# """
# 1. Bubble Sort
# 2. Insertion Sort
# 3. Selection Sort
# 4. Quick Sort
# 5. Merge Sort
# 6. Heap Sort
# """
# Search Algorithms
# 1 . Linear Search: """
# For unsorted and unordered small lists
# """
# 2. Binary Search
# LINEAR SEARCH
def linearSearch(values, target):
"""
LinearSearch algorithm..
Values = An array with all the values
Target = Value to be found in the algorithm
"""
for i in values:
if i == target:
print (f'{i}, Index:{values.index(i)}')
print("Not Found")
values = [2,3,23,1,4,12,4,2,9,288,283]
linearSearch(values, 12)
# BINARY SEARCH
# 1. Start at the middle element:
# 2. If the target value is equal to the middle element of the array then return the index of the element
# 3. If target value is greater than middle element , pick the elements to the right and start with step 1
# 4. If target value is less than middle element , pick the elements to the left and start with step 1
# 5. When the item is found return the index of the matched element
# 6. If no match return not found/ -1
def binarySearch(values, target, length):
"""
Binary: List to be searched
Target: Search Term
len: The number of elements in the list
"""
max = (length - 1)
min = 0
step = 0
for number in values:
while max >= min :
center = (max + min ) / 2
# step = 0
step += 1
if values[center] == target:
print(values[center])
# return step
elif values[center] > target:
max = (center - 1)
min = (center + 1 )
listt = [1,3,5,7,9,2,39,33,2]
size = len(listt)
binarySearch(listt, 39, size) | true |
9306bc2f534a7e1236ddec4fb09317fde59ac9dc | johnwanjema/python | /expandtabs.py | 854 | 4.34375 | 4 | # Sometimes, there is a need of specifying the space in the string, but the amount of space to be left
# is uncertain and depending upon the environment and conditions. For these cases, the need to modify
# the string, again and again, is a tedious task. Hence python in its library
# has “expandtabs()” which specifies the amount of space to be substituted with the “\t” symbol in the string.
# initializing string
str = "i\tlove\tgfg"
# using expandtabs to insert spacing
print("Modified string using default spacing: ", end ="")
print(str.expandtabs())
print("\r")
# using expandtabs to insert spacing
print("Modified string using less spacing: ", end ="")
print(str.expandtabs(2))
print("\r")
# using expandtabs to insert spacing
print("Modified string using more spacing: ", end ="")
print(str.expandtabs(12))
print("\r") | true |
2f9e50e5fa6cbed1ace9e77de70bf9c4d266ce28 | billcod3r/PythonAutomationCourse | /python_insiders/upload_widget.py | 245 | 4.1875 | 4 | text = "Hello How are you doing?"
text_split = text.split()
for word in text_split:
for letter in word:
print(letter)
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = 0
print(thisdict)
| true |
4798634605a01c0f078d144f0c3b1413ba0ff5eb | alexdcodes/Python_SelfEducation | /printing.py | 1,580 | 4.5625 | 5 | from math import sqrt
print ("Hello world\n\n")
print sqrt(10)
name = raw_input("What is your name? ")
print "Hello, " + name + "!"
print "\nPython Scripts for testing\n\n"
x = "Hello"
y = "World"
print (y, x)
temp = "42"
print "The temperature is " + temp
print '''\n THIS IS A JUST A TESTING APPLICATION FOR EDUCATION NOTHING MORE, .
.. EXAMPLE OF A VERY LONG STRING PROGRAM IN PYTHON'''
months = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
"October",
"November",
]
years = [
"1979",
"1980",
"1981",
"1982",
"1983",
"1984",
"1985",
"1986",
"1987",
"1988",
"1989",
"1990",
"1991",
"1992",
"1993",
"1994",
"1995",
"1996",
"1997",
]
endings = ['st', 'nd', 'rd'] + 17 * ['th'] \
+ ['st', 'nd', 'rd'] + 7 * ['th'] \
+ ['st']
year = raw_input('Year: ')
month = raw_input('Month (1-12): ')
day = raw_input('Day (1-31): ')
month_number = int(month)
day_number = int(day)
# Remember to subtract 1 from month and day to get the correcet index
month_name = months[month_number-1]
ordinal = day + endings[day_number-1]
print month_name + ' ' + ordinal + ', ' + year
print "\n\nContinue to domain names\n\n"
# Now to Split up a URL in the form of http://www.something.com
url = raw_input("Please enter the URL: ")
domain = url[11:-4]
# Continue to the actual Split
print "Domain name: " + domain
raw_input("\nPress <enter> to end application")
| false |
a4946e9294bac3a266cd23f148e8e7c41e9107c8 | alexdcodes/Python_SelfEducation | /listing2-3.py | 664 | 4.15625 | 4 | # Prints a sentence in centered "box" correct width
# Note that the integer division operator (//) only works in Python
# 2.2 and newer. In earlier versions, simply use plain divsion (/) to correct mistakes or alternate.
sentence = raw_input("Sentence: ")
screen_width = 80
text_width = len(sentence)
box_width = text_width + 6
left_margin = (screen_width - box_width) / 2
print
print '' * left_margin + '+' + '-' * (box_width-2) + '+'
print '' * left_margin + '| '+ ' ' * text_width + '|'
print '' * left_margin + '| ' + sentence + '|'
print '' * left_margin + '| '+ ' ' * text_width + '|'
print '' * left_margin + '+' + '-' * (box_width-2) + '+'
print
| true |
c9fbe6b04213932badd51e38072d633a385fe9d5 | don-k-jacob/hacktoberfest2021 | /calculator.py | 929 | 4.1875 | 4 | #Defining function for addition.
def add(x, y):
return x + y
#Defining function for substraction.
def subtract(x, y):
return x - y
#Defining function for multiplication.
def multiply(x, y):
return x * y
#Defining function for division.
def divide(x, y):
return x / y
def start():
print("""Select Operation.
1.Add
2.Subtract
3.Multiply
4.Divide""")
choice = input("Select Number(1/2/3/4): ")
num1 = int(input("Input First Number: "))
num2 = int(input("Input Second Number: "))
#Knowing which operation to perform.
if choice == '2':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == '1':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == '4':
print(num1,"/",num2,"=", divide(num1,num2))
elif choice == '3':
print(num1,"*",num2,"=", multiply(num1,num2))
else:
print("Wrong Input")
if __name__ == '__main__':
start()
| false |
a114de7b447f890ef76c075de4b72aee4ea07bc0 | TGITS/programming-workouts | /python/misc/learning_python/using_enumerate.py | 1,646 | 4.65625 | 5 | letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
print('letters {}'.format(letters))
print('\n##########\n')
print('In Python, the for is a foreach : ')
for letter in letters:
print(letter)
print('\n##########\n')
# Naive approach to emulate a C-like for loop in Python
print('Naive approach to access both index of element in the list and the associated value : ')
for index in range(len(letters)):
print('letters[{}] : {}'.format(index, letters[index]))
print('\n##########\n')
# For loop with enumerate
print('using enumerate in a for loop : ')
for index, value in enumerate(letters):
print('letters[{}] : {}'.format(index, value))
print('\n##########\n')
# For comprehension with enumerate
print('using enumerate in a for comprehension : ')
list_to_print = ['letters[{}] : {}'.format(
index, value) for index, value in enumerate(letters)]
print('\n'.join(list_to_print))
print('\n##########\n')
# For loop with enumerate, ignoring the value
print('using enumerate in a for loop and ignoring the value : ')
for index, _ in enumerate(letters):
print('index of letter :', index)
print('\n##########\n')
# Creating a list of tuples from enumerate
print('Creating a list of tuples (index, value) from a list of values')
letters_with_index = list(enumerate(letters))
print(letters_with_index)
print('\n##########\n')
# enumerate works with tuple, string and set for example
print('enumerate with tuple : ')
print(list(enumerate(('a', 'e', 'i', 'o', 'u'))))
print('enumerate with string : ')
print(list(enumerate(('aeiou'))))
print('enumerate with set : ')
print(list(enumerate({'a', 'e', 'i', 'o', 'u', 'a', 'e'})))
| true |
f1134a04fd366402bef057753a0db067e89aed02 | TGITS/programming-workouts | /python/misc/turtle/spirals.py | 596 | 4.4375 | 4 | # importing turtle
import turtle
# initialise the turtle instance
animation = turtle.Turtle()
#creating animation
# changes speed of turtle
animation.speed(0)
# hiding turtle
animation.hideturtle()
# changing background color
animation.getscreen().bgcolor("black")
# color of the animation
animation.color("red")
for i in range(100):
# drawing circle using circle function
# by passing radius i
animation.circle(i)
# changing turtle face by 5 degree from it's
# previous position after drawing a circle
animation._rotate(5) | true |
74f19b13e9da44ca09bd9a7aa8718f34ddb79755 | TGITS/programming-workouts | /python/codingame/practice/easy/carmichael_number/carmichael_number.py | 2,741 | 4.15625 | 4 | import sys
import math
# You might know Fermat’s small theorem:
# If n is prime, then for any integer a, we have a^n ≡ a mod n,
# that means that a^n and a have the same r in the euclidian division by n.
# There are numbers, called Carmichael numbers, that are not prime but for which the equality remains true for any integer a.
# For example, 561 is a Carmichael numbers because for any integer a, a^561 ≡ a mod 561. It’s in fact the smallest Carmichael number.
# You have to tell if the given number is a Carmichael number or not. Beware, you might be given a prime number.
# Input
# A single number n.
# Output
# YES if n is a Carmichael number, or NO if it’s not.
# Informations complémentaires trouvées trouvé sur Wikipedia (https://fr.wikipedia.org/wiki/Nombre_de_Carmichael)
# # Tout nombre de Carmichael est impair et ne peux pas être un nombre premier
# testing if a^n and a have the same remainder in the euclidian division by n
# this is (a**n) % n == (a % n)
# pour tout entier a premier avec n, n est un diviseur de a^(n-1) - 1
# a premier avec n, signifie que le pgcd de n et de a est 1
# Auto-generated code below aims at helping you parse
# the standard input according to the problem statement.
def is_prime(n):
for i in range(2,int(math.ceil(math.sqrt(n)))):
if n % i == 0:
return False
return True
def pgcd(a,b):
r = a % b
while r != 0 :
a = b
b = r
r = a % b
return r
def is_carmichael_number(n):
# Informations complémentaires trouvées trouvé sur Wikipedia (https://fr.wikipedia.org/wiki/Nombre_de_Carmichael)
# Tout nombre de Carmichael est impair et ne peux pas être un nombre premier
if is_prime(n) or n % 2 == 0:
return False
else:
# testing if a^n and a have the same remainder in the euclidian division by n
# this is (a**n) % n == (a % n)
# pour tout entier a premier avec n, n est un diviseur de a^(n-1) - 1
# a premier avec n, signifie que le pgcd de n et de a est 1
a = 2
n_minus_one = n-1
while a < n :
# Test n et a premier entre eux
# De plus est-ce que n est un diviseur de a^(n-1) - 1
# Si premier entre eux et n n'est pas un diviseur de a^(n-1) - 1, nous n'avons pas un nombre de Carmichael
if pgcd(n,a) == 1 and (a**(n_minus_one) - 1) % n != 0:
return False
a += 1
#If we arrive here, we have a Carmichael number
return True
if __name__ == "__main__":
n = int(input())
answer = "YES" if is_carmichael_number(n) else "NO"
# Write an action using print
# To debug: print("Debug messages...", file=sys.stderr)
print(answer) | true |
9b67ab1893fe832a532c4078f5590683a0c5f969 | TGITS/programming-workouts | /python/misc/turtle/chessboard.py | 1,200 | 4.3125 | 4 | # import turtle package
import turtle
# create screen object
sc = turtle.Screen()
# create turtle object
pen = turtle.Turtle()
# method to draw square
def draw():
for i in range(4):
pen.forward(30)
pen.left(90)
pen.forward(30)
# Driver Code
if __name__ == "__main__" :
# set screen
sc.setup(600, 600)
# set turtle object speed
pen.speed(100)
# loops for board
for i in range(8):
# not ready to draw
pen.up()
# set position for every row
pen.setpos(0, 30 * i)
# ready to draw
pen.down()
# row
for j in range(8):
# conditions for alternative color
if (i + j)% 2 == 0:
col ='black'
else:
col ='white'
# fill with given color
pen.fillcolor(col)
# start filling with colour
pen.begin_fill()
# call method
draw()
# stop filling
pen.end_fill()
# hide the turtle
pen.hideturtle()
# This code is contributed by Deepanshu Rustagi. | true |
ef22bbba54dab9afe0bf06462ad8a96827499170 | vadymshturkhal/Reusable | /Python/2_loops_range_not_even.py | 470 | 4.1875 | 4 | # Реализуйте функцию rangeOdd(start: number, end: number):
# array которая отдает массив нечетных чисел из диапазона [15, 30] включая крайние числа.
def function_return_not_even_numbers() -> list:
# With list comprehension
return [number for number in range(15, 31) if number % 2 != 0]
if __name__ == '__main__':
result = function_return_not_even_numbers()
print(result)
| false |
99aa1e56e5e7f8d0f2490c3b944af731196571b6 | weerachaiy/pythonita-1 | /intro_compu_book/root_pwr.py | 680 | 4.40625 | 4 | '''
“Finger exercise: Write a program that asks the user to enter an integer and prints two integers, root and pwr, such that 0 < pwr < 6 and root**pwr is equal to the integer entered by the user. If no such pair of integers exists, it should print a message to that effect.”
Fragmento de: John V. Guttag. “Introduction to Computation and Programming Using Python: With Application to Understanding Data (MIT Press)”. Apple Books.
'''
# Asking the user for an integer
# root =
# root = None
# pwr = None
# user_int = int(input('Enter an integer: '))
# if 0 < pwr and pwt < 6
# print(root, pwr)
total = 0
for c in '123,45678':
total = int(c)
print(total)
| true |
cfe3a018b2d85d94ebe84ec14e4e3ebb9cc5f58b | weerachaiy/pythonita-1 | /pyw_palindromo.py | 1,811 | 4.375 | 4 | # Desarrollar un programa el cual nos permita conocer si un string es, o no un palíndromo.
# Un palíndromo es una palabra, o frase que se lee igual de izquierda a derecha que de derecha a izquierda
# El programa debe cumplir con los siguiente requerimientos.
# El programa debe poseer una función llamada palíndromo.
# La función debe poseer como parámetro la variable sentencia.
# La función debe retornar verdadero o falso dependiendo si el parámetro es, o no, un palíndromo.
# Ejemplos
# >>> palindromo('anitalavalatina')
# True
# >>> palindromo('sometamosomatemos')
# True
# >>> palindromo('superpalindromo')
# False
# Ayuda: No es necesario validar, mayusculas, minúsculas, números o espacios.
# Restricciones:
# No es posible implementar ningún método para un
# No es posible importar absolutamente nada.
# def palindromo(sentencia):
# sentencia = sentencia.strip()
# sentencia = sentencia.replace(" ", "")
# sentencia = sentencia.lower()
# sentencia_reves = sentencia[::-1]
# if sentencia == sentencia_reves:
# return True
# else:
# return False
# if __name__ == "__main__":
# sentencia = input("Escribe una frase: ")
# es_palindromo = palindromo(sentencia)
# print(es_palindromo)
def palindromo(sentencia):
sentencia_reves = sentencia[::-1]
if sentencia == sentencia_reves:
return True
else:
return False
if __name__ == "__main__":
sentencia = input("Escribe una frase: ")
es_palindromo = palindromo(sentencia)
print(es_palindromo)
# Resultado de Pywombat
# def palindromo(sentencia):
# longitud = len(sentencia)
# for pos in range(0, longitud // 2):
# if sentencia[pos] != sentencia[ ((pos - longitud) * - 1) - 1 ]:
# return False
# return True
| false |
482308859c1ded0705aefd56afffd7834e5f8782 | weerachaiy/pythonita-1 | /Practice_Python/less_than_ten_3.py | 885 | 4.40625 | 4 | """Take a list, say for example this one:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
and write a program that prints out all the elements of the list that are less than 5.
Extras:
Instead of printing the elements one by one, make a new list that has all the elements less than 5 from this list in it and print out this new list.
Write this in one line of Python.
Ask the user for a number and return a list that contains only elements from the original list a that are smaller than that number given by the user."""
def less_than(any_list, user_number):
which_less = [i for i in any_list if i < 5]
print(which_less)
which_user = [i for i in any_list if i < user_number]
print(which_user)
if __name__ == '__main__':
any_list = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
user_number = int(input('Enter a number: '))
less_than(any_list, user_number) | true |
8753363fd2989f9cf0c782d9be5042edd13558ba | weerachaiy/pythonita-1 | /Practice_Python/character_input_1.py | 1,041 | 4.3125 | 4 | """Create a program that asks the user to enter their name and their age. Print out a message addressed to them that tells them the year that they will turn 100 years old.
Extras:
Add on to the previous program by asking the user for another number and printing out that many copies of the previous message. (Hint: order of operations exists in Python)
Print out that many copies of the previous message on separate lines. (Hint: the string "\n is the same as pressing the ENTER button)"""
year = 2021
def ask_user():
user_name = input("what's your name?: ")
user_age = int(input("How old are you?: "))
user_year_born = year - user_age
return (f'\nHello {user_name}, you will turn 100 years old by {user_year_born + 100}')
def user_number():
user_repeat_choise = int(input("Give me a number from 1 to 10: "))
return user_repeat_choise
if __name__ == '__main__':
one_hundred = ask_user()
print(one_hundred)
repeat_num = user_number()
print(repeat_num)
print(f'{one_hundred * repeat_num}')
| true |
7c89b585ee75052519067998a3c00d7347b77dc7 | weerachaiy/pythonita-1 | /codewars/replace_alph.py | 1,624 | 4.28125 | 4 | '''
In this kata you are required to, given a string, replace every letter with its position in the alphabet.
If anything in the text isn't a letter, ignore it and don't return it.
"a" = 1, "b" = 2, etc.
Example
alphabet_position("The sunset sets at twelve o' clock.")
Should return "20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11" (as a string)
'''
# Set a list with the alphabet to have a base to compare
signs = [' ', '!', '"', '·', '·', '·', '$', "'", '%', '&', '/', '(', ')', '=', '?', '¿', '.', ',', ';', ':']
alphabet = ['a', 'b', 'c', 'd', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z',]
alphabet_lenght = len(alphabet)
print(alphabet_lenght)
# Create a function that sort the input sentece, compare the string with the base to obtain the number for each letter.
def alphabet_position(sentence):
print(sentence)
sentence_lower = sentence.lower()
take_out_spaces = sentence_lower.strip()
sentence_without_spaces = take_out_spaces.replace(' ','')
print(sentence_without_spaces)
for char in sentence_without_spaces:
for sign in signs:
if char == sign:
char = char.replace(char, '')
char_list = []
char_list = char_list.append(char)
print(char)
# char_in_sentence = []
# char_in_sentence = char_in_sentence.append(char)
# print(char_in_sentence)
if __name__ == "__main__":
sentence = "The sunset sets at twelve o' clock."
alphabet_position(sentence) | true |
921b97caca2f09bc877067dcb447d6070f70f992 | chymoltaji/Algorithms | /Sorting Algos/bubbleSort.py | 515 | 4.28125 | 4 | def bubbleSort(array):
n = len(array)
edit = False
for i in range(1,n):
if array[i]<array[i-1]:
array[i], array[i-1] = array[i-1], array[i]
edit = True
if edit == True:
bubbleSort(array)
return array
arr = [0, 2, 15, 2017, 1, 1, 17, 3, 7, 1, 2, 3, 9, 22]
correct = [0, 1, 1, 1, 2, 2, 3, 3, 7, 9, 15, 17, 22, 2017]
result = bubbleSort(arr)
if result == correct:
print(f"CORRECT: Sorted to\t{result}")
else:
print(f"INCORRECT: Sorted to\t{result}") | false |
358073b97e8b916b0cae5094ab2eff817e5fb0ee | chymoltaji/Algorithms | /Sorting Algos/SelectionSort.py | 514 | 4.21875 | 4 | def selection_sort(array):
n = len(array)
for i in range(n):
min_index = i
for j in range(i+1, n):
if array[j] < array[min_index]:
min_index = j
array[i], array[min_index] = array[min_index], array[i]
return array
arr = [13, 15, 2017, 17, 3, 7, 1, 2, 9, 22]
correct = [1, 2, 3, 7, 9, 13, 15, 17, 22, 2017]
result = selection_sort(arr)
if result == correct:
print(f"CORRECT: Sorted to {result}")
else:
print(f"INCORRECT: Sorted to {result}") | false |
4cb8b149ba6311bae5175e5a182a27789936b4d4 | chymoltaji/Algorithms | /MonotonicArray.py | 692 | 4.3125 | 4 | # Given an array of integers, determine whether the array is monotonic or not.
A = [6, 5, 4, 4]
B = [1, 1, 1, 3, 3, 4, 3, 2, 4, 2]
C = [1, 1, 2, 3, 7]
D = [2, 5, 1, 7, 9, 1, 4]
test_list = [A, B, C, D]
def isMonotonic(array):
increasing = 0
decreasing = 0
for i in range(len(array)-1):
if array[i] < array[i+1]:
increasing += 1
elif array[i] > array[i+1]:
decreasing += 1
if increasing == 0:
print("True \t |decreasing")
elif decreasing == 0:
print("True \t |increasing")
else:
print("False \t |not monotonic")
# print(increasing, decreasing)
for test in test_list:
isMonotonic(test) | true |
209a31ee3cfd4b301d110c00fa4e611ae4a528f2 | fahimkk/anandology | /reverse.py | 543 | 4.625 | 5 | # Write a program reverse.py to print lines of a file in reverse order
import sys
def reverse_txt(filename):
f = open(filename,'r')
f_list = f.readlines()
for line_num in range(len(f_list)-1,-1,-1):
print(f_list[line_num].strip('\n'))
f.close()
if __name__ == "__main__":
args = sys.argv
if len(args) < 2:
print('Usage: python filename.py filemane.txt')
elif len(args) > 2:
print('Usage: python filename.py filemane.txt')
else:
filename = args[1]
reverse_txt(filename) | true |
12157328165e762521def92fca9047bd127c5f80 | ConorSheehan1/ctci | /conor/Python/string_and_arrays/1_6_rotate_matrix.py | 367 | 4.15625 | 4 | from copy import deepcopy
def rotate90(m):
temp = deepcopy(m)
# iterate over rows
col = len(m)-1
for row in m:
for i in range(len(row)):
temp[i][col] = row[i]
col -= 1
return temp
if __name__ == "__main__":
arr = [[i for i in range(j, j+3)] for j in range(0, 9, 3)]
print(arr)
print(rotate90(arr))
| false |
63bb4f63fb3bbe57dffe4241c2404e8918ffe01f | aplcido/Machine-Learning | /Machine-Learning/numpy_arrays.py | 1,822 | 4.34375 | 4 | """Creating NumPy arrays."""
import numpy as np
def test_run():
#list to 1D array
#print (np.array([2,3,4]))
#list to 2D array
#print (np.array([(2,3,4),(5,6,7)]))
#empty array
#print np.empty(5)
#empty matrix
#print (np.empty((5,4)))
#matrix of 1s
#print (np.ones((5,4)))
#specifying datatype (int) of matrix of 1s
#print (np.ones((5,4), dtype=np.int_))
#generate an array full of random numbers, uniformly sampled from [0.0,1.0]
#print (np.random.random((5,4)))
#sample numbers from a Gaussian (normal) distribution
print (np.random.normal(size=(2,3)))
print (np.random.normal(50,10,size=(2,3))) #change mean to 50 and standard deviation to 10
#random numbers
print (np.random.randint(0,10, size=5)) #5 random numbers between 0 and 10
print (np.random.randint(0,10, size=(2,3))) #2x3 size matrix with random numbers between 0 and 10
a = np.random.random((5,4))
print (a.shape)
print (a.shape[0]) #number of rows
print (a.shape[1]) #number of columns
print (a.size) #number of elements in array/matrix
np.random.seed(693) #seed the random number generator
a = np.random.randint(0,10, size=(5,4))
print ("Array:\n",a)
#sum of all elements
print("Sum of all elements:",a.sum())
#iterate over rows, to compute sum of each column
print("Sum of each column:",a.sum(axis=0))
#iterate over columns, to compute sum of each row
print("Sum of each row:",a.sum(axis=1))
#Statistics: min, max, mean (across rows,cols and overall)
print("Minimum of each column:",a.min(axis=0))
print("Maximum of each row:",a.max(axis=1))
print("Mean of all elements:",a.mean())
if __name__ == "__main__":
test_run() | true |
d3a46790f41ba4f24b0f5c52af004998e328cd68 | Mateus-Silva11/AulasPython | /Aula_6/Aula6(lista).py | 835 | 4.375 | 4 | # Aula 6 [Listas,vetores]
#conhecito de lista pode usar qualquer tipo de dados esse conjuto de dados dentro de uma unica variavel
#listas
#inicialização de uma variel do tipo lista
lista1 = []
#inicialização de uma variel lista, com elementos
lista2 = ['Marcela', 'Nicole','*Matheus']
#lista de inteiros
lista3 = [1,2,3,5]
#lista de tipos diferestes.
lista4 =[1, 'Mateus', 23.5]
#Impressao das listas criadas
print(lista1)
print(lista2)
print(lista3)
print(lista4)
# ---- Adicionando elementeos em uma lista ja criada
lista1.append(lista2)
lista1.append(lista3)
# Criação de lista com dados vindos da função Input
lista_duvida = [input('aaaaa'), input('sdsdsdsdsdss')]
print(lista_duvida)
#Recuperando um dado de uma posição especifica da lista
posicao = int(input('Digite a posicao'))
print(lista2[posicao-1])
| false |
8d83fc9ae33730e716eee8cc63b9746e32bcaff9 | dgoldsb/advent-of-code-2018 | /day-0/problem_0.py | 2,017 | 4.21875 | 4 | """
After feeling like you've been falling for a few minutes, you look at the device's tiny screen. "Error: Device must be calibrated before first use. Frequency drift detected. Cannot maintain destination lock." Below the message, the device shows a sequence of changes in frequency (your puzzle input). A value like +6 means the current frequency increases by 6; a value like -3 means the current frequency decreases by 3.
For example, if the device displays frequency changes of +1, -2, +3, +1, then starting from a frequency of zero, the following changes would occur:
Current frequency 0, change of +1; resulting frequency 1.
Current frequency 1, change of -2; resulting frequency -1.
Current frequency -1, change of +3; resulting frequency 2.
Current frequency 2, change of +1; resulting frequency 3.
In this example, the resulting frequency is 3.
Here are other example situations:
+1, +1, +1 results in 3
+1, +1, -2 results in 0
-1, -2, -3 results in -6
Starting with a frequency of zero, what is the resulting frequency after all of the changes in frequency have been applied?
--- Part Two ---
You notice that the device repeats the same frequency change list over and over. To calibrate the device, you need to find the first frequency it reaches twice.
What is the first frequency your device reaches twice?
"""
if __name__=='__main__':
# Part 1.
values = []
with open('input', 'r') as file:
for row in file:
values.append(int(row))
print('Answer 1 is {}'.format(sum(values)))
iterations = 0
total = 0
visited_values = set()
visited_values.add(total)
found = False
while not found:
for value in values:
total += value
if total in visited_values:
print('Answer 2 is {}'.format(total))
found = True
break
visited_values.add(total)
iterations += 1
print('{} iterations done'.format(iterations))
| true |
ceb7d4240edbb13c14da53255c107a0934c1ddcf | baubrun/Challenges-PY | /Challenges/stripping_sentence.py | 1,058 | 4.5 | 4 | """
/*
Stripping a Sentence Down
Create a function which takes in a sentence str and a string
of characters chars and return the sentence but with all the specified characters removed.
Examples
strip_sentence("the quick brown fox jumps over the lazy dog", "aeiou")
➞ "th qck brwn fx jmps vr th lzy dg"
strip_sentence(
"the hissing snakes sinisterly slither across the rustling leaves", "s")
➞ "the hiing nake initerly lither acro the rutling leave"
strip_sentence("gone, reduced to atoms", "go, muscat nerd") ➞ ""
Notes
You may be asked to remove punctuation and spaces.
Return an empty string if every character is specified (see example #3).
All tests will be in lowercase.
*/
"""
import re
def strip_sentence(s, chars):
regex = f"[{chars}]"
copy = re.sub(regex, "", s)
return copy
print(strip_sentence("the quick brown fox jumps over the lazy dog", "aeiou"))
print(strip_sentence("the hissing snakes sinisterly slither across the rustling leaves", "s"))
print(strip_sentence("gone, reduced to atoms", "go, muscat nerd"))
| true |
0fdb023e56e3ddfbc8f470eff49aa641f1b0cf87 | baubrun/Challenges-PY | /Challenges/increment_to_top.py | 828 | 4.21875 | 4 | """
Create a function that returns the total number of steps
it takes to transform each element to the maximal element in the array.
Each step consists of incrementing a digit by one.
Examples
increment_to_top([3, 4, 5]) ➞ 3
// 3 increments: 3 -> 4, 4 -> 5; 4 -> 5
increment_to_top([4, 3, 4]) ➞ 1
increment_to_top([3, 3, 3]) ➞ 0
increment_to_top([3, 10, 3]) ➞ 14
Notes
If the array contains only the Same digits, return 0 (see example #2).
Bonus: Can you write a solution that achieves
this by only traversing the array once?
(i.e. without finding the max before hand)
"""
def increment_to_top(arr):
s = 0
for i in arr:
s += max(arr) - i
return s
print(increment_to_top([3, 4, 5]))
print(increment_to_top([4, 3, 4]))
print(increment_to_top([3, 3, 3]))
print(increment_to_top([3, 10, 3])) | true |
95acc7ef0870bada4a4615b57f686581b6e4ec68 | baubrun/Challenges-PY | /Challenges/snake_area_filling/snake_fill.py | 1,093 | 4.4375 | 4 | """
Assuming that you know the popular game "Snake", you have an area of x*x, the snake length is
1 (only the head) and is positioned in the top left corner of the
area at the beginning which means
if your area is 7*7 it will look something like this:
Knowing that each time the snake eats the food his length will be 2
times longer (so if the length of the snake is 4, after eating it will be 8),
you have to create a function that takes a number as an argument and
returns how many times the snake needs to eat to fill the entire area.
Examples
snakefill(3) ➞ 3
snakefill(6) ➞ 5
snakefill(24) ➞ 9
Notes
The argument is the length of a side of the area which
mean that if the given number is 6 your area will be of 6*6.
The snake can exceed the borders
The given number can't be a float.
The given number is always positive.
"""
def snake_fill(x):
if x == 1:
return 0
d = x * x
size = 1
count = 0
for _ in range(2, d):
if size > d:
return count - 1
else:
size *= 2
count += 1
return count
| true |
687065d62e1fab03ba659bba3eeccb0da2a22ebd | baubrun/Challenges-PY | /Challenges/fog.py | 794 | 4.25 | 4 | """
/*
Clear the Fog
Create a function which returns the word in the string,
but with all the fog letters removed.
However, if the string is clear from fog, return "It's a clear day!".
Examples
clearFog("sky") ➞ "It's a clear day!"
clearFog("fogfogfffoooofftreesggfoogfog") ➞ "trees"
clearFog("fogFogFogffffooobirdsandthebeesGGGfogFog") ➞ "birdsandthebees"
Notes
There won't be any fog inside of any of the actual words
(won't include the letters f, o or g).
Hidden words are always in lowercase.
*/
"""
import re
def clear_fog(string):
good_string = re.search("[fog]", string)
s = "".join(re.findall("[^fog]", string))
return s if good_string is not None else "It's a clear day!"
# ans = clear_fog("fogfogfffoooofftreesggfoogfog")
ans = clear_fog("a")
print(ans)
| true |
376da000f106e64474e3aa1813cb9212c373f6af | wikislate/python-wiki | /dictionary-keyError.py | 270 | 4.25 | 4 | #!/usr/bin/python3
dict = {'Name': 'Vivek', 'EMP-ID': 694, 'Team': 'DevOps', 'DOJ': '25-08-2014', 'DOB': '28-12-1983'};
for key in dict:
print(key)
key = input("Enter key: ")
try:
print ("Record found: ", dict[key])
except KeyError as e:
print("Key not found: ", e)
| false |
b0b9050a4d5311b495fd508fd447a6db3b57deba | nikejd1706/Speshilov_Nikita | /PyLesson_09/ReverseWord.py | 380 | 4.1875 | 4 | myList = ["cheese", "money", "pizza", "trash", "football"]
print("In order....")
output = ""
for i in myList:
output += i + " "
print(output)
print("\n________________")
print("Reversed....")
def reverse(myList):
output = " "
for i in range(len(myList),0,-1):
output += myList[i-1] + " "
print(output)
reverse(myList)
| false |
4b9818780f0e479b25ad142c597907e523b2f8a4 | verkeerd-zz/structured-programming | /2. tekstcheck.py | 797 | 4.125 | 4 | def index_intersection():
"""
asks the user for two strings. returns the index on which the two given strings deviate.
"""
string_1 = input('Geef een string: ')
string_2 = input('Geef nog een string:')
found = False
if not found:
for i in range(len(string_1)):
if string_1[i] != string_2[i]:
found = True
print('Het eerste verschil zit op index ' + str(i))
break
if string_1 == len(string_2):
print('De strings zijn identiek.')
elif string_1 > string_2:
print('Het eerste verschil zit op index ' + str(len(string_2) + 1))
else:
print('Het eerste verschil zit op index ' + str(len(string_1) + 1))
index_intersection()
| false |
ad0643f1266e05b6706f7fe645de827e8f61193d | dhx1994/PyPro | /test_2/5.py | 1,111 | 4.125 | 4 | """"jine = input("请输入金额:") # 获取输入金额,赋值给jine这个变量
print("输入的金额为:",jine) # 打印jine
num = jine.count(".") # 统计jine这个字符串中,有多少个小数点
if num == 0 or num == 1: # 判断小数的个数,只有小数点为0或者为1个的情况,才认为是正常的数字
hstr = "0123456789."
for i in jine: # 便利jine 给i
if i not in hstr: # 判断jine这个字符串中,是否存在非数字和小数点的值
print("输入的值不合法,请输入数字!")
exit()
jine = float(jine) # 强制转换数据类型为float
if jine >= 0.01 and jine <= 200:
print("发送红包成功!")
else:
print("金额超出范围!")
else:
print("输入的金额不合法,只能输入数字!")"""
while True:
try:
x = float(input('Please input a number: '))
break
except TypeError:
print('Oops! invalid number.Try again...')
if x >= 0.01 and x <= 200:
print("success!")
else:
print('please try again')
| false |
89acb313a5b19f8766aeca403af3ec8bd3366a30 | ItsFadinG/Python-100-Day-of-Code-Walkthrough | /100Python_Day_Code_Challenges/Day1-3/Pomodoro.py | 461 | 4.28125 | 4 | """
Walkthorugh:
- let the user set a duration.
- when its done notfiy him.
- make it countiously.
"""
import datetime, time
input_time = input("Enter Your Studying minutes: ")
print("Your Styduing time will be finished after {} Minutes".format(input_time))
duration = int(input_time) * 60
while True:
print(datetime.timedelta(seconds=duration))
duration -= 1
if duration < 0:
break
time.sleep(1)
print("Time's Up")
| true |
cbe95786dc58d87b91627042b2e595ee68041280 | yaizkazani/yaizkazani | /jorgegonzales_py_practice/Mean, Median, Mode.py | 2,109 | 4.3125 | 4 | # Mean, Median, and Mode
#
# In a set of numbers, the mean is the average, the mode is the number that occurs the most, and if you rearrange all the numbers numerically,
# the median is the number in the middle.
#
# Create three functions that allow the user to find the mean, median, and mode of a list of numbers. If you have access or know of functions
# that already complete these tasks, do not use them.
# Subgoals
# In the mean function, give the user a way to select how many decimal places they want the answer to be rounded to.
# If there is an even number of numbers in the list, return both numbers that could be considered the median.
# If there are multiple modes, return all of them.
from functools import *
from math import *
def mean(mylist, digits = 10):
return round(reduce(lambda x, y: x + y, mylist) / len(mylist), digits) # we call for lambda using reduce and then calculate mean with required accuracy
def mode(mylist):
count = dict()
ans = []
for item in mylist:
count[item] = count.get(item, 0) + 1 # using dict to calculate number of occurences
for key in count.keys():
if count[key] == max(count.values()): # get digits (they are keys) that has maximum occurence number
ans.append(key)
return ans
def median(mylist):
half_len = len(mylist) / 2
if half_len.is_integer(): # yay its not integer, but still works ^^
half_len = int(half_len) # now its integer
return mylist[half_len - 1:half_len + 1]
else:
return mylist[floor(half_len)]
mylist = [int(i) for i in input("Please enter set of numbers that will be used to calculate median, mean and mode")]
digits = input("Optional: Please enter number of decimal places to round mean")
print("Median is: ", median(mylist))
print("Mean is: ", mean(mylist), " rounded to 10 digits by default") if digits == "" \
else print("Mean is: ", mean(mylist, int(digits)), " rounded for", digits, "decimal places")
print("Mode value(s) :", mode(mylist))
| true |
44edbd860fb9c2a7bc8da43ef6f7576de95b6893 | yaizkazani/yaizkazani | /jorgegonzales_py_practice/Palindrome.py | 574 | 4.28125 | 4 | # Palidrome
#
# Palindrome means anything(here numbers) that reads the same backwards as forwards.
# Write a program to check if a number is a palindrome or not.
# For example 12321 is a palindrome since it reads the same forward and backwards.
def is_palindrome(string):
if len(string) % 2 == 0:
return True if string[:len(string) // 2] == string[:len(string) // 2 - 1:-1] else False
else:
return True if string[:len(string) // 2] == string[:len(string) // 2:-1] else False
print(is_palindrome(input("Please enter the string to check"))) | true |
1d99e190e9cdf9c1b5c792724b120bb69b9af1eb | yaizkazani/yaizkazani | /jorgegonzales_py_practice/Fibonacci.py | 1,239 | 4.3125 | 4 | # Fibonacci Sequence
#
# If you do not know about the Fibonacci Sequence, read about it here.
#
# Define a function that allows the user to find the value of the nth term in the sequence.
# To make sure you've written your function correctly, test the first 10 numbers of the sequence.
# You can assume either that the first two terms are 0 and 1 or that they are both 1.
# There are two methods you can employ to solve the problem. One way is to solve it using a loop and the other way is to use recursion.
# Try implementing a solution using both methods.
#
from functools import reduce
def recursive_fib(n):
if n == 1 or n == 2:
return 1
else:
return recursive_fib(n - 1) + recursive_fib(n - 2)
def iterative_fib(n):
if n == 0 or n == 1:
return 1
else:
fib = 1
mylist = [1, 0]
while n > 2:
mylist[1] = fib
fib += mylist[0]
mylist[0] = mylist[1]
n -= 1
return fib
seq_number = int(input("Enter number of desired Fib number\n"))
print("recursive function result: ", recursive_fib(seq_number),"\niterative function result: ", iterative_fib(seq_number), sep="") | true |
d666c6b8c3bca4179e81e67980c6f28f707bb4d1 | Novandev/projecteuler | /python/problem1.py | 600 | 4.5625 | 5 | # This program will print out the multiples of 3 or 5 and print them
import sys
def multiples(num):
""" This will print out mulitples of 3 and 5 of any number and will add them"""
#Convert to an integer value first
num=int(num)
# tracking value
total_list=0
# loop through all of the values in the range of num
for i in range(num + 1):
# if its devisible my 3 or 5 then print
if i % 3 == 0 or i % 5 ==0:
total_list += i
print("{} is the total number of items".format(total_list))
if __name__ == '__main__':
multiples(sys.argv[1])
| true |
4d76aac9da3e8f587a7c3d739ee8e572f535686a | deepsjuneja/tathastu_week_of_code | /day5/program5.py | 478 | 4.25 | 4 | def arrange(array):
odd = []
even = []
for i in array:
if i%2 == 0:
even.append(i)
else:
odd.append(i)
array = sorted(odd, reverse=True) + sorted(even)
print("Re-arranged array: ", array)
n = int(input("Enter no. of elements in array: "))
Array = []
print("Enter the elements of array one by one: ")
for i in range(n):
ele = int(input())
Array.append(ele)
print("Original array: ", Array)
arrange(Array)
| true |
6afbcc9140b7d26d775b6d957f1e29bac7b10896 | deepsjuneja/tathastu_week_of_code | /day4/program2.py | 656 | 4.21875 | 4 | nList = int(input("Enter the no. of tuples in list: "))
nTuple = int(input("Enter the no. of elements in each tuple: "))
List = []
for i in range(nList):
print("Enter the elements in tuple", i+1, "one by one: ")
Tuple = ()
for j in range(nTuple):
a = int(input())
Tuple = Tuple + (a, )
List.append(Tuple)
num = int(input("Enter the index by which you want the tuple list to be sorted: "))
for i in range(nList):
for j in range(nList - i - 1):
if List[j][num] > List[j+1][num]:
temp = List[j]
List[j] = List[j+1]
List[j+1] = temp
print("Sorted Tuple List: ", List)
| false |
21a16b97346d5deebd9b1170669e38e8e936153b | whatsreal/CIS-120-Assignments | /Guttag Finger Exercises/FE2.py | 528 | 4.625 | 5 | #Finger Exercise 2
#End of Chapter 2 Section 2
#Write a program that examines three variables x, y, and z.
#It prints the largest odd variable of the three.
#If none of the variables are odd print an error message.
#Define the three variables:
#Use nested if-elif-else statements to find the largest odd number.
#What if all the numbers are odd?
#What if only 1 is odd? Or 2?
#What if the largest number is even, but one of the others is odd?
#Account for all possibilities in the if statement. (It might be kinda big.) | true |
b1ecad6b819348fe4b84c67f50a413f2ee811dec | samyakbambole/Python | /Learning/4.Strings.py | 1,126 | 4.5 | 4 | # Strings Program
# 6/5/2020
greeting = "Samyak Bambole"
#indexes: 01234
print( len(greeting) ) # Length of the string
print("")
print( greeting[0] ) #Accessing the index
print("")
print( greeting[-1] ) #This is the negative index position
print("")
print( greeting.find("yak") )# This will find the string given in the variable
print("")
print( greeting.find("z") )
print("")
print( greeting[2:] )
print("")
print( greeting[2:3] )
print("")
print ("Samyak \" Bambole\" ") # Use this to print a double-quotation mark in the string
print("")
print(greeting.lower()) # This will output everything in the lower case
print("")
print(greeting.upper())# This will output everything in the upper case
print("")
print(greeting.isupper()) # This will return a boolean value. it will say true if all of the characters are upper case.
print("")
print(greeting.islower())
print("")
print(greeting.upper().isupper()) # I made it upper case and now it will return true
print("")
print(greeting.index("k")) # This will return the index value of k
print("")
print(greeting.replace("Samyak", "Elephant")) # This will replave samyak with elephant
| true |
e8812e8254fcd60a449eedc52843bab4d540769f | antonioazambuja/study | /exercpythonbrasil/2.exerc_decisao/exerc21.py | 1,216 | 4.21875 | 4 | '''Faça um Programa para um caixa eletrônico. O programa deverá perguntar ao usuário a valor do saque e depois informar
quantas notas de cada valor serão fornecidas. As notas disponíveis serão as de 1, 5, 10, 50 e 100 reais. O valor mínimo
é de 10 reais e o máximo de 600 reais. O programa não deve se preocupar com a quantidade de notas existentes na máquina.
Exemplo 1: Para sacar a quantia de 256 reais, o programa fornece duas notas de 100, uma nota de 50, uma nota de 5 e uma
nota de 1;
Exemplo 2: Para sacar a quantia de 399 reais, o programa fornece três notas de 100, uma nota de 50, quatro notas de 10,
uma nota de 5 e quatro notas de 1.
'''
saque = float(input("INFORME O VALOR DO SAQUE: "))
if saque > 0:
saque_final = saque
nota100 = saque_final // 100
saque_final = saque % 100
nota50 = saque_final // 50
saque_final = saque % 50
nota10 = saque_final // 10
saque_final = saque % 10
nota5 = saque_final // 5
saque_final = saque % 5
nota1 = saque_final // 1
saque_final = saque % 1
print("NOTAS DE 100:",nota100,", NOTAS DE 50:",nota50,", NOTAS DE 10:",nota10,", NOTAS DE 5:",nota5,"NOTAS DE 1:",nota1,'.')
else:
print("VALOR INVÁLIDO!")
| false |
9c34ac3a37cd56bc02d2ffbdae8786014228186c | Oyagoddess/PDX-Code-Guild | /learnpyex/ex6.py | 826 | 4.375 | 4 | # x is a string statement with 10 as the value for % variable with a complex string
x = "There are %d types of people." % 10
#binary is string value for binary
binary = "binary"
#don't is the string value for do_not
do_not = "don't"
# y is the string statement with two values replacing the % with string values.
y = "Those who know %s and those who %s." % (binary, do_not)
#print x and y statements
print x
print y
# %r gives the raw data of x (as is)
print "I said: %r." % x
# this is a print statement with a string inside a string
print "I also said: '%s'." % y
hilarious = False
#this is another string inside a string
joke_evaluation = "Isn't that joke so funny?! %r"
print joke_evaluation % hilarious
w = "This is the left side of..."
e = "a string with a right side."
#this adds the two strings together
print w + e | true |
3b7bc7a7a6654aabd92afb276d4b2310176da240 | Oyagoddess/PDX-Code-Guild | /phonebook3.py | 1,813 | 4.15625 | 4 | # Cleaner updated phonebook
name = 'name'
address = 'address'
phone = 'phone'
entry = [name, address, phone]
phonebook = {} # removed original value- {name: entry} to test joe.
phonebook['joe'] = ['joe', '123 elm st', '123-456-1234']
choice = raw_input('would you like to add, search or delete an entry?')
if choice == 'add':
name = raw_input('What is your first and last name?')
address = raw_input('What is your current address?')
phone = raw_input('what is your phone number?')
entry = [name, address, phone]
phonebook = {name: entry}
d = {'n': entry[0], 'a': entry[1], 'p': entry[2]}
template = """
%(n)s
%(a)s
%(p)s
Has been added
"""
print (template % d)
print (phonebook)
elif choice == 'search':
name = raw_input('who do you want to find?') # had to redefine search variable
if name in phonebook.keys(): # Changed to an 'if' statement so that it will look in the dictionary key.
d = {'n': phonebook[name][0], 'a': phonebook[name][1], 'p': phonebook[name][2]}
template = """
%(n)s
%(a)s
%(p)s
"""
print (template % d)
else:
print ('It is not found')
elif choice == 'delete':
name = raw_input('who do you want to delete?')
if name in phonebook.keys():
d = {'n': phonebook[name][0], 'a': phonebook[name][1], 'p': phonebook[name][2]}
template = """
%(n)s
%(a)s
%(p)s
"""
print (template % d)
answer = raw_input('are you sure you want to delete? y/n')
if answer == 'y' or 'yes':
phonebook.pop(name) # Added a method to delete the dictionary.
print(phonebook)
else:
print('You changed your mind!')
else:
print ('It is not found')
| true |
9ea28602435647619b41d869f1c7c04d2159d790 | Oyagoddess/PDX-Code-Guild | /learnpyex/ex33.py | 858 | 4.1875 | 4 | i = 0 # variable i
numbers = [] # creates an empty
while i < 6: # as long as i is less than 6 is true print and run this
print "At the top i is %d" % i # print whatever position or number i is as it loops
numbers.append(i) # add i into the numbers list until you reach 5 (i in 6)
# and add 1 to i in 6 each time until you reach (i in 6) 5, translates to i = 0+1,i = 1 + 1 = 2 and so on.
i = i + 1
print "Numbers now: ", numbers # print the list of numbers in the list so far
print "At the bottom i is %d" % i # print what the number is in this position
print "The numbers: "
for num in numbers: # this calls nums (i) in numbers list this also prints each item of the list in newlines.
print num # this prints the numbers that have been added to the list
#print num, # this prints the numbers on one single line
| true |
9c3b91ff2ab458aa7612979dd9be9bce06a3948e | Oyagoddess/PDX-Code-Guild | /learnpyex/ex30.py | 1,295 | 4.59375 | 5 | # create variables
people = 30
cars = 40
buses = 15
# create if statement to create conditions to run the function, this runs top to bottom
if cars > people: # if this is true print
print "We should take the cars." # end of the if block of code
elif cars < people: # if this is true print this.
print "We should not take the cars."
else: # if neither above is true then do this and ends this block of code.
print "We can't decide"
# this is another block of code
if buses > cars:
print "That's too many buses."
elif buses < cars:
print "Maybe we could take the buses."
else:
print "We still can't decide."
# another block of code with just else
if people > buses:
print "Alright, let's just take the buses."
else:
print "Fine, let's stay home then"
# studydrill
# 1. the elif gives another condition to follow & tells python that if this statement is true then do this
# the else statement give an alternative condition if the if and elif is not true
# 2. if you change the values of the variables then the true statement will print.
# 3.
if cars == people:
print " everybody can have there own car"
elif cars < people:
print " divide the group and pic a car to ride in"
else:
print "we may have to get a bus"
# notes are above most lines.
| true |
c2a1173c55e71b497209971181f0555c22fc9bb0 | Oyagoddess/PDX-Code-Guild | /learnpyex/ex21.py | 1,503 | 4.34375 | 4 | # creates a functions with 2 arguments for adding a & b
def add (a, b):
print "ADDING %d + %d" % (a, b) # assigns a and b to string
return a + b # returns a + b
# creates a functions with 2 arguments for subtracting a & b
def subtract(a, b):
print "SUBTRACTING %d - %d" % (a, b)
return a - b
# creates a functions with 2 arguments for multiplying a & b
def mutliply(a, b):
print "MULTIPLYING %d * %d" % (a, b)
return a * b
# creates a functions with 2 arguments for dividing a & b
def divide(a, b):
print "DIVIDING %d / %d" % (a, b)
return a / b
print "Let's do some math with just functions!"
# calls to run the functions and assign values to a and b
age = add(30, 5)
height = subtract(78, 4)
weight = mutliply(90, 2)
iq = divide(100, 2)
print "Age: %d, Height %d, Weight: %d, IQ: %d" % (age, height, weight, iq)
# A puzzle for the extra credit, type it anyway.
print "Here is a puzzle."
what = add(age, subtract(height, mutliply(weight, divide(iq, 2))))
print "That becomes: ", what, "Can you do it by hand?"
#studydrill simplify and break function down in order age plus height subract weight multiply iq and divide it by 2
puzzle_by_hand = age + height - weight * iq / 2
print puzzle_by_hand, "is the same number, when you simplify the function"
inverse = iq / 2 * weight - height + age
print "when you change the formula you get", inverse,
new_function = weight + height / iq * age
print " this is a random function that totals", new_function
| true |
2b7280e3db240bc58dffdd25ca51db439d8a36ee | rlehman221/Python_Hashmap | /main.py | 807 | 4.25 | 4 | from hashmap import HashMap
# Utilizing hashmap class
hash_map = HashMap()
print("Initializing empty hashmap " + str(hash_map))
hash_map["FirstKey"] = 23
hash_map["SecondKey"] = 53
print("Adding two values to hashmap " + str(hash_map))
hash_map["FirstKey"] = 13
print("Updating first value in hashmap " + str(hash_map))
hash_map.delete("FirstKey")
print("Deleting value in hashmap " + str(hash_map))
hash_map_two = HashMap()
hash_map_two["FirstKey"] = 203
print("Initializing second hashmap " + str(hash_map_two))
hash_map.update(hash_map_two)
print("Updating first hashmap with second hashmap " + str(hash_map))
print("All keys in hashamp " + str(hash_map.keys()))
print("All values in hashmap " + str(hash_map.values()))
print("The amount of buckets in hashmap " + str(hash_map.num_sections()))
| false |
dbbe1ba36d5d2e06dbb02e64f0f9a9f0b6f41530 | LuceroLuciano/bonitoDevoradorDePalabras | /bonitoDevoradorDePalaras/bonitoDeboradorDePalabras.py | 1,097 | 4.25 | 4 | """
Objetivo:
-Utilizar la función continue de los ciclos
-Ciclo for
-condicional (if-elif-else)
Tu programa debe:
-Pedir al usuario que ingrese una palabra.
-Utilizar userWord = userWord.upper() para convertir la palabra ingresada por el usuario a mayúsculas;
-Usa la ejecución condicional y la instrucción continue para "comer" las siguientes vocales A , E , I , O , U de la palabra ingresada.
-Asigne las letras no consumidas a la variable palabrasinVocal e imprime la variable en la pantalla.
"""
print ("""
+----------------------------------+
| El bonito devorador de palabras |
+----------------------------------+
""")
# palabraSinVocal = ""
userWord = input("Ingrese una palabra: ")
userWord = userWord.upper()
for letra in userWord:
if letra == "A":
continue
elif letra == "E":
continue
elif letra == "I":
continue
elif letra == "O":
continue
elif letra == "U":
continue
else:
palabraSinVocal = letra
print(palabraSinVocal, end="")
| false |
c2c3ae073dacd83e0b9375ba317b8bb4fc9b5533 | LuceroLuciano/bonitoDevoradorDePalabras | /ciclo_for/ciclo_for.py | 476 | 4.15625 | 4 | #juegando a las escondidas
#contando los numeros y agregando
#la palabra Mississippi
import time
for i in range(1, 6): #Escribe un ciclo for que cuente hasta cinco.
print(i, "Mississippi") #Cuerpo del ciclo: imprime el número de iteración del ciclo y la palabra "Mississippi".
time.sleep(3) #esperar tres segundos para imprimir cada mensaje
# Escribe una función de impresión con el mensaje final.
print("¡Listo o no!, ahi voy!")
| false |
b96188bd9372b4e0d4f5c071ce9947404591b79c | aby180182/PythonCore | /Lesson_8_1(Exception)/0.py | 1,330 | 4.25 | 4 | # Створити батьківський клас Figure з методами init:
# ініціалізується колір, get_color: повертає колір фігури,
# info: надає інформацію про фігуру та колір,
# від якого наслідуються такі класи як Rectangle, Square, які мають інформацію про ширину,
# висоту фігури, метод square, який знаходить площу фігури.
class Figure:
def __init__(self, color):
self.color = color
def get_color(self):
return self.color
def info(self):
return f'color: {self.color}'
class Rectangle(Figure):
def __init__(self, color, width, height):
Figure.__init__(self, color)
self.width = width
self.height = height
def square(self):
return self.width * self.height
class Square(Figure):
def __init__(self, color, side):
Figure.__init__(self, color)
self.side = side
def square(self):
return self.side * self.side
figure = Figure('red')
print(figure.get_color())
print(figure.info())
rectangle = Rectangle('green', 3, 4)
print(rectangle.square())
sq = Square('blue', 9)
print(sq.square()) | false |
2fb40baace63d67790c6a58abdd3bfeef0f02fd9 | devopsuser99/Python_Practice | /calculator.py | 264 | 4.21875 | 4 | num1 = float(input("1st number: "))
opp = input("Operator: ")
num2 = float(input("Second number: "))
if opp == "+":
print(num1 + num2)
elif opp == "-":
print(num1 - num2)
elif opp == "/":
print(num1 / num2)
else:
print(num1 * num2)
| false |
ed513e3b3568dec15daad85b681742b0cffcbc68 | yorchpave/EdX-Courses | /Introduction to Python/midterm_04.py | 831 | 4.25 | 4 | # Initialize input variable
user_input = ""
# Method that checks input and prints corresponding output
def str_analysis(user_input):
# User can't leave space blank
while user_input == "":
user_input = input("Enter word or integer: ")
if user_input != "":
break
if user_input.isdigit(): # If user input is digit, cast to int and check conditionals
user_int = int(user_input)
if user_int > 100:
print("big number")
elif user_int < 50:
print("small number")
else:
print("nice number!")
elif user_input.isalpha(): # If user input is alphabetic and check conditionals
print("That's alphabetic!")
else:
print(user_input,"is an invalid input!")
# call str_analysis method
str_analysis(user_input)
| true |
ee89c159498a9568a1ede03f9460cc05449d9676 | gaebar/London-Academy-of-It | /exercise11to20/Exercise11_NameAnalysis.py | 810 | 4.28125 | 4 | first_name = input("Please enter your first name: ")
last_name = input("Please enter your last name: ")
print("\nYour full name is " + first_name + " " + last_name)
# Firsts and lasts letters given
x = str(len(first_name))
print("Your first name length is " + x + " letters")
y = str(len(last_name))
print("Your last name length is " + y + " letters")
z = int(x) + int(y)
print("Your full name length is " + str(z) + " letters")
initial_name= first_name[:1]
print("\nFirst name starts with: ", initial_name)
initial_lastname= last_name[:1]
print("Last name starts with: ", initial_lastname)
end_name= first_name[-1:]
print("\nFirst name ends with: ", end_name)
end_lastname= last_name[-1:]
print("Last name ends with: ", end_lastname)
print("\nYour initials are: ", initial_name, initial_lastname)
| true |
1165d02610d5b0461dfac6a06de05d9835e7dd8a | gaebar/London-Academy-of-It | /exercise11to20/Exercise21_EncryptName.py | 446 | 4.34375 | 4 |
# Alberto's way:
name = input("Please enter your name: ")
name_lenght = len(name)
name_crypto: str = ""
for letter in name:
if name_crypto == "":
name_crypto += letter
elif len(name_crypto) == name_lenght-1:
name_crypto += letter
else:
name_crypto += "*"
print("Encrypted form is ", name_crypto)
# professor's way:
name = input("Please enter your name: ")
print(name[0] + '*' *(len(name)-2) + name[-1]) | false |
9256a184b1e6ec85d2c4fde69fa52a52faf7cd1e | Cameron-Calpin/Code | /Python - learning/Data Structures/merge_dict.py | 805 | 4.1875 | 4 | def mergeWithoutOverlap(oneDict, otherDict):
newDict = oneDict.copy()
for key in otherDict.keys():
if key in oneDict.keys():
raise ValueError, "the two dictionaries are sharing keys!"
newDict[key] = otherDict[key]
return newDict
def mergeWithOverlap(oneDict, otherDict):
newDict = oneDict.copy()
for key in otherDict.keys():
if key in oneDict.keys():
newDict[key] = oneDict[key], otherDict[key]
else:
newDict[key] = otherDict[key]
return newDict
if __name__ == '__main__':
phoneBook1 = {'michael': '555-1212', 'mark': '554-1121', 'emily': '556-0091'}
phoneBook2 = {'latoya': '555-1255', 'emily': '667-1234'}
# new_phonebook1 = mergeWithoutOverlap(phoneBook1, phoneBook2)
new_phonebook2 = mergeWithOverlap(phoneBook1, phoneBook2)
# print new_phonebook1
print new_phonebook2 | false |
7bcf591aedf7d3a4cdbcc6ae1f194b719f5e5f48 | NandaKumarKonetisetti/Python-Basics | /generators.py | 492 | 4.15625 | 4 | #Generators will give you iterators so we has to use iterable functions to fetch the value or else we can use iter and next functions
def generator():
yield 1
yield 2
yield 3
yield 7
gene = generator()
print(gene.__next__())#If users wants to call one one object
print(gene.__next__())
print(gene.__next__())
for i in gene:
print(i)
def gen():
value =0
while(value<8):
sq = value * value
yield sq
value += 1
for i in gen():
print(i) | true |
362c0de8d2b590362301482865e4bed37741ae26 | NandaKumarKonetisetti/Python-Basics | /prime.py | 432 | 4.125 | 4 | number = 9;
for i in range(2,number):
if number % i == 0:
print("The given number is not a prime")
break
else:
print("The given number is a prime")
print("printing the prime numbers in between a Range")
lower = 2
upper = 7
for num in range(lower,upper+1):
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num)
| true |
e36889f5bef00611e83358279b7179cc3da79dcc | pbavafa/Bioinformatics | /Rosalind/Complementing a Strand of DNA/Complementing a Strand of DNA.py | 665 | 4.21875 | 4 | def ReverseComplement(Pattern):
Pattern = Reverse(Pattern) # reverse all letters in a string
Pattern = Complement(Pattern) # complement each letter in a string
return Pattern
def Reverse(Pattern):
return Pattern[::-1]
def Complement(Pattern):
basepairs = {"A":"T", "G":"C", "T":"A", "C":"G"}
complement = ""
for char in Pattern:
complement += str(basepairs.get(char))
return complement
with open('C:\\Users\\pouya\\Documents\\Python-Projects\\Bioinformatics\\Rosalind\\Complementing a Strand of DNA\\rosalind_revc.txt', 'r') as String:
String = String.read()
result = ReverseComplement(String)
print(result) | true |
c512c53918a2eb1196a20a57800b585c5a48cc2f | nikita-choudhary/Programming-Assignment-3 | /Q1.py | 287 | 4.375 | 4 | #1. Write a Python Program to Check if a Number is Positive, Negative or Zero?
a= int(input("Enter the no. : "))
if a>0:
print("The no. you entered is Positive number")
elif a<0:
print("The no. you entered is Negative number")
else:
print("The number entered is ZERO") | true |
e0078d49ce84210390fc1a7ecf71e4b31649edff | RobyJacob/Coding-problems | /closest_sum.py | 1,058 | 4.1875 | 4 | #!/usr/bin/python3
import sys
import math
'''
Given an array of N integers and a target value, find 3 numbers such that their sum is closest to the target
and return the sum
For eg:- input: [-1, 2, 1, -4] target = 1
output: 2 (i.e., -1+2+1=2)
'''
def find_closest_sum(arr, target):
closest_sum, min_diff = 0, math.inf
arr.sort()
for i in range(len(arr)-2):
ptr1, ptr2 = i+1, len(arr)-1
while ptr1 < ptr2:
current_sum = arr[i] + arr[ptr1] + arr[ptr2]
if min_diff > abs(current_sum-target):
closest_sum = current_sum
min_diff = abs(current_sum-target)
if current_sum > target:
ptr2 -= 1
else:
ptr1 += 1
return closest_sum
def main():
if len(sys.argv) < 2:
print("Please specify arguments as space seperated numbers")
sys.exit(-1)
arr = list(map(int, sys.argv[1:]))
t = int(input("Target value: "))
print(find_closest_sum(arr, t))
if __name__ == "__main__":
main()
| true |
84d8576d9116b2f20d29ab855e3238a1dd392f25 | Avi2021-oss/ML-algorithms | /gradient_descent.py | 941 | 4.625 | 5 | '''
Here we will use Gradient Descent to find minima of a given function.
Let the Given Function be Y=(X+5)^2 and we have to find the minima of this given function.
We already know the minima of this function occurs when X = -5 let's find it out using Gradient Descent.
'''
current_x = 12
learning_rate = 0.01
no_of_steps = 1000
step_counter = 1
def df(x): return 2*(x+5) # Differentiation of given Function Y=(X+5)^2
while step_counter < no_of_steps:
prev_x = current_x
current_x = current_x - learning_rate * \
df(prev_x) # Gradient Descent algorithm
change_in_x = abs(current_x-prev_x)
step_counter += 1
print("Step:", step_counter, " || Value of X", current_x)
# Changing the value of no_of_steps and learning rate we can get closer to the minima of a function.
# This was the simple Gradient Descent Algorithm which is used to find minima of a function (generally loss function in machine learning)
| true |
62086f2ddd92b6269e8eed4a3fd89f982c3cde4d | acrodeon/pythonInteractive-algos | /binaryTree.py | 2,577 | 4.21875 | 4 | #################################################################################
# Binary Tree #
# The root value, as well as the left and right subtrees #
#################################################################################
class BinaryTree:
def __init__(self,rootObj):
"""creates a new instance of a binary tree of root rootObj"""
self.key = rootObj
self.leftChild = None
self.rightChild = None
def insertLeft(self,newNode):
"""creates a new binary tree and installs it as the left child of the current node"""
if self.leftChild == None:
self.leftChild = BinaryTree(newNode)
else:
# insert a node and push the existing child down one level in the tree
t = BinaryTree(newNode)
t.leftChild = self.leftChild
self.leftChild = t
def insertRight(self,newNode):
"""creates a new binary tree and installs it as the right child of the current node"""
if self.rightChild == None:
self.rightChild = BinaryTree(newNode)
else:
# insert the node between the root and an existing right child
t = BinaryTree(newNode)
t.rightChild = self.rightChild
self.rightChild = t
def getRightChild(self):
"""returns the binary tree corresponding to the right child of the current node"""
return self.rightChild
def getLeftChild(self):
"""returns the binary tree corresponding to the left child of the current node"""
return self.leftChild
def setRootVal(self,obj):
"""stores the object in parameter val in the current node"""
self.key = obj
def getRootVal(self):
"""returns the object stored in the current node"""
return self.key
def getMinDepth(self):
"""returns the min depth of this binary tree (it means the root)"""
return 1 + min(self.leftChild.getMinDepth(), self.leftChild.getMinDepth()) if self.key != null else 0
def getMaxDepth(self):
"""returns the Max depth of this binary tree (it means the root)"""
return 1 + max(self.leftChild.getMaxDepth(), self.leftChild.getMaxDepth()) if self.key != null else 0
def inOrder(self):
"""in Order"""
if self.key:
if self.leftChild:
self.leftChild.inOrder()
print(self.key)
if self.rightChild:
self.rightChild.inOrder()
| true |
464b7151743ffce15d0ff5df5872c2806f531767 | acrodeon/pythonInteractive-algos | /shellSort.py | 1,566 | 4.46875 | 4 | #################################################################################
# Shell Sort #
# sort by breaking the original list into a number of smaller sublists, #
# each of which is sorted using an insertion sort #
# the shell sort uses an increment i, sometimes called the gap, to create #
# a sublist by choosing all items that are i items apart #
#################################################################################
def shellSort(alist):
"""y sorting the sublists, we have moved the items closer to where they actually belong"""
sublistcount = len(alist) // 2
while sublistcount > 0:
for startposition in range(sublistcount):
gapInsertionSort(alist,startposition,sublistcount)
print("After increments of size",sublistcount,"The list is",alist)
sublistcount = sublistcount // 2
def gapInsertionSort(alist,start,gap):
"""sublists defined by gap are sorted with the basic insertion sort"""
for i in range(start+gap,len(alist),gap):
currentvalue = alist[i]
position = i
while position >= gap and alist[position-gap] > currentvalue:
alist[position] = alist[position-gap]
position = position - gap
alist[position] = currentvalue
##################
# Main() to test #
##################
if __name__ == '__main__':
alist = [54,26,93,17,77,31,44,55,20]
shellSort(alist)
print(alist)
| true |
a2160c5aead207a98a4707785644bf0f0f26bd89 | Deepshikhasinha/CTCI | /LinkedList/ReverseLinkedList.py | 1,187 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Dec 3 12:39:39 2018
@author: dsinha1
"""
#Linked List - reverse
class Node:
def __init__(self,data):
self.data = data
self.next = None
def insert(self, value):
node1 = self
while node1.next is not None:
node1 = node1.next
node = Node(value)
node1.next = node
node.next = None
def print_list(self):
node1 = self
while node1 is not None:
print(str(node1.data)+" -> "),
node1 = node1.next
class LinkedList:
def __init__(self,head):
self.head = head
def reverse(self):
prev = None
cur = self.head
while cur is not None:
next1 = cur.next
cur.next = prev
prev = cur
cur = next1
self.head = prev
def print_list(self):
node1 = self.head
while node1 is not None:
print(str(node1.data)+" -> "),
node1 = node1.next
n = Node(1)
n.insert(6)
n.insert(5)
n.insert(3)
n.insert(8)
n.print_list()
print("----------")
l = LinkedList(n)
l.reverse()
l.print_list()
| false |
7713be4a7c227fc6a26f294b29c783bf05b1d019 | FredChang823913319/Intro-Deep-Learning | /mp1/Perceptron.py | 1,718 | 4.5 | 4 | """Perceptron model."""
import numpy as np
import scipy
class Perceptron:
def __init__(self, n_class: int, lr: float, epochs: int):
"""Initialize a new classifier.
Parameters:
n_class: the number of classes
lr: the learning rate
epochs: the number of epochs to train for
"""
self.w = None # TODO: change this
self.lr = lr
self.epochs = epochs
self.n_class = n_class
def train(self, X_train: np.ndarray, y_train: np.ndarray):
"""Train the classifier.
Use the perceptron update rule as introduced in the Lecture.
Parameters:
X_train: a number array of shape (N, D) containing training data;
N examples with D dimensions
y_train: a numpy array of shape (N,) containing training labels
"""
# TODO: implement me
self.w = np.random.randn(X_train.shape[1], 10)
for epoch in range(self.epochs):
print("epoch: " + str(epoch))
for i, x in enumerate(X_train):
label = y_train[i]
score = x.dot(self.w) # (10,)
update = (score > score[label]) # (10,)
sum_update = np.sum(update)
update = x[:, np.newaxis] * update # (D, 10)
self.w[:, label] = self.w[:, label] + self.lr * sum_update * x
self.w = self.w - self.lr * update
def predict(self, X_test: np.ndarray) -> np.ndarray:
"""Use the trained weights to predict labels for test data points.
Parameters:
X_test: a numpy array of shape (N, D) containing testing data;
N examples with D dimensions
Returns:
predicted labels for the data in X_test; a 1-dimensional array of
length N, where each element is an integer giving the predicted
class.
"""
# TODO: implement me
print("start predicting")
pred = X_test.dot(self.w).argmax(axis=1)
return pred
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.