blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
836e57879b40ec2e28484ddfda310704dfe30705 | prise-3d/rawls | /rawls/scene/vector.py | 738 | 4.125 | 4 | """3D vector representation
"""
class Vector3f():
"""3D vector represention constructor
Arguments:
x: {float} -- x axis value
y: {float} -- y axis value
z: {float} -- z axis value
"""
def __init__(self, x, y, z):
"""3D vector represention constructor
Arguments:
x: {float} -- x axis value
y: {float} -- y axis value
z: {float} -- z axis value
"""
self.x = x
self.y = y
self.z = z
def __str__(self):
"""Display Vector3f object representation
Returns:
{str} -- Vector3f information
"""
return '({0}, {1}, {2})'.format(self.x, self.y, self.z)
| false |
973dbd6c6cacda7b83e94d537eef50d729701423 | srivenkat13/OOP_Python | /Association _example.py | 892 | 4.25 | 4 | # two classes are said to associated if there is relation between classes without any rule
# be it aggregation , association and composition the object of one class is 'owned' by other class, this is the common point
# In composition they work together but, if one classes dissapears other will also sieze to exist
class A(object):
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def addNums(self):
self.b + self.c
class B(object):
def __init__(self, d, e):
self.d = d
self.e = e
def addAllNums(self, Ab, Ac):
x = self.d + self.e + Ab + Ac
return x
first = A("Hi", 2, 3)
second = B(3, 4)
print(second.addAllNums(first.b , first.c))
print(first.a , first.b, first.c) # this line prints the Class A objects
# this example demonstrates association between two classes ( object is shared here) | true |
192e5f3604b9d11c1192fa42aabcc8b0d130d36e | RaghaviRShetty/pythonassignment | /ebill.py | 307 | 4.125 | 4 | # -*- coding: utf-8 -*-
units = int(input(" Please enter Number of Units you Consumed : "))
if(units <=100):
amount = units * 2
elif(units > 100 and units<=200):
amount = units*3
elif(units > 200 and units<=300):
amount = units*5
else:
amount =units*6
print("\nElectricity Bill = ",amount) | true |
80b10f042795a094b4b72b22a3fca9f153ffeb02 | Sinfjell/FOR14 | /Workshops/week_36 - Variables_and_strings/exercise_4.py | 810 | 4.625 | 5 | # -*- coding: utf-8 -*-
"""
@author: Isabel Hovdahl
"""
"""
Exercise 4
Modify this week’s class exercise so that the temperature conversion program
instead converts temperatures from celsius to fahrenheit.
The program should:
- prompt the user for a temperature in celsius
- display the converted temperature in fahrenheit
"""
print('***************** Conversion program 3 *****************')
print('This program converts from Celsius to Fahrenheit.')
print('********************************************************\n')
# convert user input to integer
celsius = int(input('Please enter temperature to convert: '))
# calculate temperature conversion
fahren = (9 / 5 * celsius) + 32
print('\n{} degree(s) Celsius is {:.1f} degree(s) Fahrenheit.'.format(celsius, fahren)) | true |
e51133c3d5c0a4389a342db4d71dd204146e8ac3 | Sinfjell/FOR14 | /Workshops/week_38 - loops/Exercise_1a.py | 1,294 | 4.53125 | 5 | # -*- coding: utf-8 -*-
"""
@author: Isabel Hovdahl
"""
"""
Exercise 1a
Modify the random number generator from last workshop so that the
program now draws multiple random numbers within the given bounds.
The program should now:
- prompt the user for a lower and upper bound, and for the number
of draws.
- use a while loop to draw and display the random numbers to
the user.
For simplicity, you can ignore checking whether the inputs are valid.
"""
import random
# welcome message
print('*'*49)
print('**** Welcome to the random number generator! ****')
print('*'*49)
print('\nThis program draws random numbers between an upper and lower bound.')
# get number of draws and bounds from user
num_draws = int(input('Please enter the number of random numbers: '))
lower = int(input('Please enter a lower bound: '))
upper = int(input('Please enter an upper bound: '))
print('\nYou asked for {} random number(s) between {} and {}.'.format(num_draws, lower, upper))
print('The random numbers are:\n')
i = 0
while i < num_draws:
# draw and display random number
rand_num = random.randint(lower, upper)
print(rand_num)
# increment counter
i = i + 1 # alternatively, "i += 1"
| true |
0001040e8215e2f2e687d3d162a6c0812bc67d01 | Sinfjell/FOR14 | /Workshops/week_41 - Lists/Exercise_1b.py | 1,332 | 4.4375 | 4 | # -*- coding: utf-8 -*-
"""
@author: Isabel Hovdahl
"""
"""
Exercise 1b:
Write a program that creates a table with the tests scores of students.
The table should be in the form of a nested list where each sublist
contains the tests scores for a spesific student.
The program should:
- prompt the user for the number of students and the number of tests that
each student has taken.
- for each student:
- prompt the user for the scores on each of the tests.
- store the test scores in a nested list called table.
"""
# get the dimensions of the table
students = int(input('Enter the number of students: '))
tests = int(input('Enter the number of tests: '))
# initialize the table
table = []
# for each student...
for student in range(students):
print('\nEnter scores for student number {}:'.format(student + 1))
# ...initialize the scores
scores = []
# ...ask for the score on each test and append to list
for test in range(tests):
score = int(input('...Test number {}: '.format(test + 1)))
scores.append(score)
# ...append list with scores to table
table.append(scores)
# print table
print('\nThis is the final table with grades:')
for row in table:
print(row) | true |
f482dd234cd32a129e1e19db26dac4bd0cbf9ed3 | Sinfjell/FOR14 | /Workshops/week_37 - Decisions/Exercise_3.py | 1,241 | 4.28125 | 4 | # -*- coding: utf-8 -*-
"""
@author: Isabel Hovdahl
"""
"""
Exercise 3
The prisoner’s dilemma is a common example used in game theory.
One example of the game is found in the table below (see slide).
Write a program that implements the game. The program should:
- prompt the user for two inputs – prisoner A’s choice and prisoner B’s choice (confess or stay silent).
- print the outcome of the game, i.e. how much time must each of the prisoners serve.
"""
print('**********************************')
print("Welcome to the Prisoner's Dilemma.")
print('**********************************')
choiceA = input('Prisoner A, you are up.\nPress 1 for "confess", press 2 for "stay silent": ')
choiceB = input('Prisoner B, you are up.\nPress 1 for "confess", press 2 for "stay silent": ')
if choiceA == '1' and choiceB == '1':
print('\nYou both get 2 years.')
elif choiceA == '1' and choiceB == '2':
print('\nPrisoner A gets 3 years, prisoner B goes free.')
elif choiceA == '2' and choiceB == '1':
print('\nPrisoner A goes free, prisoner B gets 3 years.')
elif choiceA == '2' and choiceB == '2':
print('\nYou both get 1 year.')
else:
print('INVALID INPUT') | true |
4d3cc4a33f6b0a0f13c703a7a5eeca8a52eb83cf | jlyu/chain-leetcode | /expired/algorithm/341. Flatten Nested List Iterator.py | 2,826 | 4.5625 | 5 | # -*- coding: utf-8 -*-
import time
"""
https://leetcode.com/problems/flatten-nested-list-iterator/
Given a nested list of integers, implement an iterator to flatten it.
Each element is either an integer, or a list -- whose elements may also be integers or other lists.
Example 1:
Given the list [[1,1],2,[1,1]],
By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1].
Example 2:
Given the list [1,[4,[6]]],
By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6].
"""
# """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
#class NestedInteger(object):
# def isInteger(self):
# """
# @return True if this NestedInteger holds a single integer, rather than a nested list.
# :rtype bool
# """
#
# def getInteger(self):
# """
# @return the single integer that this NestedInteger holds, if it holds a single integer
# Return None if this NestedInteger holds a nested list
# :rtype int
# """
#
# def getList(self):
# """
# @return the nested list that this NestedInteger holds, if it holds a nested list
# Return None if this NestedInteger holds a single integer
# :rtype List[NestedInteger]
# """
class NestedIterator(object):
def __init__(self, nestedList):
"""
Initialize your data structure here.
:type nestedList: List[NestedInteger]
"""
def gen(nestedList):
for x in nestedList:
if x.isInteger():
yield x.getInteger()
else:
for y in gen(x.getList()):
yield y
self.gen = gen(nestedList)
def next(self):
"""
:rtype: int
"""
return self.value
def hasNext(self):
"""
:rtype: bool
"""
try:
self.value = next(self.gen)
return True
except StopIteration:
return False
# Your NestedIterator object will be instantiated and called as such:
# i, v = NestedIterator(nestedList), []
# while i.hasNext(): v.append(i.next())
def testcase(input, expected):
ins = Solution()
output = ins.removeDuplicateLetters(input)
print "in: %s, expected: %s, out: %s" % (input, expected, output)
#assert (before == input)
#assert (after == output)
print "-"*40
def unittest():
testcase(input=[[1,1],2,[1,1]], expected=[1,1,2,1,1])
testcase(input=[1,[4,[6]]], expected=[1,4,6])
if __name__ == '__main__':
start = time.time()
unittest()
print "run time:", time.time() - start
| true |
038b2a2e1d1515decbf7a42cab33f3573e94c071 | whitem1396/CTI110 | /P5HW1_RandomNumber_White.py | 994 | 4.28125 | 4 | ''' P5HW1 Random Number
Matthew White
03/18/2019
Random number generator '''
# Display a random number in the range of 1 to 100
import random
def get_number():
# Get the random number
number = random.randint(1, 100)
# Ask the user to guess the number
guess = int(input("Guess the number: "))
print("The number is:", number)
# If/Else statement depending on the users guess
if guess > number:
print("Too high, try again")
else:
if guess < number:
print("Too low, try again")
else:
print("They are the same congrats!!")
def main():
#variable to control the loop
again = "y"
print("Random number generator 1-100")
# Calling the get_number function
while again == 'y' or again == 'Y':
get_number()
#Want to play another game?
again = input("Generate another number? (y = yes): ")
# Call the main function
main()
| true |
d41ebd2cfa5967513e89ecc7080b64c7786ae9bf | fhansmann/coding-basics | /mini-programs/birthdays.py | 1,139 | 4.40625 | 4 | birthdays = {'Alice' : 'Apr 1', 'Bob' : 'Dec 12', 'Carol' : 'Mar 4'}
while True:
print('Enter a name: (blank to quit)')
name = input()
if name == '':
break
if name in birthdays:
print(birthdays[name] + ' is the birthday of ' + name)
else:
print('I do not have birthday information for ' + name)
print('What is their birthday?')
bday = input()
# Check input format
bdayarray = bday.split(" ")
# bdayarray first argument: month so we need 3 character string
# first check string
try:
bdaymonth = str(bdayarray[0])
except:
print("Enter a month! (3 char lenght)")
continue
# second check lenght
if len(bdaymonth) != 3:
print("Enter a month correctly! (3 char lenght)")
continue
# thirth check day integer
try:
bdayinteger = int(bdayarray[1])
except:
print("Enter a day correctly!")
continue
birthdays[name] = bday
print(name + "'s birthday added to database. (" + bday + ")")
| true |
8d941369d1a3d3caa1b19dfb0a24e9fa6e740bc1 | blazehalderman/PythonAlgorithms | /ThreeNumberSum/threenumbersum.py | 765 | 4.34375 | 4 | """
Write a function that takes in a non-empty array of distinct integers and an
integer representing a target sum. The function should find all triplets in
the array that sum up to the target sum and return a two-dimensional array of
all these triplets. The numbers in each triplet should be ordered in ascending
order, and the triplets themselves should be ordered in ascending order with
respect to the numbers they hold.
"""
def threeNumberSum(array, targetSum):
found_sum = []
array.sort()
for i in range(len(array) - 2):
for j in range(1, len(array)):
for k in range(len(array) - 1, ):
if(array[i] + array[j] + array[k] == targetSum):
found_sum.append([array[i], array[j], array[k]])
j += 1
k -= 1
return(found_sum)
| true |
acb9969798a28f201ebba4e1262e75db79d86f69 | blazehalderman/PythonAlgorithms | /Two Number Sum/Two-Number-Sum.py | 597 | 4.1875 | 4 | """
Write a function that takes in a non-empty array of distinct integers and an
integer representing a target sum. If any two numbers in the input array sum
up to the target sum, the function should return them in an array, in any
order. If no two numbers sum up to the target sum, the function should return
an empty array."""
def twoNumberSum(array, targetSum):
# Write your code here.
sum_array = []
for i in range(len(array) - 1):
x = array[i]
print(str(x))
for j in range(i + 1, len(array)):
y = array[j]
if(x + y == targetSum):
return [x, y]
return [] | true |
0e998e3b9d5aaa520356a2ccdcaf14f61bc8a935 | SupriyaRadhakrishnan/Python_Learning | /FirstProject/ForLoopSample.py | 321 | 4.15625 | 4 |
friends = ["Jim" , "Karen" , "Joey"]
for letter in "My Acamedy" :
print(letter)
#prints from 0-9
for index in range(10) :
print(index)
#prints from 3-9
for index in range(3,10) :
print(index)
for friend in friends :
print(friend)
for i in range(len(friends)) :
print(friends[i])
print(i)
| false |
bacfee8695b0ea151fb60d82b4e308c17c798bb4 | apeterlein/A-Short-Introduction-To-Python | /AShortIntroductionToPython/9_Intro_To_Euler_Problems.py | 2,497 | 4.15625 | 4 | # A Short Introduction To Python
# FILE 9 - INTRO TO EULER PROBLEMS
# Adam Peterlein - Last updated 2019-01-29 with python 3.6.5 and Visual Studio 15.7.1.
# Any questions, suggestions, or comments welcome and appreciated.
# For the remainder of this tutorial series we will focus on something called "Euler problems."
# These are problems published on projecteuler.net designed specifically to be solved with computer
# code. They increase in difficulty as they go, and although I will be the first to admit that I am
# an engineer not a computer scientist and so my knowledge of effecient algorithms is limited, I hope
# that Euler problems as a learning tool will prove as helpful and fun to you as they have been to
# me.
# My intention for this file is to build a module that we can import in our solutions to both time
# our methods for finding the correct answer and to check the answer that we get. To that end we first
# import a timer from the time module.
from time import perf_counter as timer
from typing import Callable
# A list of the correct answers to problems, in order. No cheating!
answers = [
233168,
4613732,
6857
]
# Now we will define a class "Problem" this class will take two arguments, the first is the function
# that generates the answer, and the second is the number of the problem (beginning from 1) so we can
# check our answers.
class Problem:
def __init__(self, fun: Callable[[], float], num: int) -> None:
# Callable[[], float] just means the variable fun is a function that takes no inputs, and spits out a float.
self.fun = fun
self.num = num
# Our init function is very simple. It just takes the function and the number and attaches them to the
# instance of our class.
# Next we have the method that actually runs the function and returns 3 values. First the value the function
# returned, then the correct answer, then the time it took the function to get there.
def run(self) -> (float, float, float):
t = timer()
return self.fun(), answers[self.num-1], timer() - t
# Finally, we have a method outside our function that helps us display the results.
def display(ans: float, answer: float, time: float) -> None:
print("Result:\t", ans, "\nAnswer:\t", answer, "\n\t " + ("C" if ans == answer else "Inc") + \
"orrect\nTime:\t", time, "\n")
# Some things to note: "\t" represents a tab, "\n" represents a like break.
# End of file 9.
| true |
f9c881baee98ff82427dbe5b13a8d53e83386671 | rohira-dhruv/Python | /Blackjack/main.py | 2,657 | 4.125 | 4 |
from art import logo_blackjack
import os
import random
def clear():
"""This function is used to clear the terminal window for a better user experience"""
os.system('cls')
def deal_card():
"""This function returns a randomly drawn card from a deck of cards"""
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
return random.choice(cards)
def calculate_score(card_list):
"""This function returns the score of the hand dealt"""
if sum(card_list) == 21 and len(card_list) == 2:
return 0
elif sum(card_list) > 21 and 11 in card_list:
card_list.remove(11)
card_list.append(1)
return sum(card_list)
def compare(user_cards, dealer_cards):
"""This function compares the score between two set of cards and prints the result"""
if calculate_score(user_cards) == 0 or calculate_score(user_cards) == 21:
if calculate_score(dealer_cards) == 0 or calculate_score(dealer_cards) == 21:
print("It is a Draw!")
else:
print("BLACKJACK! You Win 🎉")
elif calculate_score(user_cards) < 21:
if calculate_score(dealer_cards) > 21:
print("The Computer went over. You Win 😁")
elif calculate_score(dealer_cards) < calculate_score(user_cards):
print("You Win 😃")
elif calculate_score(dealer_cards) == calculate_score(user_cards):
print("It is a Draw!")
else:
print("You Lose 😭")
else:
print("You went over. You Lose 😤")
def play_game():
print(logo_blackjack)
user_cards = []
dealer_cards = []
decision = 'y'
user_cards.append(deal_card())
dealer_cards.append(deal_card())
user_score = user_cards[0]
while decision == 'y' and user_score <= 21:
user_cards.append(deal_card())
user_score = calculate_score(user_cards)
print(f"\tYour cards: {user_cards}, current score is: {user_score}")
print(f"\tDealer's first card is: {dealer_cards[0]}")
if user_score <= 21:
decision = input("Type 'y' to get another card, 'n' to pass: ")
dealer_score = dealer_cards[0]
while dealer_score < 17:
dealer_cards.append(deal_card())
dealer_score = calculate_score(dealer_cards)
print(f"\tYour final hand is {user_cards} and the final score is: {user_score}")
print(f"\tComputer's final hand is {dealer_cards} and the final score is {dealer_score}")
compare(user_cards, dealer_cards)
while input("Do you want to play a game of Blackjack? Type 'y' for yes or 'n' for no: ").lower() == 'y':
clear()
play_game()
print("Thank you for playing!")
| true |
0d5af65d27b460db68f7d33f251e6c320783a649 | LeandroAzevedo-1/Listas_Dicion-rio_python | /Listas_ex_Valores_unicos.py | 1,461 | 4.25 | 4 | '''Crie um programa onde o usuário possa digitar vários VALORES NUMÉRICOS e cadastre-se
em uma LISTA. Caso o número já exista lá desntro, ele não será adcionado. No final
,serão exibidos todos os VALORES ÚNICOS digitados, em ordem CRESCENTE'''
'''Vamos criar uma lista que não sabemos quantos valores podem serem acrescentados'''
numeros = list()
while True:
n = int(input('Digite um valor: '))
if n not in numeros:
numeros.append(n)
print('Valor adcionado com sucesso...')
else:
print('Valor duplicado! Não vou adcionar...')
r = str(input('Quer continuar? [S/N] '))
if r in 'Nn':
break
print('-=' * 30) # linhas de resultados 30vezes
numeros.sort() #Esse comando coloca na ordem crescente
print(f'Você digitou os valores {numeros} ')
''' Respostas
Digite um valor: 9
Valor adcionado com sucesso...
Quer continuar? [S/N] s
Digite um valor: 2
Valor adcionado com sucesso...
Quer continuar? [S/N] s
Digite um valor: 3
Valor adcionado com sucesso...
Quer continuar? [S/N] s
Digite um valor: 9
Valor duplicado! Não vou adcionar...
Quer continuar? [S/N] s
Digite um valor: 40
Valor adcionado com sucesso...
Quer continuar? [S/N] s
Digite um valor: 15
Valor adcionado com sucesso...
Quer continuar? [S/N] s
Digite um valor: 10
Valor adcionado com sucesso...
Quer continuar? [S/N] n
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Você digitou os valores [2, 3, 9, 10, 15, 40]'''
| false |
61261f7f230376b91f30c878c441383af2f60d16 | evelandy/Remove-Headers-from-CSV-Files | /HeaderRemoveCSV.py | 1,171 | 4.15625 | 4 | #!/usr/bin/env python3
"""evelandy/W.G.
Nov. 3, 2018 7:31pm
Remove-Headers-from-CSV-Files
Python36-32
Removes Headers from .CSV files
"""
import csv
import os
# This makes a new folder in the directory that you input and leaves the one there if one exists
directory = input("Enter the directory for your .csv files: ") # Enter full path for the directory w/ no quotes
os.makedirs(directory, exist_ok=True)
# Loops through the files in the directory and skips the non .csv files
for csv_file in os.listdir('.'):
if not csv_file.endswith('.csv'):
continue
print("Working on {}".format(csv_file)) # Prints the finished header removal of each file
# Reads through the .csv file leaving out the first row
csv_rows = []
with open(csv_file) as csv_obj:
reader_obj = csv.reader(csv_obj)
for row in reader_obj:
if reader_obj.line_num == 1:
continue
csv_rows.append(row)
# Write out the csv file
with open(os.path.join('headerRemove', csv_file), 'w', newline='') as csv_obj:
csv_writer = csv.writer(csv_obj)
for row in csv_rows:
csv_writer.writerow(row)
| true |
083eb84db09598f89b5c2b12c4e919f72fd2cc3b | SwapnilBhosale/DSA-Python | /bit_manipulation/chek_pow_2.py | 937 | 4.625 | 5 | '''
Check whether given number is power of 2.
The logic is , if we AND the power of 2 number with the number one less that that,
the output will be zero
example: We are checking if 8 is power of 2
8 -> 1000
7 -> 0111
8 & 7 = 1 0 0 0
0 1 1 1
---------
0 0 0 0
'''
def check_power_two(num: int):
if num == 0:
return 0
if num & (num - 1) == 0:
return 1
return -1
output = {
1: "Number {} is power of two",
0: "Number is zero",
-1: "Number {} is not power of two"
}
assert (output[check_power_two(2)].format(2) == "Number 2 is power of two")
assert (output[check_power_two(6)].format(6) == "Number 6 is not power of two")
assert (output[check_power_two(0)] == "Number is zero")
assert (output[check_power_two(128)].format(128) == "Number 128 is power of two")
assert (output[check_power_two(15-15)].format(2) == "Number is zero") | true |
36e466e0b67dabeb375aebce6023f9ef35bc39ba | aaaaatoz/leetcode | /algorithms/python/powerofN.py | 770 | 4.1875 | 4 | """
Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
Example:
Given num = 16, return true. Given num = 5, return false.
Follow up: Could you solve it without loops/recursion?
Credits:
Special thanks to @yukuairoy for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
"""
class Solution(object):
def powerofN(self, number, power):
assert(power >= 2)
if number < power:
return False
elif number == power:
return True
elif number % power != 0:
return False
else:
return self.powerofN(int(number/power), power)
if __name__ == "__main__":
a = Solution()
print(a.powerofN(2,2)) | true |
763a9b03eb618d6b69a4b5b8a9f29cfff0ea5347 | shangpf1/python_study | /2017-11-30-01.py | 818 | 4.15625 | 4 | """
我的练习作业02-pytho 逻辑运算符
"""
a = 10
b = 20
if ( a and b ):
print ("line 1 - 变量 a 和 b 都为 true")
else:
print ("line 1 - 变量 a 和 b 有一个不为true")
if ( a or b ):
print ("line 2 - 变量 a 和 b 都为true,或其中一个变量为true ")
else:
print ("line 2 - 变量 a 和 b 都不为true")
# 修改变量 a 的值
a = 0
if ( a and b ):
print ("line 3 - 变量 a 和 b 都为true")
else:
print ("line 3 - 变量 a 和 b 有一个不为true")
if ( a or b ):
print ("line 4 - 变量 a 和 b 都为true,或其中一个变量为true")
else:
print ("line 4 - 变量 a 和 b 都不为true")
if not( a and b ):
print ("line 5 - 变量a 和 b 都为false,或其中一个变量为true")
else:
print ("line 5 - 变量 a 和 b 都为true") | false |
428811ce79e144a62db247e7776c4c36fb716bc8 | JAreina/python | /4_py_libro_1_pydroid/venv/4_py_libro_1_pydroid/COLECCIONES/py_10_collec_ordered_dict_1.py | 475 | 4.125 | 4 | '''
The OrderedDict is a subclass of the dictionary and it remembers the order in which the
elements are added:
'''
import collections
print ('Regular Dictionary'
)
d = {}
d['g']= "aaaa"
d['a']= 'SAS'
d['bbbb']= 'PYTHON'
d['c']= 'R'
for k,v in d.items():
print (k, ":",v
)
print( '\n Ordered dictionary'
)
d1 = collections.OrderedDict()
d1['a']= 'SAS'
d1['b']= 'PYTHON'
d1['c']= 'A'
for k,v in d1.items():
print (k, ":",v) | false |
ce978e0784cb039c045e88b380012bc85d08f3fd | JAreina/python | /3_py_libro_1/venv/py_7_operadores.py | 852 | 4.25 | 4 |
'''
MATEMATICOS
'''
print( 3 % 2)
print( 3.0 % 2)
print("DIVISION" ,3 / 2)
print("floor division", 3 // 2 ) # redondea hacia abajo
print(2 ** 2)
'''
prioridad operadores
parentesis
exponentes,
multiplicacion
division
suma
resta
'''
a = 2 + 2 * 5
print(a)
a = (2 + 2) * 5
print(a)
print (5 - 6 * 2)
print ((5 - 6) * 2)
print (3 ** 3 * 5) #135
print (3** (3 * 5)) # 14348907
'''
OPERADORES COMPARACION
'''
z = 5
y = 5
print ( z == y)
print( 10 == 10.0)
print( z != y )
#print( z <> y ) no soportado version 3.5
print( z > y )
print( z >= y )
z += 100
print( z )
'''
OPERADORES LOGICOS
'''
print("OPERADORES LOGICOS \n")
print(5 == 5 and 10 == 10) # true
print(5 == 5 and 7 < 6) # false
print(5 == 5 and 7 == 7 and 6 < 7) #v
print(5 == 5 or 7 < 6) # v
print(5 == 5 or 7 < 6 or 5 >10)##v
print(not (5 == 5))#f
print(not (5 == 6))#v | false |
bdfb06de8553a2b56cb68d014e23526387cab600 | SomyaRanjanMohapatra/DAY-14-SOLUTION | /DAY 14 SOLUTION.py | 258 | 4.125 | 4 | S=input("The original string is :")
nsub=input("\nThe substring you want to replace :")
nrep=input("\nThe string you want to use instead :")
nl=S.split()
for i in range(len(nl)):
if nsub == nl[i]:
nl[i]=nrep
n=" ".join(nl)
print("\n",n)
| false |
bd2a7b005121f31fe646f34ab4bdca6aca6a9662 | Amjad-hossain/algorithm | /basic/reverse_string.py | 1,246 | 4.625 | 5 | # /**
# * Reverse a string without affecting special characters
# * Given a string, that contains special character together with alphabets
# * (‘a’ to ‘z’ and ‘A’ 'Z’), reverse the string in a way that special characters are not affected.
# *
# * Examples:
# *
# * Input: str = "a,b$c"
# * Output: str = "c,b$a"
# * Note that $ and , are not moved anywhere.
# * Only subsequence "abc" is reversed
# * Write the function in such a way can be easily shared
# *
# * Input: str = "Ab,c,de!$"
# * Output: str = "ed,c,bA!$"
# **/
def reverse(string):
reverse_string = ""
count = len(string) - 1
for index, val in enumerate(string):
if not val.isalpha():
reverse_string = reverse_string + val
else:
while count >= 0:
count -= 1
if string[count + 1].isalpha():
reverse_string = reverse_string + string[count + 1]
break
return reverse_string
assert reverse("!!$!!,,,,!!!,,!") == "!!$!!,,,,!!!,,!"
assert reverse("abcd") == "dcba"
assert reverse("a,b$c") == "c,b$a"
assert reverse("Ab,c,de!$") == "ed,c,bA!$"
assert reverse("ab,c,d!") == "dc,b,a!"
assert reverse("$ab,c,d!") == "$dc,b,a!"
| true |
428c32f4557f6d8d903a785ea2e3944e5b325b20 | euphwes/Project-Euler-Python | /problems/problem_9.py | 989 | 4.40625 | 4 | """
Special Pythagorean triplet
---------------------------
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
"""
from utils.timer import time_it
#-------------------------------------------------------------------------------------------------
def is_pythagorean_triplet(a,b,c):
""" Determine if the provided arguments form a Pythagorean triplet: a^2 + b^2 == c^2 """
return pow(a,2) + pow(b,2) == pow(c,2)
@time_it
def problem_9():
for a in range(3, 500):
for b in range(3, 500):
c = 1000 - a - b
if is_pythagorean_triplet(a,b,c) and (a + b + c == 1000):
print(a*b*c)
return
#-------------------------------------------------------------------------------------------------
if __name__ == '__main__':
problem_9()
| false |
63f4ed10ed7f58c2c2f0b8f2c531f270ad12894e | euphwes/Project-Euler-Python | /problems/problem_38.py | 1,833 | 4.15625 | 4 | """
Pandigital multiples
--------------------
Take the number 192 and multiply it by each of 1, 2, and 3:
192 × 1 = 192
192 × 2 = 384
192 × 3 = 576
By concatenating each product we get the 1 to 9 pandigital, 192384576.
We will call 192384576 the concatenated product of 192 and (1,2,3)
The same can be achieved by starting with 9 and multiplying by 1, 2, 3, 4, and 5, giving the
pandigital, 918273645, which is the concatenated product of 9 and (1,2,3,4,5).
What is the largest 1 to 9 pandigital 9-digit number that can be formed as the concatenated
product of an integer with (1,2, ... , n) where n > 1?
"""
from utils import is_pandigital
from utils.timer import time_it
#-------------------------------------------------------------------------------------------------
def concatenated_product(n):
""" Calculates the 'concatenated product' of n as defined in the problem description above.
Makes sure that the concatenated product is at least 9 digits, so there it is a candidate for
being pandigital. """
# start off with the digits of n
digits = str(n)
# concatenate the digits of n * x, where x = 2, 3, 4 ...
x = 2
while len(digits) < 9:
digits += str(n*x)
x += 1
# return the number itself
return int(digits)
@time_it
def problem_38():
# Get a list of concatenated products from n=1 to n=10^4 (upper limit established
# experimentally), and filter so only the pandigital numbers remain. Sort them so the largest
# is the last item, and pop that.
candidates = [concatenated_product(n) for n in range(10**4)]
candidates = sorted(filter(is_pandigital, candidates))
print(candidates.pop())
#-------------------------------------------------------------------------------------------------
if __name__ == '__main__':
problem_38()
| true |
50a19f4ee8a2ec28b9281bce67ed39693ea93574 | katsuunhi/PythonExercises | /ex3.py | 673 | 4.125 | 4 | # 三、猜数字的AI
# 和猜数字一样,不过这次是设计一个能猜数字的AI。
# 功能描述:用户输入一个单位以内的数字,AI要用最少的次数猜中,并且显示出猜的次数和数字。
import random
digit = int(input("input a digit:"))
times = 0
answer = 100//2
middle = 100//4
times = times + 1
while digit != answer:
if answer < digit:
print(answer, " too small")
answer = answer + middle
times = times + 1
if answer > digit:
print(answer, " too big")
answer = answer - middle
times = times + 1
middle = middle//2
if middle == 0:
middle = 1
print(answer, " is right! you have tried for ", times, " times!")
| false |
4b419589c596829305b2cb76999ea64a59c207ac | translee/learn_python_answers | /even_or_odd.py | 219 | 4.1875 | 4 | number=input("Enter a number.and I'll tell you if it's even or odd: ")
number=int(number)
if number%2==0:
print("\nThe number "+str(number)+" is even.")
else:
print("\nThe number "+str(number)+" is odd.")
| true |
99b3bde0232a3f0fb8fd7188f738de98671bfb1a | mkvenkatesh/CrackTheCode | /Stack & Queue/three_in_one.py | 2,599 | 4.4375 | 4 | # Describe how you could use a single array to implement three stacks.
# push top of the array, pop top of the array, peek top of the array, is_empty() - O(1)
# solutions
# 1. use array of arrays
# 2. if you have a fixed size array, divide by 3 and use modulo to define the
# lower and upper limits of each stack. use three top pointers to represent
# where the top of each stack would be
# 3. above is fixed but you can also make it variable by shifting the elements
# when more space is needed for a stack and making the array circular
class Stack:
STACK_SIZE = 3
NUM_STACKS = 3
stack_array = []
stack_ctr = 0
def __init__(self):
if Stack.stack_ctr < self.NUM_STACKS:
self.stack_start = Stack.stack_ctr * self.STACK_SIZE
self.stack_end = self.stack_start + self.STACK_SIZE
self.top = self.stack_start
Stack.stack_ctr += 1
else:
raise OverflowError("No more stacks can be created")
def push(self, item):
if self.top >= self.stack_end:
raise OverflowError("No more space in stack. Pop some elements before pushing them")
else:
Stack.stack_array.append(item)
self.top += 1
def pop(self):
if self.top <= self.stack_start:
raise OverflowError("Stack is empty. No elements to pop")
else:
self.top -= 1
return Stack.stack_array[self.top]
def peek(self):
if self.top < self.stack_start:
raise OverflowError("Stack is empty. No elements to peek")
else:
return Stack.stack_array[self.top]
def is_empty(self):
return self.top == self.stack_start
def __str__(self):
print_str = ["Stack: "]
for i in range(self.stack_start, self.top):
print_str.append(str(Stack.stack_array[i]))
if i < self.top - 1:
print_str.append(", ")
if len(print_str) == 1:
return "Stack is empty"
else:
return "".join(print_str)
s1 = Stack()
s2 = Stack()
s3 = Stack()
s1.push(10)
s1.push(20)
s1.push(30)
print(s1)
print("Pop element: ", s1.pop())
print("Pop element: ", s1.pop())
print("Pop element: ", s1.pop())
print(s1)
s2.push(10)
s2.push(20)
s2.push(30)
print(s2)
print("Pop element: ", s2.pop())
print("Pop element: ", s2.pop())
print("Pop element: ", s2.pop())
print(s2)
s3.push(10)
s3.push(20)
s3.push(30)
print(s3)
print("Pop element: ", s3.pop())
print("Pop element: ", s3.pop())
print("Pop element: ", s3.pop())
print(s3) | true |
1fff0364d53459a4d557796e07f73e0741c68fef | mkvenkatesh/CrackTheCode | /Linked List/delete_middle_node.py | 1,316 | 4.15625 | 4 | # Implement an algorithm to delete a node in the middle (i.e., any node but the
# first and last node, not necessarily the exact middle) of a singly linked
# list, given only access to that node.
# EXAMPLE
# Input:the node c from the linked list a->b->c->d->e->f
# Result: nothing is returned, but the new linked list looks like a->b->d->e->f
# questions
# 1. does the node that you are given access to, can it be the first node?
# 2. are you given the length of the linked list?
# examples
# a | a->b : no deletion.
# a->b->c: only b can b deleted
# a->b->c->d: b or c can be deleted
# solution Assumption: you are not given the first node
# 1. given a node, check if node.next is none and return else, get node.next.val
# and store it in node.val inc ptr to next node and repeat the same. store
# reference to previous pointer as well when node.next is done, go back to
# prev pointer and set prev.next to none
from linked_list import LinkedList
class Solution1:
def delete_middle_node(self, node):
if node == None or node.next == None:
return
else:
node.val = node.next.val
node.next = node.next.next
return
ll = LinkedList([5, 4, 3, 2, 1])
s = Solution1()
print(ll)
s.delete_middle_node(ll.head.next.next.next.next)
print(ll)
| true |
7a8165c6de5b7c049c8ff0ab2f34bb61fd47b5cb | mkvenkatesh/CrackTheCode | /Trees & Graphs/validate_bst_recrusion.py | 1,562 | 4.25 | 4 | # Implement a function to check if a binary tree is a binary search tree.
# example 1
# 10
# 4 17
# 3 5 11 18
# example 2
# 10
# 4 17
# 3 5 6 18
# solution
# 1. maintain two vars - MIN and MAX that you keep updating as you traverse down
# the tree. Moving to the left, update Max var and moving to the right update
# MIN var. Compare this min and max with the node value as you visit each
# node. If the node value is between min and max, return True else false
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
class BinaryTree:
def __init__(self, root):
self.root = root
def is_bst(self, root, min_val=None, max_val=None):
if root == None:
return True
else:
if not self.is_bst(root.left, min_val, root.data):
return False
if not self.is_bst(root.right, root.data, max_val):
return False
if min_val == None and max_val == None:
return True
elif min_val == None and root.data < max_val:
return True
elif max_val == None and min_val <= root.data:
return True
elif min_val <= root.data < max_val:
return True
else:
return False
n0 = Node(10)
n0.left = Node(4)
n0.right = Node(17)
n0.left.left = Node(3)
n0.left.right = Node(11)
b = BinaryTree(n0)
print(b.is_bst(n0)) | true |
ba6827952b6e40869c6df721fcb32333cd8f6daa | mkvenkatesh/CrackTheCode | /Trees & Graphs/check_balanced.py | 2,420 | 4.21875 | 4 | # check balanced - Implement a function to check if a binary tree is balanced.
# For the purposes of this question, a balanced tree is defined to be a tree
# such that the heights of the two subtrees of any node never differ by more
# than one.
# examples
# 9
# 8 7
# 6 5 1 8
# 1 4 4 6
# 1
# solutions
# 1. For each node, do dfs on left and right subtree and get the max level on each
# and compare the difference. If it's more than 1 for any node it's not balanced - O(n^2)
from queue import Queue
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
class BinaryTree:
def __init__(self, root):
self.root = root
def get_level_by_bfs(self, node):
if node != None:
q = Queue()
q.put((node,0))
max_lvl = 0
while not q.empty():
popped_val = q.get()
node = popped_val[0]
depth = popped_val[1]
if node.left != None:
q.put((node.left, depth+1))
if node.right != None:
q.put((node.right, depth+1))
if max_lvl < depth:
max_lvl = depth
return max_lvl
else:
return 0
def is_balanced(self, node):
if node != None:
left_depth = self.get_level_by_bfs(node.left)
right_depth = self.get_level_by_bfs(node.right)
if abs(left_depth - right_depth) > 1:
return False
if node.left != None:
return self.is_balanced(node.left)
if node.right != None:
return self.is_balanced(node.right)
return True
# 9
# 8 7
# 6 5 1 8
# 1 4 4 6 6 2 1
# 1
n0 = Node(9)
n0.left = Node(8)
n0.right = Node(7)
n0.left.left = Node(6)
n0.left.right = Node(5)
n0.right.left = Node(1)
n0.right.right = Node(8)
n0.left.left.left = Node(1)
n0.left.left.right = Node(4)
n0.left.right.left = Node(4)
n0.left.right.right = Node(6)
#n0.right.left.left = Node(6)
#n0.right.left.right = Node(2)
#n0.right.right.left = Node(1)
# n0.right.right.right = Node(0)
n0.left.right.right.right = Node(1)
b = BinaryTree(n0)
print("Balanced Tree: ", b.is_balanced(n0)) | true |
a39775a0b1be47236a09fb74e26f06e45d79442b | jsdeveloper63/Python-Sqlite | /ConditionSearchGet.py | 1,062 | 4.375 | 4 | import sqlite3
#Create the database
conn = sqlite3.connect("Electricity.db")
#Cursor method is used to go through the database
c = conn.cursor()
#Select individual column from the table
#c.execute("SELECT period FROM electricity")
#Prints/Gives data from all columns
#c.execute("SELECT * FROM electricity")
#data = c.fetchall()
#print(data)
#To Select some specific chunk of data
#Selects the 2 rows of data after offsetting / skipping the first 10 rows
#c.execute("SELECT * FROM electricity LIMIT 2 OFFSET 10")
#data = c.fetchall()
#print(data)
#Gives the data in order
#c.execute("SELECT * FROM electricity ORDER BY vicprice")
#data = c.fetchmany(size=20)
#print(data)
#Using ASCI / DESC print the data in ascending or descending order
#c.execute("SELECT * FROM electricity ORDER BY vicprice ASC")
#data = c.fetchone()
#print(data)
#To retreive distinct values in case we have replicate data
#c.execute("SELECT DISTINCT date FROM electricity")
#data = c.fetchall()
#for i in data:
# print(data)
conn.commit()
c.close()
conn.close()
| true |
dbe87a4561b3faf45aa1ab441173161cfd9ce755 | Alwayswithme/LeetCode | /Python/092-reverse-linked-list-ii.py | 1,193 | 4.1875 | 4 | #!/bin/python
#
# Author : Ye Jinchang
# Date : 2015-09-14 23:56:48
# Title : 092 reverse linked list ii
# Reverse a linked list from position m to n. Do it in-place and in one-pass.
#
# For example:
# Given 1->2->3->4->5->NULL, m = 2 and n = 4,
#
# return 1->4->3->2->5->NULL.
#
# Note:
# Given m, n satisfy the following condition:
# 1 ≤ m ≤ n ≤ length of list.
#
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseBetween(self, head, m, n):
"""
:type head: ListNode
:type m: int
:type n: int
:rtype: ListNode
"""
dummy = ListNode(0)
dummy.next = head
prev, current = dummy, head
# find begin
i = 1
while current and i != m:
i += 1
prev, current = current, current.next
begin_prev, begin = prev, current
while current and i <= n:
i += 1
current.next, prev, current = prev, current, current.next
begin.next, begin_prev.next = current, prev
return dummy.next
| false |
39441d61b7d370db5d9092b149b224ea9d02eacb | Alwayswithme/LeetCode | /Python/116-populating-next-right-pointers-in-each-node.py | 1,835 | 4.1875 | 4 | #!/bin/python
#
# Author : Ye Jinchang
# Date : 2015-10-08 13:23:10
# Title : 116 populating next right pointers in each node
# Given a binary tree
#
# struct TreeLinkNode {
# TreeLinkNode *left;
# TreeLinkNode *right;
# TreeLinkNode *next;
# }
#
# Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
#
# Initially, all next pointers are set to NULL.
#
# Note:
#
# You may only use constant extra space.
# You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).
#
# For example,
# Given the following perfect binary tree,
#
# 1
# / \
# 2 3
# / \ / \
# 4 5 6 7
#
# After calling your function, the tree should look like:
#
# 1 -> NULL
# / \
# 2 -> 3 -> NULL
# / \ / \
# 4->5->6->7 -> NULL
# Definition for binary tree with next pointer.
# class TreeLinkNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# self.next = None
class Solution(object):
def connect(self, root):
"""
:type root: TreeLinkNode
:rtype: nothing
"""
if not root:
return
nodes = [root]
while nodes:
self.connectNode(nodes)
size = len(nodes)
for i in range(size):
n = nodes[i]
if n.left:
nodes.append(n.left)
if n.right:
nodes.append(n.right)
nodes = nodes[size:]
def connectNode(self, nodes):
pre = None
for i in reversed(nodes):
i.next = pre
pre = i
| true |
7c3b522f1f6a70dd4f718297f4077801f2664f6f | Alwayswithme/LeetCode | /Python/098-validate-binary-search-tree.py | 1,134 | 4.15625 | 4 | #!/bin/python
#
# Author : Ye Jinchang
# Date : 2015-09-17 20:10:24
# Title : 098 validate binary search tree
# Given a binary tree, determine if it is a valid binary search tree (BST).
#
# Assume a BST is defined as follows:
#
# The left subtree of a node contains only nodes with keys less than the node's key.
# The right subtree of a node contains only nodes with keys greater than the node's key.
# Both the left and right subtrees must also be binary search trees.
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
bignum = 1 << 63
return self.isValid(-bignum, bignum, root)
def isValid(self, left, right, node):
if not node:
return True
v = node.val
if v <= left or v >= right:
return False
return self.isValid(left, v, node.left) and self.isValid(v, right, node.right)
| true |
78d1084a4dcf796b06973f9f66fc737a51737b20 | tahabroachwala/hangman | /ExternalGuessingGame.py | 1,109 | 4.28125 | 4 | # The Guess Game
# secret number between 1 and 100
import random
randomNumber = random.randrange(1, 100) # changed from 10 to 100
#print randomNumber #check if it's working
# rules
print('Hello and welcome to the guess game !')
print('The number is between 1 and 100')
guesses = set() # your set of guesses
guessed = False
tries = 0 # no need add 1 to the tries here
while guessed == False:
userInput = int(input("Please enter your guess: "))
if userInput not in guesses: # if it's not in our set
tries += 1 # increase the tries
guesses.add(userInput) # add it to our set
if userInput == randomNumber:
guessed = True
tries = str(tries)
print("Congratulations ! You win after " + tries + " tries ! ")
elif userInput > 100 or userInput < 1:
print("The guess range is between 1 and 100, please try again")
elif userInput > randomNumber:
print("Your guess is too large")
elif userInput < randomNumber:
print("Your guess is too small")
print("End of the game, please play again")
| true |
179b10a76d7f45d72b940df327b3130df69c6aac | mrmufo/learning-python | /dates-and-datetime/challenge.py | 2,824 | 4.1875 | 4 | # Create a program that allows a user to choose one of
# up to 9 time zones from a menu. You can choose any
# zones you want from the all_timezones list.
#
# The program will then display the time in that timezone, as
# well as local time and UTC time.
#
# Entering 0 as the choice will quit the program.
#
# Display the dates and times in a format suitable for the
# user of your program to understand, and include the
# timezone name when displaying the chosen time.
import datetime
import pytz
menu = {1: "Andorra",
2: "Burundi",
3: "Belarus",
4: "Iran",
5: "St Kitts & Nevis",
6: "Maldives",
7: "Poland",
8: "Palau",
9: "Great Britain"}
menu_tz = {1: "Europe/Andorra",
2: "Africa/Bujumbura",
3: "Europe/Minsk",
4: "Asia/Tehran",
5: "America/St_Kitts",
6: "Indian/Maldives",
7: "Europe/Warsaw",
8: "Pacific/Palau",
9: "Europe/London"}
chosenCountry = 10
while True:
for each in menu:
print("{number}: {country}".format(number=each, country=menu.get(each)), end=', ')
chosenCountry = int(input("\nChoose a number of the country to see its time: (0 to quit)\n"))
if chosenCountry == 0:
break
if chosenCountry in menu.keys():
# ============== MY SOLUTION ===================
# countryTimeZone = pytz.timezone(menu_tz.get(chosenCountry))
# local_time = pytz.utc.localize(datetime.datetime.now()).astimezone()
# utc_time = pytz.utc.localize(datetime.datetime.utcnow()).astimezone()
# countryTime = local_time.astimezone(countryTimeZone)
#
# print("=" * 100)
# print("Your local time:\t{lt}, time zone {lttz} \nUTC time:\t\t\t{utc}, time zone {utctz}\n"
# "Time in {country}:\t\t{ct}, time zone {ctz}"
# .format(lt=local_time, lttz=local_time.tzinfo, utc=utc_time, utctz=utc_time.tzinfo,
# country=menu.get(chosenCountry), ct=countryTime, ctz=countryTime.tzinfo))
# print("=" * 100)
# ===============================================
country_tz = pytz.timezone(menu_tz.get(chosenCountry))
local_time = datetime.datetime.now().strftime('%A %x %X')
utc_time = datetime.datetime.utcnow().strftime('%A %x %X')
country_time = datetime.datetime.now(tz=country_tz)
print("=" * 100)
print("Your local time:\t{lt}\n"
"UTC time:\t\t\t{utc}\n"
"Time in {country}:\t\t{ct}, time zone {ctz}"
.format(lt=local_time, utc=utc_time, country=menu.get(chosenCountry),
ct=country_time.strftime('%A %x %X %z'), ctz=country_time.tzname()))
print("=" * 100)
else:
print("Wrong input, try again")
| true |
e7ca99c8556e63e0ab6dc1ab1d0a951cfad3feab | LGMart/USP-CC-Python | /4-Ex1-FizzBuzz.py | 724 | 4.25 | 4 | #Escreva a função fizzbuzz que recebe como parâmetro um número inteiro e retorna
#'Fizz' se o número for divisível por 3 e não for divisível por 5;
#'Buzz' se o número for divisível por 5 e não for divisível por 3;
#'FizzBuzz' se o número for divisível por 3 e por 5;
#Caso a função não seja divisível 3 e também não seja divisível por 5, ela deve retornar o número recebido como parâmetro.
def fizzbuzz (Numero):
if (Numero % 3) == 0 and (Numero % 5) != 0:
return ("Fizz")
elif (Numero % 5) == 0 and (Numero % 3) != 0:
return ("Buzz")
elif (Numero % 5) == 0 and (Numero % 3) == 0:
return ("FizzBuzz")
else:
return (Numero)
Numero = int(input("Entre com um numero: "))
fizzbuzz(Numero)
| false |
6f998d7918322d4c8934e7a690cbf10e8e59eb7e | imranmohamed1986/cs50-pset01 | /pset6/caesar/caesar.py | 1,469 | 4.125 | 4 | from cs50 import get_string
from sys import argv
def main():
key = get_key()
plaintext = get_plaintext("plaintext: ")
print("ciphertext:", encipher_text(plaintext, key))
# Get key
def get_key():
# Check if program was executed with an argument and only one
# If yes, produce an int from it
if len(argv) == 2:
return int(argv[1])
# If not, print error msg and exit with code 1
else:
print("Usage: python caesar.py key")
exit(1)
# Get plaintext
def get_plaintext(prompt):
return get_string(prompt)
# Encipher text
# Preserve case
# Non-alphabetical characters remain the same
# ord() takes a char and returns an int representing its unicode code value
# chr() takes an int and returns a char if that int is a unicode code value
def encipher_text(text, key):
# Create empty string to append characters to
str = ""
for char in text:
if not char.isalpha():
# Append c as is if non-alphabetical
str += char
# p(i) = ord(c) - ASCII_OFFSET
# c(i) = (p(i) + key) % 26
# chr(c(i) + ASCII_OFFSET)
if char.isupper():
# if uppercase, ASCII_OFFSET = 65
str += chr(((ord(char) - 65) + key) % 26 + 65)
if char.islower():
# if lowercase, ASCII_OFFSET = 97
str += chr(((ord(char) - 97) + key) % 26 + 97)
# return complete string
return str
if __name__ == "__main__":
main() | true |
bbecc9c3de6b21ecc7981e6da0d1c37a7937b792 | Topazoo/Machine_Learning | /collab_filter/euclid_dist/euclid_dist.py | 1,964 | 4.34375 | 4 | from math import sqrt
import recommendations
'''Code for calculating Euclidean Distance scores.
Two preferences are mapped on axes to determine
similarities'''
def distance(y1, y2, x1, x2):
'''Calculating Distance:
1. Take the difference in each axis
2. Square them
3. Add them
4. Take the sqaure root of the sum
Returns a score between 0 (opposite) and 1
(identical)'''
dist = sqrt(pow(y1 - y2, 2)+pow(x1 - x2, 2))
'''Invert distance so higher values mean higher
similarities'''
inv_dist = 1/(1 + dist)
return inv_dist
def calc_sim(pref_dict, cat1, cat2):
'''Calculates the similarity between two categories
and returns a Euclidean Distance score between 0
(opposite) and 1 (identical)
@pref_dict: A dictionary of categories containing
dictionaries of items and scores.
@cat1: The first category to compare items from.
@cat2: The category to compare items 2.'''
shared = {} #Hold the items shared by both categories
dist_scores = []
'''Store all items that are in both categories'''
for item in pref_dict[cat1]:
if item in pref_dict[cat2]:
shared[item] = 1
'''If there are no shared items return 0'''
if len(shared) == 0:
return 0
'''Calculate the Euclidean Distance of all shared
items and sum them using a list comprehension'''
for item in shared:
score = pow(pref_dict[cat1][item]-pref_dict[cat2][item],2)
dist_scores.append(score)
score_sum = sum(dist_scores)
# dist_scores = sum([pow(pref_dict[cat1][item]-pref_dict[cat2][item],2)
# for item in shared])
'''Invert the sum'''
invert_dist = 1/(1+sqrt(score_sum))
return invert_dist
print calc_sim(recommendations.critics, 'Lisa Rose', 'Gene Seymour')
print calc_sim(recommendations.critics, 'Lisa Rose', 'Claudia Puig')
| true |
0e16302bcec94857f4f3bae43d638df597f8b191 | Haridhakshini/Python | /selectionsort.py | 674 | 4.28125 | 4 | #Program for Selection Sort
#Array Input
array_num = list()
num = raw_input("Enter how many elements in the array:")
print "Enter elements in the array: "
for i in range(int(num)):
n = raw_input("num :")
array_num.append(int(n))
#Selection Sort function
def selectionsort(array_num):
for slot in range(len(array_num)-1,0,-1):
locationofmax=0
for location in range(1,fillslot+1):
if array_num[location]>array_num[locationofmax]:
locationofmax = location
temp = array_num[slot]
array_num[slot] = array_num[locationofmax]
array_num[locationofmax] = temp
selectionsort(array_num)
print(array_num)
| true |
1c66c415554e0d1d60effecd3ecd42ce7165551e | amanewgirl/set09103 | /Python_Tutorials_Continued/exercise16.py | 638 | 4.25 | 4 | #Exercise 16 from Learn Python the Hard way- Reading and writing
from sys import argv
script, filename = argv
print "Opening the file: "
target = open(filename, 'w')
print "Now I'm going to ask you for three lines."
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
print "I'm going to write this to the file %s." %filename
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
print "This end the writing segment of this exercise, please hold on for other options"
print "In the mean time I will close this file"
target.close()
| true |
7dc0ccdce064edf0d8cda6eaf90ec44a73da1416 | frapimoneto/CodeStart | /Aula_1/3.py | 405 | 4.3125 | 4 | '''
Faca um programa em Python que recebe tres
numeros e calcule sua media.
'''
# Recebe os numeros do teclado:
n1 = input ("Informe o primeiro numero: ")
n2 = input ("Informe o segundo numero: ")
n3 = input ("Informe o terceiro numero: ")
# Converte para numerico:
n1 = float (n1)
n2 = float (n2)
n3 = float (n3)
# Escreve a media na tela:
media = (n1 + n2 + n3) / 3.0
print (media)
| false |
0c53d752d09b426a810792bbc244d653a775e55f | Tarun-coder/Data-science- | /table14.py | 597 | 4.15625 | 4 | # Print multiplication table of 14 from a list in which multiplication table of 12 is stored.
number=int(input("Enter the number to Find Table of: "))
table=[]
for i in range(1,11,1):
numb=number*i
table.append(numb)
print("Table of Number",number,"is",table)
print("---------------table of 2---------------------")
number_1=int(input("Enter the number to Find Table of: "))
table_2=[]
for i in range(1,11,1):
numb_1=number_1*i
table_2.append(numb_1)
print("Table of Number",number_1,"is",table_2)
for i in range(10):
new=table[i]+table_2[i]
print("14 x",i+1,"=",new) | true |
889d67897848f4b7ec25397bfb6825378fbc7cc5 | Tarun-coder/Data-science- | /evenno.py | 509 | 4.21875 | 4 | # Write a Python function to print the even numbers from a given list.
a =int(input("Enter the size of the list : " ))
li=[]
for i in range(a):
number=int(input("Enter the Number to add into list: "))
li.append(number)
print("The value of the list",li)
print("The Final list is :",li)
print("-------------------------Even number list from original list---------------------------")
even=[]
for i in li:
if i%2==0:
even.append(i)
print("The Even list is:",even)
| true |
933286a486e6e386fac2064ae8616225f6bf4817 | Tarun-coder/Data-science- | /function9.py | 237 | 4.1875 | 4 | # Print multiplication table of 12 using recursion.
num=int(input("Enter the Number:"))
def mult12(num,i=1):
if i<11:
mul=num*i
print(num,"x",i,"=",mul)
i+=1
mult12(num,i)
mult12(num) | false |
97dbe152ca65123ee746e5ec222aec6f51cc0cd8 | Tarun-coder/Data-science- | /Roman2.py | 461 | 4.3125 | 4 | # Write a Python script to check if a given key already exists in a dictionary.
new={1:"one",2:"two",3:"Three",4:"Four",5:"Five",6:"Six",7:"Seven",8:"Eight",9:"Nine",10:"Ten"}
keys=[1,2,3,4,5,6,7,8,9,10]
values=["one","two","Three","Four","Five","Six","Seven","Eight","Nine","Ten"]
number=int(input("Enter the Key : "))
if number in keys:
print("This key already exist in Dictionary")
else:
print("It is a New Key and not found in the Dictionary")
| true |
b526c782ab5c09113d16827fcf81e8eb7d8da8eb | Tarun-coder/Data-science- | /function7.py | 358 | 4.25 | 4 | # Write a function to calculate area and perimeter of a rectangle.
lenth=int(input("Enter the Lenth of Rectangle:"))
width=int(input("Enter the Breadth of the Rectangle:"))
def rectangle(lenth,width):
print("The Permiter of the Rectangle is:",2*lenth+2*width,"cm")
print("The Area of the Rectangle is:",lenth*width,"cm*2")
rectangle(lenth,width) | true |
76dbfeb357c5f237f3c1c803ed110fca8807b5cf | Tarun-coder/Data-science- | /tempcon.py | 762 | 4.53125 | 5 | # If we want to Print the value from farenheit to celsius
Converter=input("Enter the Converter Name: ")
print("The Converter Selected is : ",Converter)
if Converter=="cels to far":
celscius=int(input("Enter the Temperature in celscius : "))
farenheit=(celscius*9/5)+32
print("The Value in Farenheit is {}F:".format(farenheit))
elif Converter=="far to cels":
farenheit=int(input("Enter the Temperature in Farenheit : "))
celscius=5*(farenheit-32/9)*5/9
print("The Value in the Celscius is :{}C ".format(celscius))
else:
print("oops!! Please Enter the valid name of Converter from the two option:")
print("1. From Farenheit to Celscius as: far to cels")
print("2. From Celscius to Farenheit as: cels to far")
| true |
5231ad5e30fdb1102c98f309ab30c80a37f257e0 | Tarun-coder/Data-science- | /functionq 5.py | 465 | 4.15625 | 4 | a=int(input("Enter the Number a: "))
b=int(input("Enter the Number b: "))
c=int(input("Enter the Number c: "))
def findmax(a,b,c):
if a==b==c:
print("All are Equal")
exit()
if a>b:
if a>c:
print("a is Greater than all")
else:
print("c is Greater than all")
elif b>c:
print("b is Greater than all")
else:
print("c is greater than all ")
findmax(a,b,c) | true |
8f2994a49203bc8dcae758fad8fd848dc212c7b9 | NikaZamani/ICS3U-Unit3-03-Python-Number_Guessing_Game | /Number_Guessing_Game.py | 808 | 4.28125 | 4 |
#!/usr/bin/env python3
# Created by: Nika Zamani
# Created on: April 2021
# This program will generate a random number between 0 and 9
# and then checks if it matches the right number.
import random
def main():
# this function generates a random number between 0 and 9
random_number = random.randint(0, 9) # a number between 0 and 9
# input
print('The randomly generated number is: ', random_number)
# process & output
if random_number == 5:
print("Number generated matches the random number !!")
print("")
print("Done.")
else:
print("Number generated does not matche the random number,")
print("Number generated that matches the random number is 5 !!")
print("")
print("Done.")
if __name__ == "__main__":
main()
| true |
260332aa405a51e0666c247002196d69b8e959ba | zhubiaook/python | /syntax/built_in_functions/filter_function.py | 852 | 4.21875 | 4 | """
filter(function, iterable)
function: 函数
iterable: 可迭代对象
filter()用于过滤iterable, 返回符合function条件的可迭代对象
iterable的每个元素作为function的参数传入,进行判断,然后返回True或False
最后将返回True的元素形成一个可迭代对象。
Version: 0.1
Author: slynxes
Date: 2019-01-13
"""
def odd_list(list_data):
"""
过滤出列表中所有的奇数
:param list_data:
:return: 奇数列表
"""
return list(filter(lambda x: x % 2 == 1, list_data))
def is_positive(num):
"""
判断是否大于0
:param num:
:return:
"""
return num > 0
def positive_list(list_data):
"""
过滤出列表中所有正数
:param list_data:
:return: 正数列表
"""
return list(filter(is_positive, list_data))
| false |
3950ced96153a601310a17980f9031013b82d59d | shafirpl/InterView_Prep | /Basics/Colt_Data_structure/Queue/Queue.py | 1,196 | 4.125 | 4 | class Node:
def __init__(self, val):
self.val = val
self.next = None
# in java, use a LinkedList class, use add method (compared to push method which
# adds item at the front/head) to enqueue/add item to the end, and pop to remove item from head/front/begining
class Queue:
def __init__(self):
self.head = None
self.length = 0
self.tail = None
# for enqueuing, we add at the end
def enqueue(self, val):
new_item = Node(val)
if self.length == 0:
self.length += 1
self.head = new_item
self.tail = new_item
return
self.tail.next = new_item
self.tail = new_item
self.length += 1
return
# for dequeing remove item from the beginning
def dequeue(self):
if self.length == 0:
return None
if self.length == 1:
self.length = 0
removed_item = self.head
self.head = None
self.tail = None
return removed_item.val
removed_item = self.head
self.head = removed_item.next
removed_item.next = None
return removed_item.val
| true |
e370ad016d1c193084a224df6a3f8f347b4ac595 | weak-head/leetcode | /leetcode/p0023_merge_k_sorted_lists.py | 1,743 | 4.125 | 4 | from queue import PriorityQueue
from typing import List
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def mergeKLists(lists: List[ListNode]) -> ListNode:
"""
Divide And Conquer
Time: O(n * log(k))
n - total number of nodes
k - total number of linked lists
"""
if not lists:
return None
def merge_two(l1: ListNode, l2: ListNode) -> ListNode:
head = node = ListNode(None)
while l1 and l2:
if l1.val < l2.val:
node.next = l1
l1 = l1.next
else:
node.next = l2
l2 = l2.next
node = node.next
node.next = l1 if l1 else l2
return head.next
n = len(lists)
while n > 1:
res = []
for i in range(0, n, 2):
l1 = lists[i]
l2 = lists[i + 1] if i + 1 < n else None
res.append(merge_two(l1, l2))
lists, n = res, len(res)
return lists[0]
# -----------------------------------------------
# -- Much slower solution using priority queue --
class PriorityEntry(object):
def __init__(self, priority, data):
self.data = data
self.priority = priority
def __lt__(self, other):
return self.priority < other.priority
def mergeKLists_pq(lists):
"""Priority Queue"""
head = current = ListNode(None)
q = PriorityQueue()
for node in lists:
if node:
q.put(PriorityEntry(node.val, node))
while not q.empty():
current.next = q.get().data
current = current.next
if current.next:
q.put(PriorityEntry(current.next.val, current.next))
return head.next
| true |
fde9c44a1de285bb11bb2d24b3e07c5c74747022 | weak-head/leetcode | /leetcode/p0212_word_search_ii.py | 2,581 | 4.125 | 4 | from typing import List
def findWords_optimized(board: List[List[str]], words: List[str]) -> List[str]:
"""
Backtracking with trie and multiple optimizations
to prune branching
Time: O(r * c * (3 ** l))
Space: O(l)
r - number of rows
c - number of cols
l - max length of the word in list
"""
word_key = "##"
trie = {}
for word in words:
node = trie
for char in word:
node = node.setdefault(char, {})
node[word_key] = word
res = []
def track(r, c, parent):
letter = board[r][c]
current = parent[letter]
# optimization:
# - avoid duplicates
# - reduce the size of the trie
word_match = current.pop(word_key, False)
if word_match:
res.append(word_match)
# optimization to avoid re-visit
board[r][c] = "#"
for dr, dc in [(-1, 0), (0, 1), (1, 0), (0, -1)]:
nr, nc = r + dr, c + dc
if (
0 <= nr < len(board)
and 0 <= nc < len(board[0])
and board[nr][nc] in current
):
track(nr, nc, current)
# optimization to avoid re-checks:
# - reduce the size of the trie
if not current:
parent.pop(letter)
# restore
board[r][c] = letter
for r in range(len(board)):
for c in range(len(board[0])):
if board[r][c] in trie:
track(r, c, trie)
return res
def findWords(board: List[List[str]], words: List[str]) -> List[str]:
"""
Backtracking, not optimized
Extremely slow
Time: O(r * c * (3 ** l))
Space: O(l)
r - number of rows
c - number of cols
l - max length of the word in list
"""
ws = set(words)
max_len = max(map(len, words))
res = set()
def track(r, c, path, word, l):
wrd = "".join(word)
if wrd in ws:
res.add(wrd)
if l >= max_len:
return
for dr, dc in [(-1, 0), (0, 1), (1, 0), (0, -1)]:
nr, nc = r + dr, c + dc
if (
0 <= nr < len(board)
and 0 <= nc < len(board[0])
and (nr, nc) not in path
):
path.add((nr, nc))
track(nr, nc, path, word + [board[nr][nc]], l + 1)
path.remove((nr, nc))
for r in range(len(board)):
for c in range(len(board[0])):
track(r, c, set([(r, c)]), [board[r][c]], 1)
return res
| true |
d743e7c63ddee5169e99773c615f3a2cb63613bf | weak-head/leetcode | /leetcode/p0609_find_duplicate_file_in_system.py | 2,447 | 4.15625 | 4 | from typing import List
from collections import defaultdict
def findDuplicate(paths: List[str]) -> List[List[str]]:
"""
* 1. Imagine you are given a real file system, how will you search files? DFS or BFS?
BFS explores neighbors first.
This means that files which are located close to each other are also accessed one after another.
This is great for space locality and that's why BFS is expected to be faster. Also, BFS is easier to parallelize (more fine-grained locking).
DFS will require a lock on the root node.
* 2. If the file content is very large (GB level), how will you modify your solution?
For very large files we should do the following comparisons in this order:
- compare sizes, if not equal, then files are different and stop here!
- hash them with a fast algorithm e.g. MD5 or use SHA256 (no collisions found yet), if not equal then stop here!
- compare byte by byte to avoid false positives due to collisions.
* 3. If you can only read the file by 1kb each time, how will you modify your solution?
That is the file cannot fit the whole ram.
Use a buffer to read controlled by a loop; read until not needed or to the end.
The sampled slices are offset by the times the buffer is called.
* 4. What is the time complexity of your modified solution? What is the most time-consuming part and memory consuming part of it? How to optimize?
T = O(|num_files||sample||directory_depth|) + O(|hashmap.keys()|)
* 5. How to make sure the duplicated files you find are not false positive?
Add a round of final check which checks the whole string of the content.
T = O(|num_output_list||max_list_size||file_size|).
Time: O(n * s)
Space: O(n * s)
n - total number of files across all paths
s - average file content size
"""
def extract(file_info):
ix = file_info.find("(")
file_name = file_info[:ix]
content = file_info[ix + 1 : -1]
return file_name, content
files = defaultdict(set)
for path in paths:
info = path.split()
folder = info[0]
for file_info in info[1:]:
file_name, content = extract(file_info)
file_path = f"{folder}/{file_name}"
files[content].add(file_path)
res = []
for content, duplicates in files.items():
if len(duplicates) > 1:
res.append(duplicates)
return res
| true |
b88e80385800a44af25da1f0ab75ccfbca9387d8 | candyer/learn-python-the-hard-way | /airport-board.py | 1,741 | 4.15625 | 4 | def next_letter(letter):
return chr(ord(letter) + 1)
def initialize_array(city):
"""
create a list of "a" the same length as city
"""
list_city = []
while len(list_city) < len(city):
list_city.append('a')
return list_city
def list_to_string(list_city):
"""
take a list, make what's inside to a string.
"""
return ''.join(list_city)
def increment_letter(letter_from_list, letter_from_city):
"""
take the value from list and string,on the same position,if it's the same, return the same, otherwise increment one
"""
if letter_from_list < letter_from_city:
return next_letter(letter_from_list)
else:
return letter_from_city
def increment_list(changing_list, city):
"""
compare the initialize_array with list_city, stop running when they are the same.
"""
n = 0
while n < len(changing_list):
# print "comparing", changing_list[n], "with", city[n]
changing_list[n] = increment_letter(changing_list[n], city[n])
n = n + 1
return changing_list
def print_board(city):
changing_list = initialize_array(city)
print list_to_string(changing_list)
while list_to_string(changing_list) != city:
print list_to_string(increment_list(changing_list, city))
print_board("paris")
def tests():
print initialize_array("paris") == ['a','a','a','a','a']
print initialize_array("bj") == ['a','a']
print initialize_array("") == []
print list_to_string(['p','a','r','i','s']) == "paris"
print list_to_string([]) == ""
print increment_letter("a", "p") == "b"
print increment_letter("b", "p") == "c"
print increment_letter("p", "p") == "p"
print increment_list(['i','a','i','i','i'], "paris") == ['j','a','j','i','j']
print increment_list(['a'], "a") == ['a']
print increment_list(['a'], "d") == ['b']
| true |
03abde311519c576eed418644098b09848945806 | deepakag5/Data-Structure-Algorithm-Analysis | /Sorting/InsertionSort.py | 477 | 4.21875 | 4 | def insertion_sort(arr):
for i in range(1,len(arr)):
# create a temp variable to store current value
temp = arr[i]
position = i
# keep swapping the elements until the previous element is greater than the element at position
while position > 0 and temp < arr[position - 1]:
arr[position] = arr[position - 1]
position -= 1
arr[position] = temp
arr = [3, 1, 8, 6, 2]
insertion_sort(arr)
print(arr)
| true |
eb3f98069aa33aeabac448c00c91085d54de9576 | deepakag5/Data-Structure-Algorithm-Analysis | /leetcode/array_merge_intervals_two_lists.py | 1,226 | 4.1875 | 4 | # Time Complexity: Best case : O(m+n)
# Space Complexity - O(m+n) for holding the results
def merge(list1, list2):
# base case
if not list1:
return list2
if not list2:
return list1
# first we need to merge both lists in sorted order (on basis of first element) so that we can then merge intervals
i, j = 0, 0
merged_list = []
while i < len(list1) and j < len(list2):
if list1[i][0] <= list2[j][0]:
merged_list.append(list1[i])
i += 1
else:
merged_list.append(list2[j])
j += 1
# if one list is greater in length than other list then
# we need to append rest of the elements from that list at the end
if i < len(list1):
merged_list.extend(list1[i:])
if j < len(list2):
merged_list.extend(list2[j:])
# now we can just iterate over this merged list and combine the intervals
combined_intervals = []
for item in merged_list:
if not combined_intervals or combined_intervals[-1][-1] < item[0]:
combined_intervals.append(item)
else:
combined_intervals[-1][-1] = max(combined_intervals[-1][-1], item[-1])
return combined_intervals | true |
d0bb05a35c89ba9729417de48331a660d6ffe6b1 | sureshkanna-alg/python | /new_file1.py | 393 | 4.1875 | 4 | n = input("Enter your number: ")
if n==1:
print "English"
elif n==2:
print "Telugu"
elif n==3:
print "Maths"
elif n==4:
print "Social"
elif n==5:
print "Science"
else:
print "Enter Valid Number"
n = input("Enter Your Number: ")
if type(n) == int:
if n%2 == 0:
print "Even"
else:
print "Odd"
else:
print " Not Valid Integer"
| false |
eb104e1a0f8d6a13ef93c7b3e46385dd32480d97 | dackour/python | /Chapter_23/01_Module_Usage.py | 1,675 | 4.125 | 4 | # The import statement
import module1 # Get module as a whole (one or more)
module1.printer('Hello world!') # Qualify to get names
# The from Statement
from module1 import printer # Copy out a variable (one or more)
printer('Hello world!') # No need to qualify name
# The from * Statement
from module1 import * # Copy out _all_variables
printer('Hello world!')
# Imports Happen Only Once
import simple # First import: loads and runs file's code
print(simple.spam) # Assignment makes an attribute
simple.spam = 2 # Change attribute in module
import simple # Just fetches already loaded module
printer(simple.spam) # Code wasn't rerun: attribute unchanged
# import and from Are Assignments
from small import x, y # Copy two names out
x = 42 # Changes local x only
y[0] = 42 # Changes shared mutable in place
import small # Get module name (from doesn't)
print(small.x) # Smalls x is not my x
print(small.y) # But we share a changed mutable
# Cross-file changes
from small import x, y # Copy two names out (only)
x = 42 # Changes my x only
import small # Get module name
small.x = 42 # Changes x in other module
print(small.x)
# Import and from Equivalence
# Potential pitfalls of the from Statement
# When import is required
from mmodule import func
from nmodule import func # This overwrites the one we fetched from M
print(func()) # Calls N.func only!
import mmodule, nmodule # Get the whole modules not their names
print(mmodule.func()) # We call both names now
print(nmodule.func()) # The module names make them unique
from mmodule import func as mfunc # Rename uniquely with as
from nmodule import func as nfunc
mfunc()
nfunc()
| true |
8b763a0c00f8caa70c566c3ea5c7cb3d66c24164 | mavamfihlo/Mava059 | /calculatorSprint4.py | 1,627 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
@author: Mava Mfihlo
"""
# below we are importing all of the functions that were created in the CalculatorFunctions.py file
from CalculatorFunctions import*
#this function import sys from os which will allow exit or quit the program
from os import sys
# while loop will remain true as the program run until the input decide to exit
while True:
#new variables are initialised and declared as to allow the user to input values and operators
num1 = float(input("Enter number: "))
op = input("Enter operator: ")
num2 = float(input("Enter second number: " ))
# if statement has been created to validate the input of the user and
#to check if correct operations and numbers format have been entered
#variable that have been imported form the CalculatorFunctions.py files have been initialised as well as parameter below
if op == "+":
addition(num1,num2)
elif op == "-":
subtraction(num1,num2)
elif op == "*":
multiplication(num1,num2)
elif op == "/":
division(num1,num2)
# if invalid operator other than the one initialised above have been entered the it will print the message below
else:
print("Invalid operator")
#below the new delared variable will allow the user to have a choice of exiting the program if all the operation have be executed
choice = input("Press E To EXIT: ")
if choice == "e" or choice == "E":
print("You have EXITED")
sys.exit(0)
| true |
11dd15d44a03f915db6ef221040d47cce032ca1f | akash95khandare/Functional-Algorithm-Object-Oriented-program-in-python | /Month1/algorithm/Anagram.py | 309 | 4.125 | 4 | from util.Utility import is_anagram
def main():
str1 = input("Enter first string : ")
str2 = input("Enter second string : ")
if is_anagram(str1.strip(), str2.strip()):
print("String is anagram.")
else:
print("String is not anagram.")
if __name__ == '__main__':
main()
| false |
6385a5bed6596c002b1363c69c4320bd88a32957 | akash95khandare/Functional-Algorithm-Object-Oriented-program-in-python | /Month1/OOPS/StockReport.py | 1,986 | 4.15625 | 4 | """
Overview : Stock Report
purpose : writing new json data into json file
class name : StockReport
author : Akash Khandare
date : 05/03/2019
"""
import json
class StockReport:
def __init__(self):
self.list = []
with open("Json_Files/Stock.json", 'r') as data:
try:
data = json.load(data)
for i in data:
self.list.append(i)
except Exception:
print("File is empty.")
def new_data(self):
"""
Taking new data from user and make json data
:return: return dt as new created json data
"""
dt = {"name": "",
"no_of_share": "",
"price": ""}
try:
name = input("Enter company name : ").strip().upper()
no_of_share = input("Enter no of share : ").strip()
price = input("Enter share price : ").strip()
if not name.isalpha() or not no_of_share.isnumeric() or not price.isnumeric():
raise ValueError
except:
print("You have entered wrong data.")
else:
dt["name"] = name
dt["no_of_share"] = no_of_share
dt["price"] = price
return dt
def stock_report(self):
"""
reading old data from json file in list and
add new json data into list and then write list into json file
:return:
"""
dt = self.new_data()
self.list.append(dt)
# print(self.list)
with open("Json_Files/Stock.json", 'w') as da:
json.dump(self.list, da)
print("Company Added.")
def display(self):
print("Company name\t\tNo of share\t\tPer share price")
for i in self.list:
print(i["name"], "\t\t\t\t", i["no_of_share"], "\t\t\t\t", i["price"])
# Main method
if __name__ == "__main__":
stock = StockReport()
stock.display()
stock.stock_report()
stock.display()
| true |
28e79fcbf38289d6608ccc1aff49a1b949ba558c | UltraChris64/Learn-Python-the-Hard-Way | /labs/ex6.py | 886 | 4.5625 | 5 | types_of_people = 10
# lines 3 and 7 format (the beginning f) inside the variable to replace any
# variable used in the curly brackets when that variable is used
x = f"There are {types_of_people} types of people."
binary = "binary"
do_not = "don't"
y = f"Those who know {binary} and those who {do_not}."
print(x)
print(y)
# lines 11 and 12 use the format (the beginning f) to substitute a variable
# that's inside the curly brackets
print(f"I said: {x}")
print(f"I also said: '{y}'")
hilarious = False
# curly brackets at the end represents a place holder when it's empty
joke_evaluation = "Isn't that joke so funny?! {}"
# .format is to to fill in a place holder
print(joke_evaluation.format(hilarious))
w = "This is the left side of..."
e = "a string with a right side."
# adding combines 2 numbers, so here it's going to combine the two variables and
# their meaning
print(w + e) | true |
30e72d54c31ba3eee6d041862264d2627ea4bfb4 | AnetaStoycheva/Programming0_HackBulgaria | /Week 10/dict_reverse.py | 289 | 4.25 | 4 | # {key:value} --> {value: key}
# {'A': 'abc'} --> {'abc':'A'}
def dict_reverse(dictionary):
new_dictionary = {}
for key in dictionary:
value = dictionary[key]
new_dictionary[value] = key
return new_dictionary
print(dict_reverse({'A': 'abc', 'B': 'def'}))
| false |
ad76f9a4e39a8cfb270db88be5c54bbe5633f2ec | Hroque1987/Exercices_Python | /Functions_examples/string.format.py | 1,036 | 4.1875 | 4 | #str.format()
#animal ='cow'
#item = 'moon'
#print('The '+animal+' jumped over '+item)
#print('The {} jumped over the {}'.format(animal, item))
#print('The {1} jumped over the {0}'.format(animal, item)) #positional argument
#print('The {animal} jumped over the {item}'.format(animal='cow', item='moon')) # keyword argument
#text = 'The {} jumped over {}'
#print(text.format(animal,item))
#name ='Helder'
#print('Hello, my name is {}'.format(name))
#print('Hello, my name is {:10} nice to meet you'.format(name)) # add padding to a value
#print('Hello, my name is {:<10}nice to meet you'.format(name))
#print('Hello, my name is {:>10}nice to meet you'.format(name))
#print('Hello, my name is {:^10}nice to meet you'.format(name))
#number = 3.14159
#print('The number pi is {:.3f}'.format(number))
number =1000
print('The number is {:,}'.format(number))
print('The number is {:b}'.format(number))
print('The number is {:o}'.format(number))
print('The number is {:x}'.format(number))
print('The number is {:e}'.format(number))
| true |
ec0bf97fb5cbf2fea670da8b29442993345fc565 | fredericyiding/algorithms | /numsIslands.py | 2,454 | 4.21875 | 4 | from Queue import Queue
class Solution:
"""This is to calculate the number of Islands based on
binary list of lists.
Attributes:
"""
def numsIslands(self, grid, method='bfs'):
"""This function calculates the number of Islands.
Both BFS and DFS implementations were presented.
Note that BFS can be implemented by both Queue.Queue or collections.deque
Args:
grid (list of lists): boolean input, 1 as island and 0 as sea.
method (string): bfs or dfs
example for generating a m x n grid:
>>> from random import randint
>>> m, n = 8, 7
>>> grid = [[randint(0, 2) for y in range(n)] for x in range(m)]
Returns:
An integer that is the number of islands, defined as segregated 1's.
"""
if method != 'bfs' or 'dfs':
raise ValueError("Please enter 'bfs' or 'dfs'")
self.grid = grid
self.m = len(grid)
if self.m == 0:
return 0
self.n = len(grid[0])
self.visited = [[False for y in range(self.n)] for x in range(self.m)] #pylint: disable=unused-variable
count = 0
for row in range(self.m):
for col in range(self.n):
if self.check(row, col):
if method.lower() == 'bfs':
self.bfs(row, col)
elif method.lower() == 'dfs':
self.dfs(row, col)
count += 1
return count
def check(self, x, y):
return x >= 0 and x < self.m and y >= 0 and y < self.n and self.grid[x][y] and not self.visited[x][y]
q = Queue(maxsize=self.m * self.n)
q.put((x, y))
self.visited[x][y] = True
nbrow = [0, 1, 0, -1]
nbcol = [1, 0, -1, 0]
while not q.empty():
x_q, y_q = q.get()
for i in range(4):
newx, newy = x_q + nbrow[i], y_q + nbcol[i]
if self.check(newx, newy):
q.put((newx, newy))
self.visited[newx][newy] = True
def dfs(self, x, y):
self.visited[x][y] = True
nbrow = [0, 1, 0, -1]
nbcol = [1, 0, -1, 0]
for i in range(4):
newx, newy = x + nbrow[i], y + nbcol[i]
if self.check(newx, newy):
self.visited[newx][newy] = True
self.dfs(newx, newy)
| true |
990578d0a0ed269d519392e7a4b58177fe0ebb59 | wojtas2000/codewars | /number_expanded_form.py | 873 | 4.375 | 4 | # Write Number in Expanded Form
# You will be given a number and you will need to return it as a string in Expanded Form. For example:
# expanded_form(12) # Should return '10 + 2'
# expanded_form(42) # Should return '40 + 2'
# expanded_form(70304) # Should return '70000 + 300 + 4'
# NOTE: All numbers will be whole numbers greater than 0.
def expanded_form(num):
expand = str(num) # convert to string
len_str = len(expand)
temp = '' # create empty string
for i in range(len_str):
if expand[i] != "0": # skipping zero
zero = (len_str-i-1) * "0" # create numberof zero
step = expand[i] + zero # add zeros to digit
temp += step
if i == len_str-1: # if we are on last digit just break
break
if expand[i+1] != "0": # if next dig is not the zero
temp += " + "
return temp
| true |
d0aa7d38ff7a446a47e562265d16f9416ed6774d | mcavalca/uri-python | /2846.py | 208 | 4.125 | 4 | def fibonot(n):
a = 1
b = 2
c = 3
while n > 0:
a = b
b = c
c = a + b
n -= (c - b - 1)
n += (c - b - 1)
return b + n
n = int(input())
print(fibonot(n))
| false |
fba00850481a6a5df77e86977cc07d11d60c05ec | Zmontague/PythonSchoolWork | /asciiArt.py | 1,896 | 4.40625 | 4 | """
Author: Zachary Montague
Date: 4/19/2021
Description: Program which prompts user for file name, reads the file
name in, line by line iterates through the file and then decrypts the text, finally displaying the art and asking the
user if they wish to read more files, until blank line is entered
"""
# CONSTANT DECLARATION
DISTANCE = 1
# Variable declaration
fileText = ""
decryptedText = ""
# Ask the user for input (file name) and explain how to exit
fileName = input("Enter a file name to read, or just Enter to quit: ")
# Loop through opening a file until the user gives an empty string
while fileName != "":
# Open file with the file name the user provided
f = open(fileName, 'r')
# Read the file line by line and store in variable
fileText = f.readline()
# Close the file when finished using it
f.close()
# Decrypt the file
for letter in fileText:
ordValue = ord(letter)
cipherValue = ordValue - DISTANCE
decryptedText += chr(cipherValue)
# Print the decrypted ASCII art
print(decryptedText)
# Ask the user if they want to save the file
userAnswer = input("Would you like to save the file? (Y/N) ")
# If the user enters Y or YES, move to asking the user for the file name
userAnswer = userAnswer.upper()
if userAnswer == 'Y' or userAnswer == 'YES':
saveFileName = input("Enter the new file name: ")
# open/create the file
f = open(saveFileName, 'x')
# write the contents of the ascii art to the new file
f.write(decryptedText)
# finished with the file, close it now
f.close()
# if the user enters N or No, move to asking the user for the next file name.
elif userAnswer == 'N' or userAnswer == 'NO':
fileName = input("Enter the next file name to read, or just Enter to quit: ")
# Say goodbye to the user.
print("All done! Goodbye!")
| true |
082cae899e0314834cbbc83c9f3043a4ae13d9c0 | codrWu/py-codewars | /get_the_mid_char.py | 900 | 4.3125 | 4 | # -*- coding: utf-8 -*-
"""
You are going to be given a word. Your job is to return the middle character of the word. If the word's length is odd,
return the middle character. If the word's length is even, return the middle 2 characters.
获取字符串中间的字符,字符串长度为奇数返回中间一个字符,长度为偶数返回中间两个字符
Created on 2018/7/4
@author: codrwu
"""
__author__ = 'codrwu'
import math
# my function
def get_middle_my(s):
before_index = math.floor(len(s)/2)
after_index = math.ceil(len(s)/2)
if before_index == after_index:
before_index = before_index - 1
after_index = after_index -1
print('%s:%s' % (before_index, after_index))
result = s[before_index:after_index]
return result
# Best Practices
def get_middle(s):
return s[math.floor((len(s)-1)/2):math.floor(len(s)/2)+1]
print(get_middle("test")) | true |
dd174d1a4f71b9583c1280b55bd1132511338c1b | amari-at4/Duplicate-File-Handler | /Topics/Loop control statements/Prime number/main.py | 233 | 4.1875 | 4 | number = int(input())
times_divisible = 0
for _i in range(1, number + 1):
if number % _i == 0:
times_divisible += 1
if times_divisible == 2:
print("This number is prime")
else:
print("This number is not prime")
| true |
021e2c922e635be0cadc325bbbc78f738f024e69 | sam-kumar-sah/Leetcode-100- | /451s.sort_character_by_frequency_in_string.py | 663 | 4.1875 | 4 | //451. Sort Characters By Frequency
'''
Given a string, sort it in decreasing order based on the
frequency of characters.
Example 1:
Input: "tree"
Output: "eert"
Example 2:
Input: "cccaaa"
Output: "cccaaa"
Example 3:
Input: "Aabb"
Output: "bbAa"
'''
//code:
class Solution(object):
def fs(self,s):
h={}
for ch in s:
if(ch not in h):
h[ch]=1
else:
h[ch]+=1
l=sorted([(h[c],c) for c in h],reverse=True)
l1=[]
for ch,c in l:
l1.append(c*ch)
return ''.join(l1)
s=input()
ss=Solution()
print(ss.fs(s)) | true |
b7bab5235de87b65aa8fe8c7c8bdb26debdf3e35 | marcowchan/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/2-matrix_divided.py | 1,417 | 4.28125 | 4 | #!/usr/bin/python3
"""Defines matrix_divided"""
def matrix_divided(matrix, div):
"""Divides all elements of a matrix.
Args:
matrix: A list of lists of integers or floats.
div: The divisor to divide the elements of the matrix by.
Raises:
TypeError: If the matrix is not a list of lists of integers or floats.
or the rows of the matrix are not of the same size
or div is not a integer or a float
ZeroDivisionError: If div is zero
Returns:
A new matrix of quotients
"""
invalid_mat = "matrix must be a matrix (list of lists) of integers/floats"
if not isinstance(matrix, list) or len(matrix) == 0:
raise TypeError(invalid_mat)
if not isinstance(div, int) and not isinstance(div, float):
raise TypeError("div must be a number")
if div == 0:
raise ZeroDivisionError("division by zero")
row_len = None
for row in matrix:
if not isinstance(row, list) or len(row) == 0:
raise TypeError(invalid_mat)
if row_len is not None and row_len != len(row):
raise TypeError("Each row of the matrix must have the same size")
row_len = len(row)
for col in row:
if not isinstance(col, int) and not isinstance(col, float):
raise TypeError(invalid_mat)
return [[round(col / div, 2) for col in row] for row in matrix]
| true |
5747ce73e516a8a66c6668f7ca3d9ea389fac79f | gerpsh/backtoschool | /imgEditor/editor/processing/bw.py | 1,748 | 4.3125 | 4 | def applyFilter(pixels):
# This is an array where we'll store pixels for the new image. In the beginning, it's empty.
newPixels = []
# Let's go through the entire image, one pixel at a time
for pixel in pixels:
# Let's get the Red, Green and Blue values for the current pixel
inputRed = pixel[0]
inputGreen = pixel[1]
inputBlue = pixel[2]
# in a Black&White image, each pixel has the same value for Red, Green, and Blue.
# But what is that value?
# Red = Green = Blue = ?
# The easiest method of calculating the new value is to average the old values:
# newRed = newGreen = newBlue = (oldRed + oldGreen + oldBlue) / 3
average = (inputRed + inputGreen + inputBlue) / 3
outputRed = average
outputGreen = average
outputBlue = average
# Now that we know the color values for the new pixel, let's create this pixel.
newPixel = [0,0,0]
# Let's set the Red, Green, and Blue values for this new pixel
newPixel[0] = outputRed
newPixel[1] = outputGreen
newPixel[2] = outputBlue
# Optional exercise:
# Now that you know how to convert an image to B&W, try something new!
# Try changing the output values. For example, If you increase the outputRed value,
# you can make the image red-and-white instead of black-and-white!
# But remember that each color value cannot be bigger than 255.
# To make sure that a number is not bigger than 255, you can use the min function, for example:
# newNumber = min(number, 255)
# add the new pixel to the resulting image
newPixels.append(newPixel)
return newPixels | true |
34d222f0a98b6d90711a37661c30bddb450b09db | randm989/Euler-Problems | /python/p14.py | 891 | 4.15625 | 4 | #!/usr/bin/python
#The following iterative sequence is defined for the set of positive integers:
#
#n n/2 (n is even)
#n 3n + 1 (n is odd)
#
#Using the rule above and starting with 13, we generate the following sequence:
#
#13 40 20 10 5 16 8 4 2 1
#It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
#
#Which starting number, under one million, produces the longest chain?
#
#NOTE: Once the chain starts the terms are allowed to go above one million.
#naive
startNum=13
def chain(num):
chainlength = 1
while num > 1:
if num%2 == 0:
num/=2
else:
num=num*3+1
chainlength+=1
return chainlength
maxLength = (1,1)
for i in range(500000,1000000):
res = (chain(i),i)
maxLength = max(res,maxLength)
print maxLength
| true |
9b6c8d5b353f452cfd2809c57d3a521fa0aa553c | mattcucuzza/pyLinearAlgebra | /main.py | 2,060 | 4.125 | 4 | # Matthew Cucuzza
# 2/18/17
# Python program doing various operations with vectors from linear algebra
import math
# Find the sum of two vectors combined
def addVectors(x1, y1, x2, y2):
x = x1+x2
y = y1+y2
return x,y
# Find the length of two vectors combined
def lengthOfVector(x,y):
x = x**2
y = y**2
xY = x+y
return "sqrt("+str(xY)+")"
# Find the length of the sum of two vectors combined
def lengthOfAddVectors(x1, y1, x2, y2):
x = (x1+x2)**2
y = (y1+y2)**2
xY = x+y
return "sqrt("+str(xY)+")"
# Find the dot product (multiply x's, multiply y's, add them together)
def dotProduct(x1, y1, x2, y2):
x = x1*x2
y = y1*y2
return x+y
# Check if the dot product is orthogonal (equal to 0)
def isOrthogonal(x1, y1, x2, y2):
if dotProduct(x1,y1,x2,y2) == 0:
return True
else:
return False
# Find the angle between two vectors
def findAngle(x1, y1, x2, y2):
dot = dotProduct(x1, y1, x2, y2)
lengthU = lengthOfVector(x1,y1)
lengthV = lengthOfVector(x2,y2)
return str(dot) +"/"+ "(" + str(lengthU) + " * " + str(lengthV) + ")"
# Find the unit vector of two vectors
def unitVector(x1, y1, x2, y2):
add = addVectors(x1, y1, x2, y2)
length = lengthOfAddVectors(x1, y1, x2, y2)
return str(add) +"/"+ "(" + str(length) +")"
print "-----First Set of Coordinates-----"
x1 = input("Enter X1: ")
y1 = input("Enter Y2: ")
print
print "-----Second Set of Coordinates-----"
x2 = input("Enter X2: ")
y2 = input("Enter Y2: ")
print
print "-----Inputted Coordinates-----"
print "u : ("+str(x1)+ ","+ str(y1)+")"
print "v : ("+str(x2)+ ","+ str(y2)+")"
print
print "-----Calculations-----"
print "||u|| : ", lengthOfVector(x1,y1)
print "||v|| : ", lengthOfVector(x2,y2)
print "u+v : ", addVectors(x1, y1, x2, y2)
print "||u+v|| : ", lengthOfAddVectors(x1, y1, x2, y2)
print "u*v : ", dotProduct(x1, y1, x2, y2)
print "Orthogonal: ", isOrthogonal(x1, y1, x2, y2)
print "Angle of Two Vectors: ", findAngle(x1, y1, x2, y2)
print "Unit Vector: ", unitVector(x1, y1, x2, y2)
| true |
4cf83df6618978bd041bfa78af67e33a73818663 | atriadhiakri2000/Algorithm | /Tree/Merge two BST 's.py | 2,677 | 4.375 | 4 | # Data structure to store a BST node
class Node:
# Constructor
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
# Helper function to print a doubly linked list
def printDoublyList(head):
while head:
print(head.data, end=" -> ")
head = head.right
print("None")
# Function to insert a BST node at the front of a doubly linked list
def push(root, head):
# insert the given node at the front of the DDL
root.right = head
# update the left pointer of the existing head node of the DDL
# to point to the BST node
if head:
head.left = root
# update the head pointer of DDL
head = root
return head
"""
Recursive function to convert a binary search tree into a doubly linked list
root -. Pointer to the root node of the binary search tree
head -. Reference to the head node of the doubly linked list
"""
def convertBSTtoDLL(root, head):
# Base case
if root is None:
return head
# recursively convert the right subtree a
head = convertBSTtoDLL(root.right, head)
# push current node at the front of the doubly linked list
head = push(root, head)
# recursively convert the left subtree
head = convertBSTtoDLL(root.left, head)
return head
# Recursive function to merge two doubly linked list into a
# single doubly linked list in sorted order
def mergeDDLs(a, b):
# if the first list is empty, return the second list
if a is None:
return b
# if the second list is empty, return the first list
if b is None:
return a
# if head node of the first list is smaller
if a.data < b.data:
a.right = mergeDDLs(a.right, b)
a.right.left = a
return a
# if head node of the second list is smaller
else:
b.right = mergeDDLs(a, b.right)
b.right.left = b
return b
# Function to merge two binary search trees into a doubly linked list
# in sorted order
def merge(a, b):
# Convert first binary search tree to a doubly linked list
first = convertBSTtoDLL(a, None)
# Convert second binary search tree to a doubly linked list
second = convertBSTtoDLL(b, None)
# Merge both doubly linked lists
return mergeDDLs(first, second)
if __name__ == '__main__':
"""
Construct first BST
20
/ \
10 30
/ \
25 100
"""
a = Node(20)
a.left = Node(10)
a.right = Node(30)
a.right.left = Node(25)
a.right.right = Node(100)
"""
Construct second BST
50
/ \
5 70
"""
b = Node(50)
b.left = Node(5)
b.right = Node(70)
# merge both BSTs into a doubly linked list
root = merge(a, b)
printDoublyList(root)
| true |
74d0229c22b3083e4a0a0d45636fc01fa735bdc8 | MMDIOUF/basic_python | /exercise/palindrome.py | 279 | 4.15625 | 4 | def palindrome(mot):
mot_inverse=mot[::-1]
return mot == mot_inverse
m=input("Veuillez saisir un mot?\t")
resultat=palindrome(m)
reponse=f"{m} est un palindrome"
if resultat:
print(reponse)
else:
reponse = reponse.replace("est","n'est pas")
print(reponse) | false |
59e4e85b1be563055dc3a616b72e07d1e188c009 | btjd/coding-exercises | /array_strings/toeplitz_matrix.py | 1,006 | 4.15625 | 4 | """
LeetCode 766
A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same element.
Now given an M x N matrix, return True if and only if the matrix is Toeplitz.
"""
def toeplitz(matrix):
nr = len(matrix)
nc = len(matrix[0])
for r in range(nr - 1):
c = 0
curr = matrix[r][c]
r += 1
c += 1
while r <= nr -1 and c <= nc - 1:
if matrix[r][c] == curr:
r += 1
c += 1
else:
return False
for c in range(1, nc - 1):
r = 0
curr = matrix[r][c]
r += 1
c += 1
while r <= nr -1 and c <= nc - 1:
if matrix[r][c] == curr:
r += 1
c += 1
else:
return False
return True
def test_toeplitz():
assert toeplitz([[1,2,3,4],[5,1,2,3],[9,5,1,2]]) is True
assert toeplitz([[1,2],[2,2]]) is False
assert toeplitz([[1,2,3],[5,1,2],[4,5,2]]) is False | false |
0137bccec4aecafec20f89a64077fee732221da4 | priyanka090700/hacktoberfest2021 | /multiply.py | 367 | 4.375 | 4 | #Taking input from the user.
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
#Defining a function to calculate multiplication of the two numbers.
def multiply(a,b):
result = a * b
print("Product of two given numbers is: ", result)
#Calling the function to get the desired output.
multiply(num1, num2)
| true |
c6fae1838643eddada768c1cefff9508b6001ed7 | zeeshanhanif/ssuet-python | /4June2017/DataScienceChap4/Demo1.py | 945 | 4.125 | 4 | data = [
[26,30],
[28,50],
[30,70]
]
def vector_add(v, w):
"""adds corresponding elements"""
return [v_i + w_i
for v_i, w_i in zip(v, w)]
def vector_subtract(v, w):
"""subtracts corresponding elements"""
return [v_i - w_i
for v_i, w_i in zip(v, w)]
def vector_sum(vectors):
"""sums all corresponding elements"""
result = vectors[0] # start with the first vector
for vector in vectors[1:]: # then loop over the others
result = vector_add(result, vector) # and add them to the result
return result
re = vector_sum(data);
print(re);
def scalar_multiply(c, v):
"""c is a number, v is a vector"""
return [c * v_i for v_i in v]
def vector_mean(vectors):
"""compute the vector whose ith element is the mean of the
ith elements of the input vectors"""
n = len(vectors)
return scalar_multiply(1/n, vector_sum(vectors))
r3 = vector_mean(data);
print(r3)
| false |
f00c9f561c037c9bbc0fbbb8c12b6339719c1116 | zeeshanhanif/ssuet-python | /9April2017/DemoList/StudentTerminal.py | 1,256 | 4.28125 | 4 |
studentslist = ["zeeshan","saad","osama"]
print("Welcome to student portal")
print("Please enter 1 to list student names")
print("Please enter 2 to add student names")
print("Please enter 3 to search student names")
print("Please enter 4 to delete particular student names")
print("Please enter 5 to sort student names")
print("enter 6 to exit")
while(True):
user_input = int(input("Enter of your choice"))
if user_input == 1:
for studentnames in studentslist:
print(studentnames)
elif user_input == 2:
addname = input("Enter name to add")
studentslist.append(addname)
print(studentslist)
elif user_input == 3:
userinput = input("Search for a student name")
if userinput in studentslist:
print("found")
else:
print("not found")
elif user_input == 4:
userinput = input("Enter student name to delete")
if userinput in studentslist:
studentslist.remove(userinput)
print(userinput + " deleted")
else:
print("not found")
elif user_input == 5:
studentslist.sort()
print("Sorted")
print(studentslist)
elif user_input == 6:
exit()
| true |
00e40c3ec5331789c75a00ed50e44e0d7f0de932 | josias-natal/learning-python | /aulas/aula017_listas.03_copiar_listas.py | 631 | 4.15625 | 4 | '''NOTE: When one list is matched to another in Python, when modifying one, the other is also modified together.'''
a = [2, 3, 4, 7]
b = a # Cria uma lista "b" idêntica à lista "a", tornando-as intrinsecamente ligadas
b[2] = 8
print(f'Lista A: {a}')
print(f'Lista B: {b}')
print('')
"""
Para criar duas listas com itens idênticos, porém que sejam independentes entre si, ao invés de fazer:
a = [2, 3, 4, 7]
b = a
Se faz:
a = [2, 3, 4, 7]
b = a[:]
"""
c = [1, 2, 3, 4]
d = c[:] # Cria uma lista "d" com os mesmos elementos da lista "c", deixando cada uma independente
d[3] = 5
print(f'Lista C: {c}')
print(f'Lista D: {d}') | false |
451e9c53ffbf4a4d5e888765fd00cca8f933306d | xyismy/py | /if.py | 358 | 4.15625 | 4 | # -*- coding: utf-8 -*-
# str = 5
# #第一种
# if str > 10:
# print(str)
# #第二种
# if str > 10:
# print(str)
# elif str > 1:
# print('yes')
# else:
# print('no')
# #第三种,非0,非空str,list则true,反之false
# if str:
# print(str)
str = 'ABC'
str2 = 'abc'
print(str.lower())
print(str.upper())
print(str2.isupper()) | false |
835476ef90f3f6c91c00eaccc427af5cfaec0e89 | susbiswas/DSAlgo | /MaxHeap.py | 2,141 | 4.1875 | 4 | # The following code implements a **max** Heap
#
# Strictly speaking, the following functions will take O(n) time
# in Python, because changing an input array within the body of a function
# causes the language to copy the entire array. We will soon see how to do this
# better, using Python classes
# function for inserting element in heap
def heapInsert(H,x):
H.append(x) # append in last leaf (next available position in array/list)
n = len(H)
# now bubble up x
pos = n-1; # current position of bubble-up
while True:
parent_pos = (pos-1)//2
if parent_pos<0:
break
if H[parent_pos] < H[pos]:
H[pos] = H[parent_pos] # copy parent value to current position
H[parent_pos] = x # move x to parent's position
pos = parent_pos # update current position
else:
break # break the bubble-up loop
return H
# function for removing max element from heap
# WARNING: This function is intentionally incomplete --
# You will fix this in the assignment
def heapMaxRemove(H):
x = H.pop() # pop last element
H[0] = x # put it in the place of max
n = len(H) #calculate the length
# now bubble-down x
pos = 0
while True:
c1_pos = 2*pos+1 # child 1 position
c2_pos = 2*pos+2 # child 2 position
if c1_pos > n-1: # corrected the code by checking if left or right child doesn't exist
break #then break the loop
l_value = H[c1_pos]
if c2_pos > n-1:
r_value = l_value
else:
r_value = H[c2_pos]
if l_value >= r_value:
c_pos = c1_pos
else:
c_pos = c2_pos # which child is active in possible swap
if H[pos]< H[c_pos]:
H[pos] = H[c_pos] # swap
H[c_pos] = x
pos = c_pos # update current position
else:
break # break
H=[]
H = heapInsert(H,25)
H = heapInsert(H,40)
H = heapInsert(H,-8)
print("Before delete")
print(H)
heapMaxRemove(H)
print("After delete")
print(H) | true |
05ca6f981f767455a9dfb99592821976c09c6f4b | MyHackInfo/Python-3-on-geeksforgeeks | /035- Mouse and keyboard automation using Python.py | 1,409 | 4.125 | 4 | '''
#### Mouse and keyboard automation using Python ####
-The pyautogui is a module that help us control mouse and keyboard with code.
## Some Functions
1-size(): This function is used to get Screen resolution.
2-moveTo(): use this function move the mouse in pyautogui module.
3-moveRel() function: moves the mouse pointer relative to its previous position.
4-position(): function to get current position of the mouse pointer.
5-click(): Function used for clicking and dragging the mouse.
6-scroll(): scroll function takes no. of pixels as argument, and scrolls the screen up to given number of pixels.
7-typewrite(): You can automate typing of string by using typewrite() function. just pass the string which you want to type as argument of this function.
* Passing key names: You can pass key names separately through typewrite() function.
* Pressing hotkey combinations: Use hotkey() function to press combination of keys like ctrl-c, ctrl-a etc.
'''
import pyautogui
# Get screen size
print(pyautogui.size())
# Mouse move
pyautogui.moveTo(100,100,duration=1)
# previous position
pyautogui.moveRel(0,50,duration=1)
# Current Position
print(pyautogui.position())
# Mouse clicking
pyautogui.click(100,100)
# Scroll the screen
pyautogui.scroll(200)
# Type some text
pyautogui.typewrite("Hello Fuck World.")
# Hotkey
pyautogui.hotkey('ctrlleft','a')
| true |
32eda3cbc67f060040a8eed5ba02e29dde62b512 | MyHackInfo/Python-3-on-geeksforgeeks | /048-enum in Python.py | 930 | 4.46875 | 4 | '''
#### Enum in Python ####
-Enumerations in Python are implemented by using the module named “enum“.
-Enumerations are created using classes. Enums have names and values associated with them.
## Properties of enum:
1. Enums can be displayed as string or repr.
2. Enum can be checked for their types using type().
3. “name” keyword is used to display the name of the enum member.
4. Enumerations are iterable. They can be iterated using loops.
5. Enumerations support hashing. Enums can be used in dictionaries or sets.
'''
import enum
class Animal(enum.Enum):
dog=1
cat=2
lion=3
print("The String representation of enum :",Animal.dog)
print("The type of enum:",type(Animal.dog))
print("The repr representation of enum:",repr(Animal.dog))
print("The name of enum:",Animal.dog.name)
# Print all enum using loop
for a in (Animal):
print("\n",a)
| true |
8bb072d3d1a21338fd3b206de442f13e94badb01 | MyHackInfo/Python-3-on-geeksforgeeks | /020-Generators in Python.py | 1,170 | 4.625 | 5 | '''
#### Generators in Python ####
1-Generator-Function:
A generator-function is defined like a normal function,
but whenever it needs to generate a value, it does so with
the yield keyword rather than return. If the body of a def
contains yield, the function automatically becomes a generator function.
1-Generator-Object:
Generator functions return a generator object. Generator objects are
used either by calling the next method on the generator object.
'''
'''
# A generator-function that yields 1 for first time,
# 2 second time and 3 third time
def simpleGeneratorFun():
yield 1
yield 2
yield 3
# Driver code to check above generator function
for value in simpleGeneratorFun():
print(value)
'''
'''
# A Python program to demonstrate use of
# generator object with next()
# A generator function
def simpleGeneratorFuns():
yield 1
yield 2
yield 3
# x is a generator object
x = simpleGeneratorFuns()
# Iterating over the generator object using next
print(x.next()); # In Python 3, __next__()
print(x.next());
print(x.next());
'''
| true |
f37ada6908329b162e40f9486a0228be999983b0 | MyHackInfo/Python-3-on-geeksforgeeks | /017-Using Iterations in Python.py | 878 | 4.75 | 5 | # Accessing items using for-in loop
cars = ["Aston", "Audi", "McLaren"]
for x in cars:
print (x)
# Indexing using Range function
for i in range(len(cars)):
print (cars[i])
# Enumerate is built-in python function that takes input as iterator
for q, x in enumerate(cars):
print (x)
for x in enumerate(cars):
print (x[0], x[1])
# Enumerate takes parameter start which is default set to zero.
# We can change this parameter to any value we like. In the below code we have used start as 1
for x in enumerate(cars, start=5):
print (x[0], x[1])
# Python program to demonstrate working of zip
# Two separate lists
cars = ["Aston", "Audi", "McLaren"]
accessories = ["GPS", "Car Repair Kit",
"Dolby sound kit"]
# Combining lists and printing
for c, a in zip(cars, accessories):
print ("Car: %s, Accessory required: %s"\
%(c, a))
| true |
b2c38cdbf324a30dff7fef4116d3b620d3691dd0 | MyHackInfo/Python-3-on-geeksforgeeks | /057-Python tkinter Button and Canvas.py | 1,469 | 4.3125 | 4 | '''
## 1- Button:->> To add a button in your application, this widget is used.
## format of the Buttons:>
1->activebackground:-> to set the background color when button is under the cursor.
2->activeforeground:-> to set the foreground color when button is under the cursor.
3->bg:-> to set he normal background color.
4->command:-> to call a function.
5->font:-> to set the font on the button label.
6->image:-> to set the image on the button.
7->width:-> to set the width of the button.
7->height:-> to set the height of the button.
'''
import tkinter as tk
r = tk.Tk()
r.title('Counting Seconds')
button = tk.Button(r, text='Stop', width=25, command=r.destroy)
button.pack()
r.mainloop()
############################
'''
## 2 Canvas:->> It is used to draw pictures and other complex layout like graphics, text and widgets.
## format of the Canvas:>>
1->bd: to set the border width in pixels.
2->bg: to set the normal background color.
3->cursor: to set the cursor used in the canvas.
4->highlightcolor: to set the color shown in the focus highlight.
5->width: to set the width of the widget.
6->height: to set the height of the widget.
'''
from tkinter import *
master = Tk()
w = Canvas(master, width=40, height=60)
w.pack()
canvas_height=20
canvas_width=200
y = int(canvas_height / 2)
w.create_line(0, y, canvas_width, y )
mainloop()
| true |
7f2e1c54a6c5df0f7d1ebc56667e465831d875cd | MyHackInfo/Python-3-on-geeksforgeeks | /014-Inplace vs Standard Operators in Python.py | 1,503 | 4.625 | 5 | '''
# Inplace vs Standard Operators in Python
-Normal operators do the simple assigning job. On other hand, Inplace operators behave
-similar to normal operators except that they act in a different manner in case of
-mutable and Immutable targets.
Immutable=> such as numbers, strings and tuples. >>Updation But not Assignment.
Mutable => such as list and dictionaries. >>Updation and Assignment both.
'''
# 1-Immutable :
# importing operator to handle operator operations
import operator
# Initializing values
x = 5
y = 6
a = 5
b = 6
# using add() to add the arguments passed
z = operator.add(a,b)
# using iadd() to add the arguments passed
p = operator.iadd(x,y)
print ("Value after adding using normal operator : ",end="")
print (z)
print ("Value after adding using Inplace operator : ",end="")
print (p)
print ("Value of first argument using normal operator : ",end="")
print (a)
print ("Value of first argument using Inplace operator : ",end="")
print (x)
# 2-Mutable
# Initializing list
a = [1, 2, 4, 5]
# using add() to add the arguments passed
z = operator.add(a,[1, 2, 3])
print ("Value after adding using normal operator : ",end="")
print (z)
print ("Value of first argument using normal operator : ",end="")
print (a)
# using iadd() to add the arguments passed
# performs a+=[1, 2, 3]
p = operator.iadd(a,[1, 2, 3])
print ("Value after adding using Inplace operator : ",end="")
print (p)
print ("Value of first argument using Inplace operator : ",end="")
print (a)
| true |
f65250794c2b2f3fa49927b3e37786978215dfce | MyHackInfo/Python-3-on-geeksforgeeks | /036-Object Oriented Programming in Python.py | 1,823 | 4.40625 | 4 | '''
#### Object Oriented Programming in Python ####
# Class, Object and Members #
* The __init__ method:>>
The __init__ method is similar to constructors in C++ and Java.
It is run as soon as an object of a class is instantiated.
The method is useful to do any initialization you want to do with your object.
* Class and Instance Variables:>>
In Python, instance variables are variables whose value is assigned inside a constructor or method with self.
'''
########################
# A simple example class
class Test:
# A sample method
def fun(self):
print("Hello")
# Create Object
obj = Test()
obj.fun()
#######################
#######################
# A Sample class with init method
class Person:
# init method or constructor
def __init__(self, name):
self.name = name
# Sample Method
def say_hi(self):
print('Hello, my name is', self.name)
# Create Object
p = Person('Narsi')
p.say_hi()
#########################
#########################
# Python program to show that the variables with a value
# assigned in class declaration, are class variables and
# variables inside methods and constructors are instance
# variables.
# Class for Computer Science Student
class CSStudent:
# Class Variable
stream = 'cse'
# The init method or constructor
def __init__(self, roll):
# Instance Variable
self.roll = roll
# Objects of CSStudent class
a = CSStudent(101)
b = CSStudent(102)
print(a.stream) # prints "cse"
print(b.stream) # prints "cse"
print(a.roll) # prints 001
# Class variables can be accessed using class
# name also
print(CSStudent.stream) # prints "cse"
##############################
# How to create an empty class?
# An empty class
class Test:
pass
| true |
7d95dc42bae43085f729ee5d037b9cc144c51d5e | MyHackInfo/Python-3-on-geeksforgeeks | /047-Heap queue (or heapq) in Python.py | 2,260 | 4.1875 | 4 | '''
### Heap Queue in python ###
-Heap data structure is mainly used to represent a priority queue.
-In Python, it is available using “heapq” module. The property of this
-data structure in python is that each time the smallest of heap element is popped(min heap).
-Whenever elements are pushed or popped, heap structure in maintained.
-The heap[0] element also returns the smallest element each time.
## Operations on heap :>>
1. heapify(iterable) :- This function is used to convert the iterable into a heap data structure. i.e. in heap order.
2. heappush(heap, ele) :- This function is used to insert the element mentioned in its arguments into heap. The order is adjusted, so as heap structure is maintained.
3. heappop(heap) :- This function is used to remove and return the smallest element from heap. The order is adjusted, so as heap structure is maintained.
4. heappushpop(heap, ele) :- This function combines the functioning of both push and pop operations in one statement, increasing efficiency. Heap order is maintained after this operation.
5. heapreplace(heap, ele) :- This function also inserts and pops element in one statement, but it is different from above function. In this, element is first popped, then element is pushed.i.e, the value larger than the pushed value can be returned.
6. nlargest(k, iterable, key = fun) :- This function is used to return the k largest elements from the iterable specified and satisfying the key if mentioned.
7. nsmallest(k, iterable, key = fun) :- This function is used to return the k smallest elements from the iterable specified and satisfying the key if mentioned.
'''
import heapq
# list
li=[4,6,2,7,4,8]
# convert list to heap
heapq.heapify(li)
print("The created heap is:",li) # list(li)
heapq.heappush(li,9)
print("The modified heap after push :",li)
print("The popped and smallest elements:",heapq.heappop(li))
print("After pop :",li)
heapq.heappushpop(li,4)
print("The popped item using heappushpop():",li )
heapq.heapreplace(li,3)
print("The popped item using heapreplace():",li)
print("The 3 largest number is :",heapq.nlargest(3,li))
print("The 3 smallest number is :",heapq.nsmallest(3,li))
| true |
7052094ebf233f0fa595080757162a7882589e55 | CSmel/pythonProjects | /average_rainfall2/average_rainfall2.py | 1,062 | 4.5 | 4 |
# Ask user for how many years of rainfall to be used in calculations.
num_years = int(input('How many years? '))
# Determine how many years.
print()
for years in range(num_years):
total = 0 # Initialize an accumulator for number of inches of rainfall.
print('---------------')
print('Year',years + 1)
print('---------------')
# Display the amount of months within a range of 12.
for num_months in range(12):
print('Month',num_months + 1, end='')
print()
num_inches = float(input('How many inches? ',))# Ask for user's inches.
# Perform calculation for total amount of inches.
total += num_inches
# Print total rainfall for that year.
print('Total rainfall for year',years + 1, 'is:',total,'Inches')
average = total / 12 # Perform calculation for average.
print('Average rainfall for year',years + 1, 'is:',\
format(average,'.2f'),'Inches')
| true |
02e8b105d9395302f5a9452f81aa0c5ede756db0 | CSmel/pythonProjects | /feet_to_inches/feet_to_inches.py | 458 | 4.25 | 4 | # Constant for thenumber of inches per foot
INCHES_PER_FOOT = 12
# Main functions.
def main():
# Get the number of feet from the user
feet = int(input('How many feet? '))
# Display and convert feet to inches
print(feet,'feet converted to inches is:',feet_to_inches(feet),'inches.')
# The feet_to_inches function converts feet to inches.
def feet_to_inches(feet):
return feet * 12
# Call the main function.
main()
| true |
139f211d82629d5c2946b2b9a514bcc1b50f6934 | pmkiedrowicz/python_beginning_scripts | /random_string.py | 370 | 4.21875 | 4 | '''
Generate random String of length 5.
String must be the combination of the UPPER case and lower case letters only. No numbers and a special symbol.
'''
import random
import string
def generate_string(length):
base_chars = string.ascii_letters
return ''.join(random.choice(base_chars) for i in range(length))
print("Random string: ", generate_string(5))
| true |
e4c272f006a7210ca82b2d331cd8198ceb47deed | pmkiedrowicz/python_beginning_scripts | /select_multiple_columns_csv.py | 394 | 4.1875 | 4 | '''
Find each company’s Higesht price car
'''
import pandas
# Read .csv file
pd = pandas.read_csv("Automobile_data.csv")
# Create multidimension list grouped by company
companies = pd.groupby('company')
# Use below script for debugging
# for i in companies:
# print(i)
# Select from each group row with max price value
max_price = companies['company', 'price'].max()
print(max_price)
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.