blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
8e10a30c79bacca1ec4e6db28c409a559b066aa2 | ngirmachew/Get-Programming-with-Python | /u3m5_interacting_with_the_user.py | 651 | 4.125 | 4 | print("hello")
print(5*2+3**5)
print("new"+"ton")
top = 22
bottom = 7
pi_approx = top/bottom
print(pi_approx)
print(top,"/",bottom,"=",pi_approx)
to_print = str(top)+"/"+str(bottom)+"="+str(pi_approx)
print(to_print)
# input stored as a string - concatenate
a = input("Enter one number: ")
b = input("Enter another number: ")
print(a+b)
# input stored as a string - convert to int
a = int(input("Enter one number: "))
b = int(input("Enter another number: "))
print(a+b)
#############
# quick check
#############
# get user input
day = input("What day of the week? ")
num = int(input("How many times? "))
# show the phrase
print("It's", day*num)
| true |
5d05bd2887ecd2b22f68450f2663b4505d0d1b00 | linzhp/patterns-in-python | /code/triangle_counters.py | 947 | 4.28125 | 4 | import itertools
import sys
##### This file contains different functions to find triangles in a graph.
#####
##### C. Seshadhri, Jan 2015
### wedge_enum(G) does a simple wedge enumeration by looping over the adjacency list of all vertices.
#### It technically outputs the number of wedges that participate in a triangle.
#### If the graph is undirected, this is three times the number of triangles. If
#### the graph is a DAG, this is exactly the number of triangles.
####
def wedge_enum(G):
closed = 0 # Initialize number of closed wedges
for node1 in G.vertices: # Loop over all nodes
for (node2, node3) in itertools.combinations(G.adj_list[node1],2): #Loop over all pairs of neighbors of node1
if G.isEdge(node2,node3): # If (node2, node3) form an edge
closed += 1 # Then wedge participating in trianglehas been found!
return closed
| true |
7f5ada5d57bd85d0df3c6d9f61fe387c0ef7c75d | nmazaheri/project-euler | /4.py | 725 | 4.21875 | 4 | """
A palindromic number reads the same both ways.
The largest palindrome made from the product of
two 2-digit numbers is 9009 = 91 * 99.
Find the largest palindrome made from the product of two 3-digit numbers.
906609
"""
def p(num):
return (str(num) == str(num)[::-1])
def largest(top,bot):
palindrome = []
for x in range(top,bot,-1):
for y in range(top,bot,-1):
temp = x*y
if p(temp):
palindrome.append(temp)
return max(palindrome)
print largest(999,100)
"""
print max([(x*y) for x in range(100,1000) for y in range(100,1000) if p(x*y)])
result = [{x*y:(x,y)} for x in range(100,1000) for y in range(100,1000) if p(x*y)]
print result[result.index(max(result))]
"""
| true |
ad96963cd6e59f9e94d97a6594605460e6afea2d | Juaria/Jbeans | /Random num generation.py | 586 | 4.1875 | 4 | # write a funtion that returns a list/array of length n of randomly generated values, from low to high (inclusive)
import random
def rand_array(start, end, num):
int_num = []
for j in range(num):
int_num.append(random.randint(start, end))
return int_num
num = 5
start = 0
end = 20
print(rand_array(start, end, num))
# Taking input values from the user and displaying it as a string.
str = input("Enter comma seperated elements: ")
list = str.split(",")
print ("List: ", list)
# for example, input: cat, dog, bird ; output: ['cat' , 'dog', 'bird']
| true |
ff7ec0590293429f1c22216b6446033c52960640 | JosephTLyons/Interview_Question_Solutions | /java_revisited/string_programming/string_palindrome.py | 600 | 4.15625 | 4 | #!/usr/bin/env python3
# Write code to check a String is palindrome or not
# Solved
def isPalindrome(text):
text = text.lower()
textLength = len(text)
textLengthToCheck = int(textLength / 2)
for i in range(0, textLengthToCheck):
if text[i] != text[textLength - i - 1]:
return False
return True
# Should return true
print(isPalindrome("racecar"))
print(isPalindrome("tattarrattat"))
print(isPalindrome("MalayalAm"))
# Should return false
print(isPalindrome("face"))
print(isPalindrome("boy"))
print(isPalindrome("mountain"))
print(isPalindrome("rick james"))
| true |
f2a5089a3340a42a8433dbd6523f102ceab45cb3 | lorryzhai/test7 | /oh-my-python-master/oh-my-python-master/target_offer/021-使数组中奇数位于偶数前面/resort.py | 537 | 4.15625 | 4 | """
提目:输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有奇数位于数组的前半部分,所有偶数位于数组的后半部分。
总结:合理运用 Python 迭代器特性解决问题
"""
import unittest
def resort(s):
return list(filter(is_odd, s)) + list(filter(is_even, s))
def is_even(n):
return n & 1 == 0
def is_odd(n):
return n & 1 == 1
class Test(unittest.TestCase):
def test(self):
self.assertEqual([1, 3, 2, 4], resort([1, 2, 3, 4]))
| false |
140ac8d17b0163243b9b40dffb17e1104978989b | lorryzhai/test7 | /oh-my-python-master/oh-my-python-master/target_offer/016-数值的整数次方/power.py | 1,453 | 4.5625 | 5 | import unittest
"""
提目:实现函数double Power(double base, int exponent),求base的exponent次方。不得使用库函数,同时不需要考虑大数问题。
总结:需要考虑 base,exponent 为 0,正数,负数的情况
使用如下公式优化循环次数:
当n为偶数, a^n = a^(n/2) * a^(n/2)
当n为奇数, a^n = a^((n-1)/2) * a^((n-1)/2)) * a
利用位运算代替乘除提高效率:
利用右移一位运算代替除以2
利用位与运算代替了求余运算法%来判断一个数是奇数还是偶数
"""
def power_value(base, exponent):
if exponent == 0:
return 1
if exponent == 1:
return base
r = power_value(base, exponent >> 1)
r *= r
if exponent & 1 == 1:
r *= base
return r
def power(base, exponent):
if exponent == 0:
return 1
if base == 0:
return 0
r = power_value(base, abs(exponent))
if exponent < 0:
r = 1 / r
return r
class Test(unittest.TestCase):
def test(self):
r = power(2, 3)
self.assertEqual(pow(2, 3), r)
r = power(2, -3)
self.assertEqual(pow(2, -3), r)
r = power(-2, 3)
self.assertEqual(pow(-2, 3), r)
r = power(2, 0)
self.assertEqual(pow(2, 0), r)
r = power(0, 0)
self.assertEqual(pow(0, 0), r)
r = power(0, 4)
self.assertEqual(pow(0, 4), r)
r = power(0, -4)
self.assertEqual(0, r)
| false |
2076e323deb620aefd0eb00401c53a1672196c44 | pjjefferies/Project-Euler | /Problems/1. Multiples of 3 and 5.py | 1,385 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Project Euler
Problem 1
Multiples of 3 and 5
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
def isAMultiple(dividend, divisor):
return ((dividend % divisor) == 0)
def isAMultipleOf3Or5(value):
return (isAMultiple(value, 3) or isAMultiple(value, 5))
def sumDivisibleBy(dividend, divisor):
return int((divisor * (dividend // divisor) * (dividend // divisor + 1) / 2))
if __name__ == '__main__':
#Iterative Method
totalOfMultiples = 0
for i in range(1000):
if isAMultipleOf3Or5(i):
totalOfMultiples += i
print("The sum of all the multiples of 3 or 5 below 1000 is", totalOfMultiples)
#Mathematical Method
totalOfMultiples = sumDivisibleBy(999, 3) + sumDivisibleBy(999, 5) - sumDivisibleBy(999, 15)
print("The sum of all the multiples of 3 or 5 below 1000 is", totalOfMultiples)
"""
sum = sumDivisible(3) + sumDivisible(5) - sumDivisible(15)
e.g. sumDivisible(3) (from 1 to n) = 3+6+9+12+..+largest value up to n
sum(1, 2, 3, ..., n) = n * (n + 1) / 2
divisible by 3 = 3 * (1+2+3+4+...+largest value up to n divisible by 3 / 3)
= 3 * (1+3+3+4+...+n \ 3)
= 3 * (1/2*[(n/3)*(n/3 + 1)]
""" | true |
b48d905e1e6ff2eb0b6c05409e4361c8fa0b479f | MichaelORegan/52960_MPP_Assignment2_Recursion | /8_print_array_recursion.py | 588 | 4.28125 | 4 | # 8. Print an array Given an array of integers prints all the elements one per line. This is a little bit different as there is no need for a ’return’ statement just to print and recurse.
# define the function and pass an array to it
def print_array(n):
# setting a base case when nothing in the array return True
if len(n) == 0:
return True
# else print the first element (position zero),
# recursively move through the array to print it all
else:
print(n[0])
print_array(n[1:])
# simple array
a = (1,2,3,4,5)
# call to the function
print_array(a) | true |
7ba2de41fdf1927041f240477b4366d425986c8a | fumingivy/inf1340_2015_asst1 | /exercise2.py | 2,070 | 4.71875 | 5 | #!/usr/bin/env python
""" Assignment 1, Exercise 2, INF1340, Fall, 2015. Name that shape.
This module contains one function name_that_shape(). It prompts the user
to input the number of sides in a shape and outputs the name of the shape.
"""
__author__ = 'Rachel Lee and Ming Fu'
__email__ = "siuming.lee@mail.utoronto.ca and mm.fu@mail.utoronto.ca"
def name_that_shape():
"""
For a given number of sides in a regular polygon, returns the shape name
Test 1:
Input: 3
Expected Output:triangle
Actual Output: triangle
Test 2:
Input: 4
Expected Output: quadrilateral
Actual Output: quadrilateral
Test 3:
Input: 5
Expected Output: pentagon
Actual Output: pentagon
Test 4:
Input: 6
Expected Output: hexagon
Actual Output: hexagon
Test 5:
Input: 7
Expected Output: heptagon
Actual Output: heptagon
Test 6:
Input: 8
Expected Output: octagon
Actual Output: octagon
Test 7:
Input: 9
Expected Output: nonagon
Actual Output:nonagon
Test 8:
Input: 10
Expected Output: decagon
Actual Output: decagon
Test 9:
Input: 2
Expected Output: Error
Actual Output: Error
Test 10:
Input: 12
Expected Output: Error
Actual Output: Error
"""
# name the input
number_of_sides = raw_input("Enter the number of sides from 3 to 10:")
side3 = "3"
side4 = "4"
side5 = "5"
side6 = "6"
side7 = "7"
side8 = "8"
side9 = "9"
side10 = "10"
# assign a response to each expected output
if number_of_sides == side3:
print("triangle")
elif number_of_sides == side4:
print("quadrilateral")
elif number_of_sides == side5:
print("pentagon")
elif number_of_sides == side6:
print("hexagon")
elif number_of_sides == side7:
print("heptagon")
elif number_of_sides == side8:
print("octagon")
elif number_of_sides == side9:
print("nonagon")
elif number_of_sides == side10:
print("decagon")
else:
print("Error")
#name_that_shape() | true |
4119d706c5d31904ed93752675e2324826892f59 | Imanub5/Python | /Python Fundamentals/Hello World/Hello_World.py | 959 | 4.1875 | 4 | # 1. TASK: print "Hello World"
print("Hello World")
# 2. print "Hello Noelle!" with the name in a variable
name = "Iman"
print( "Hello", name, "!") # with a comma
print( "Hello " + name + "!") # with a +
# 3. print "Hello 42!" with the number in a variable
name = 1
print ("Hello, 1") # with a comma
print ("Hello" +str(1) + "!" ) # with a + -- this one should give us an error!
# 4. print "I love to eat sushi and pizza." with the foods in variables
fave_food1 = "Halal Munchies"
fave_food2 = "Dumplings"
print ("I love to eat {} and {}". format(fave_food1,fave_food2) ) # with .format()
print (f"i love to eat {fave_food1} and {fave_food2}" ) # with an f string
# Ninja Bonus: Print favorite TV Shows with the Shows in a variables
fave_Shows1 = "Cobra Kai"
fave_Shows2 = "Money Heist"
print ("My Favorite TV Shows are {} and {}". format(fave_Shows1,fave_Shows2) )
print (f"My Favorite TV Shows are {fave_Shows1} and {fave_Shows2}" )
| false |
754fa1856e9b5ab06106985ddc1faf8672e5e7c4 | jatkin-wasti/python_oop_pillars | /animal.py | 825 | 4.375 | 4 | # Creating an animal class as a SUPER/PARENT/BASE class
class Animal:
def __init__(self): # Initialising the Animal class
self.alive = True # Creating an attribute/variable
self.spine = True
self.lungs = True
self.eyes = True
def breathe(self): # Creating behaviours as methods
return "Keep breathing to stay alive"
def move(self):
return "Forwards, backwards, left, and right"
def eat(self):
return "Consume to stay alive"
def procreate(self):
return "Find a mate"
# Instantiate our class / create an object
# cat = Animal() # Creating an object of the Animal class
# We have abstracted the move() method from our parent class
# print(cat.move()) # We can see it has inherited all functionality and characteristics from Animal
| true |
e80e0fcb679c6f60a35d0c5eb779c2e5fc08a502 | ISE2012/ch5 | /while_num.py | 418 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Oct 14 07:44:37 2020
@author: ucobiz
"""
values = [] # initialize the list to be empty
userVal = 1 # give our loop variable a value
while userVal != 0:
userVal = int(input("Enter a number, 0 to stop: "))
if userVal != 0: # only append if it's valid
values.append(userVal) # add value to the list
print("Stopped!")
print(values)
| true |
3f93da4380f0b6dcd5704622afbc3686fd98cd24 | jonhandy/itp-w1-bubble-sort | /bubble_sort/main.py | 788 | 4.25 | 4 | """This is the entry point of the program."""
def bubble_sort(list_of_numbers):
was_sorted = True
while was_sorted:
was_sorted = False
for i in range(len(list_of_numbers)):
if i < len(list_of_numbers) - 1:
if list_of_numbers[i] > list_of_numbers[i+1]:
temp = list_of_numbers[i]
list_of_numbers[i] = list_of_numbers[i + 1]
list_of_numbers[i + 1] = temp
was_sorted = True
return(list_of_numbers)
if __name__ == '__main__':
print(bubble_sort([9, 1, 3, 11, 7, 2, 42, 111]))
| true |
bdfdbfda499305e1dc0474579fc1f1c0d03b7db8 | LawrenceELee/daily | /python/easy2v1.py | 1,499 | 4.40625 | 4 | '''
Simple program that calculates a value using formula/equation.
This example is an interest calculator.
version 1: straight forward code using if/case or case statements to display
options.
demos:
*simple interest vs compound interest.
usage: "python3 filename.py"
'''
def display_menu_and_read_choice():
'''
use a dictionary to store choices for easier additions.
rather than using if/else or case statements.
'''
print("1) Simple Interest")
print("2) Compound Interest")
return int(input("Enter the # of the choice: ")) #input returns a str
def read_input_and_calculate(choice):
capital = float(input("Enter capital: "))
interest_rate = float(input("Enter interest rate: "))
time = float(input("Enter time (years): "))
'''
There is a slight bug using this method to pass in the choice.
We don't know if the user picked a valid option until after we do the
calculation.
'''
if choice == 1:
print(simple(capital, interest_rate, time))
elif choice == 2:
print(compound(capital, interest_rate, time))
else:
print("Not a valid choice. Nothing was calculated")
def simple(capital, rate, time):
return capital * (1 + (rate * time))
def compound(capital, rate, time):
return capital * ((1 + rate) ** time)
def main():
'''
driver/tester.
'''
choice = display_menu_and_read_choice()
read_input_and_calculate(choice)
if __name__ =='__main__':
main()
| true |
467fc5befffc088dfda4a5f9489a62a4d7678d7b | EKarpovets/Python_Crash_Course | /Chapter_10/Exercise_10-7.py | 486 | 4.15625 | 4 | print("Please enter two numbers and I will give you their sum.")
print("Enter 'q' any time to quit.")
while True:
num1 = input("Enter the first number: ")
if num1 == 'q':
break
num2 = input("Enter the second number: ")
if num2 == 'q':
break
try:
num1 = int(num1)
num2 = int(num2)
except ValueError:
print("You should enter two numbers so that I could sum them.")
else:
summa = num1 + num2
print(summa) | true |
3d9ebf9cb1ae45d5cc145e888b86ddc0803d2c92 | vibhorverma2015/course | /python/Lists/assignment.py | 722 | 4.21875 | 4 | """
Write the function for checking the speed of drivers. This function should
have one parameter:speeed
* If speed is less then 70, it should print"OK".
* Otherwise, for every 5 km above the speed limit (70), it should give
the driver one demerit point and print the total number of demerit points.
for example, if the speed is 80, it should print
"points: 2".
* If the driver gets more than 12 points, the function should print:
"License suspended"
"""
speed = int(input())
demerit = 0
if speed < 70:
print("OK")
else:
diff = speed - 70
while diff > 0:
demerit += 1
if demerit > 12:
print("licence suspended")
break
diff -= 5
print(demerit)
| true |
4169e6a88a1ebcf3c9e53c5f5b911d80952c484c | magdeldin/tryHards | /first.py | 499 | 4.28125 | 4 | # tryHards
#! Hisham osman
# first python3 project
from tkinter import *
from tkinter import messagebox
top = Tk()
# Code to add widgets will go here...
top.geometry("350x500")
def helloCallBack():
messagebox.showinfo("Hello Python", "Hello World")
# 2 arguments: first = the name of the window. 2nd = string displayed in the message
B = Button(top, text="Hello", command = helloCallBack)
#B1 = Button(top, text = "Say Hello", command = hello)
B.place(x = 0, y = 0)
B.pack()
top.mainloop()
| true |
0bd8d46aded6afd00ad58dd7142ccb7e4418ece1 | dcDalin/MeLearningPython | /6_If_Else_Elif.py | 1,416 | 4.3125 | 4 | if True:
print('Condition was true')
# ==, <=, >=, !=
# Object Identity: is
language = 'Python'
if language == 'Python':
print('Language is python')
else:
print('No match')
if language == 'Python':
print('Language is python')
elif language == 'Java':
print('Language is Java')
elif language == 'C++':
print('Language is C++')
else:
print('No match')
# Python has no switch case statement... if elif else will do
# Boolean operations we can use
# and or not
user = 'Admin'
logged_in = True
if user == 'Admin' and logged_in:
print('Admin Page')
else:
print('Bad creds')
# not used to switch a boolean
if not logged_in:
print('Please log in')
else:
print('Logged in')
# two objects can be equal but not the same in memory
a = [1,2,3]
b = [1,2,3]
print(a == b)
print(a is b)
print(id(a))
print(id(b))
# conditions evaluating to false
# False Values:
# False
# None
# Zero of any numeric type
# An empty sequence e.g. '', (), []
# An empty mapping e.g. {}
condition = False
if condition:
print('Evaluated to tru')
else:
print('Evaluated to false')
condition = 0
if condition:
print('Evaluated to tru')
else:
print('Evaluated to false')
condition = ()
if condition:
print('Evaluated to tru')
else:
print('Evaluated to false')
condition = ''
if condition:
print('Evaluated to tru')
else:
print('Evaluated to false') | true |
4e1129c1df1f36da0d5702498e990a3ebd9fbb6c | mustafahoda/data-structures | /LinkedList/LinkedList.py | 1,710 | 4.1875 | 4 | from LinkedList import Node
class LinkedList:
def __init__(self, head = None):
self.head = head
def insert(self, val):
new_node = Node(val) # create the node itself
new_node.set_next(self.head) # point the new node to point to previous node
self.head = new_node # change the actual head of the linked list to point to the new node itself
def count(self):
current = self.head
count = 0
while(current.next):
current = current.get_next()
count = count + 1
return count
def search(self, val_to_find):
current = self.head
# proceed to see the rest of the nodes in the LinkedList.
while (current.next):
if current.val == val_to_find:
return current
current = current.get_next()
# if goes through the entire list and can't seem to to find the val
print("Cant find the value in the LinkedList")
def delete(self, val_to_delete):
current = self.head
previous = None
# Best case scenario where the first one is a match
if current.val == val_to_delete:
self.head = current.get_next() # just move the pointer of the LinkedList to the next one.
return 1
# In other cases, iterate through the rest of the LinkedList and see what's going on.
while (current.next):
previous = current
current = current.get_next()
if current.val == val_to_delete:
previous.set_next(current.get_next())
return 1
print("Couldn't find the value to delete after going through the entire list.")
| true |
53fc00b579048f8b670190b17714a7af0d525968 | jisazac/quant-finance-COL | /mathfin_utils/simple_interest.py | 1,088 | 4.28125 | 4 | class simple_interest:
"""
a) EL capital sobre el cual se calcula el interes no se aumenta con los intereses causados
b) No hay reinversion de los intereses, y por ende no hay intereses sobre los intereses
c) El valor de una inversion aumenta linealmete en el tiempo
"""
def __init__(self,rate=0.0, periodicity="",currency="COP"):
self.rate=rate
self.period=periodicity
self.currenc=currency
def __str__(self):
display = str(self.rate)+"%"+" "+"de tasa de interes simple"+"\n"
display += "Con periodiciad:"+" "+str(self.period)+"\n"
display += "Expresado en "+self.currenc
return display
class time_of_investment:
def __init__(self,number_of_periods=0,periodicity=""):
self.number_of_periods=number_of_periods
self.period=periodicity
def __str__(self):
return "La inversion se da durante: "+str(self.number_of_periods)+" "+str(self.period)
if __name__ == '__main__':
i1=simple_interet(0.03,"month")
print (i1)
t=time_of_investment(3,"month")
print (t) | false |
6eec05781048606e7830ac31fd75d5a57cd24239 | AlexandrKarpov712/Projects | /Homework_5_basic.py | 1,936 | 4.21875 | 4 | import mymodule as m
def fact():
"""Calculating the factorial of a number using a function.
Input arguments: n, must be integer.
Output: factorial of a number.
"""
def factorial(n):
"Calculating the factorial of a number without recursion"
fact = 1
for i in range(1, n + 1):
fact *= i
return fact
while True:
try:
n = int(m.text("""Введите натуральное число
для вычисления факториала: """))
except:
print('Еще раз')
continue
else:
print(f"Факториал равен: {factorial(n)}")
break
def bank():
"""Calculating the deposit.
Input arguments: sum, percent, time, must be integers.
Output: amount of money on the deposit.
"""
def deposit(a, b, c):
"""Deposit calculation function"""
for i in range(time):
dep = (sum + (sum*percent)/100)
return dep
while True:
try:
sum = int(m.text("Введите размер взноса: "))
percent = int(m.text("Введите банковский процент: "))
time = int(m.text("Введите количество месяцев: "))
except:
print('Еще раз')
continue
else:
print(f"""Предполагаемая сумма денег на вкладе:
{deposit(sum, percent, time)}""")
break
while True:
next_step = m.text(
"""
Выберите задачу:
Факториал: 1
Копилка: 2
Выход: Enter
"""
)
if not next_step:
print("Всего хорошего...")
break
else:
m.choose_task(next_step, fact, bank) | true |
d3eeb266213611a0735224bd09deacb50ccaebea | AlexandrKarpov712/Projects | /Homework_4_expert.py | 1,960 | 4.1875 | 4 | """Solving a math example.
Input arguments: signs of mathematical operations, brackets, numbers
numbers must be integer.
Output: solved example.
"""
import mymodule as m
import requests
def LIST(s):
"""Converting a string to a list."""
L = []
flag = True
l = len(s)
for i in range(l):
if s[i].isdigit() and flag:
t = ""
j = 0
while s[i + j].isdigit():
t += s[i + j]
if i + j == l - 1:
break
j += 1
L.append(t)
flag = False
elif not s[i].isdigit():
L.append(s[i])
flag = True
return L
def POL(L):
"""Converting a list to a reverse polish notation."""
S, L2 = [], []
table = {"*": 1, "/": 1, "+": 0, "-": 0, "(": -1, ")": -1}
for i in L:
if i.isdigit():
L2.append(i)
elif i == "(":
S.append(i)
elif i == ")":
while S[-1] != "(":
L2.append(S.pop())
S.pop()
else:
while len(S) != 0 and (table[S[-1]] >= table[i]):
L2.append(S.pop())
S.append(i)
while len(S) != 0:
L2.append(S.pop())
return L2
def CALC(L):
"""Calculations."""
St = []
for i in L:
if i == '+':
St.append(int(St.pop()) + int(St.pop()))
elif i == '-':
St.append(-int(St.pop()) + int(St.pop()))
elif i == '*':
St.append(int(St.pop()) * int(St.pop()))
elif i == '/':
a = int(St.pop())
b = float(St.pop())
St.append(b/a)
else:
St.append(i)
return St[0]
s = m.text("Введите пример: ")
L = LIST(s)
L = POL(L)
print(f"Ответ: {int(CALC(L))}")
| true |
df1b86fdd835ba8219a11560243447d4f5bfa21e | 1914866205/python | /pythontest/day01.py | 734 | 4.15625 | 4 | """
将华氏温度转换为摄氏温度
提示:华氏温度到摄氏温度的转换公式为: C=(F-32)/1.8
"""
import math
f = float(input('请输入华氏温度:'))
c = (f-32)/1.8
print('%.1f华氏度=%.1f摄氏度' % (f, c))
"""
输入半径计算圆的周长和面积
"""
radius = float(input('请输入圆的半径:'))
perimeter = 2*math.pi*radius
area = math.pi*radius*radius
print('周长:%.2f' % perimeter)
print('面积:%.2f' % area)
"""
输入年份 如果是闰年输出True 否则输入false
"""
year = int(input('请输入年份:'))
# 如果代码太长写成一行不便于阅读 可以使用、对代码进行折行
is_leap = (year % 4 == 0 and year % 100 != 0)or \
year % 400 == 0
print(is_leap)
| false |
597c96adf8880225cc8f5112b2b970b15f5bb9be | katiejduane/algorithms_dataStructures | /grokkingAlgorithms/selection-sort.py | 571 | 4.21875 | 4 | my_silly_array = [3, 5, 1, 10, 55, 2, 13, 84]
# function to find the (index of) smallest number in an array
def findSmallest(arr):
smallest = arr[0]
smallest_index = 0
for i in range(1, len(arr)):
if arr[i] < smallest:
smallest = arr[i]
smallest_index = i
return smallest_index
# print(findSmallest(my_silly_array))
def selectionSort(arr):
newArr = []
for i in range(len(arr)):
smallest = findSmallest(arr)
newArr.append(arr.pop(smallest))
return newArr
print(selectionSort(my_silly_array))
| true |
f4359d945bd5549a9c1fe360098d35d904234926 | driellevvieira/ProgISD20202 | /DanielHoskenPires/Atividade 3/Aula_3.py | 2,331 | 4.6875 | 5 | print ("Hello World")
# cerquilha serve para comentar o código na llinha e não será aparecido no programa
# cerquilha não será utilizado pelo programa também
'''essa função serve para comentar o código em blocos e não será aparecido no programa
print ("alguma coisa")
nada será utilizado pelo programa também '''
# variáveis
varString = "Daniel Hosken Pires"
print (varString)
varInt = 497
print (varInt)
varFloat = 9.95
print (varFloat)
varBool = True
print (varBool)
#identificando tipos de variáveis
varString = "Daniel Hosken Pires"
print (varString)
print (type(varString))
varInt = 497
print (varInt)
print (type(varInt))
varFloat = 9.95
print (varFloat)
print (type(varFloat))
varBool = True
print (varBool)
print (type(varBool))
# comando para importar módulos em Python
# uma opção é importar todo o pacote:
import math
print (math.sqrt(25))
#outra opção é importar apenas determinada função específica do pacote:
from math import sqrt
print (sqrt(25))
#Atribuição e aritméticos
resultadoSoma = 5+5
print (resultadoSoma) #atribuição
print (5+5) #soma e já vem imbutido no pacote padrão
print (2-5) #subtração e já vem imbutido no pacote padrão
print (2*5) #multiplicação e já vem imbutido no pacote padrão
print (10/2) #divisão e já vem imbutido no pacote padrão
print (2**10) #exponencialização e já vem imbutido no pacote padrão
print (21//9) #parte inteira da divisão e já vem imbutido no pacote padrão
print (21%9) #resto da divisão e já vem imbutido no programa
#operadores compostos
a, b, c = 2, 4, 8
a, b, c = a*2, a+b+c, a*b*c
print (a, b, c)
#operador lógico not: 0 -> 1 e 1-> 0
varLogica = True
print("Valor de 'not varLogica': ", not varLogica)
#operador lógico and
varLogica1 = True
varLogica2 = False
print("Valor de 'varLogica1 e varLogica2': ", varLogica1 and varLogica2)
#operador lógico or
varLogica1 = True
varLogica2 = False
print("Valor de 'varLogica1 e varLogica2': ", varLogica1 or varLogica2)
#expressões lógicas
print (2==2) #igual
print (2!=2) #diferente
print (2>2) #maior
print (2<2) #menor
print (2>=2) #maior ou igual
print (2<=2) #menor ou igual
#Input e print (básico)
num = input ("Digite um número: ")
print (num)
login = input("login: ")
senha = input("senha: ")
print ("O usuário informado foi: %s, e a senha digitada foi: %s. " %(login, senha))
| false |
52cf5e983d9b6a1ad206cb2126de2098fd341a8f | driellevvieira/ProgISD20202 | /Laura/Aula 4/Exercícios slides/ExercicioAula4.py | 668 | 4.1875 | 4 | #Exercício IMC - Aula 4
#Apresentar na tela apenas o IMC e a faixa na qual o operador se encaixa
peso = float(input ("Qual o seu peso em quilogramas? "))
altura = float(input ("Qual a sua altura em metros? "))
imc = peso / (altura**2)
print("Como o seu peso é: %skg e a sua altura é: %sm, logo, o seu IMC será: %s\n" %(peso, altura, imc))
if(imc<17):
print("Você está muito abaixo do peso.")
elif(17 <= imc < 18.5):
print("Você está abaixo do peso normal.")
elif(18.5 <= imc < 25):
print("O seu peso está dentro do normal.")
elif(25 <= imc < 30):
print("Você está acima do peso normal.")
else:
print("Você está muito acima do peso.") | false |
96acabf6b42de073c96672709060f63ce245663f | hangz88/store | /day12/面向对象.py | 1,543 | 4.34375 | 4 | # 姓名:周福航
# 小组:Python自动化7组
# 声明:本代码属本人所有,未经许可,严禁
class Car:
brand = ""
num = 0
color = ""
money = 0
site = 0
def run(self):
print("我驾驶着",self.brand,"飞驰在海边的公路上")
car = Car()
car.brand = "保时捷"
car.num = 4
car.color = "red"
car.money = 1000
car.site = 2
car.run()
class human:
__name = ""
__sex = ""
__age = 0
__job = ""
__weight = ""
def walk(self):
print(self.__name,"吃着火锅唱着歌")
def setname(self,name):
self.__name = name
def getname(self):
return self.__name
def setsex(self,sex):
self.__sex = sex
def getsex(self):
return self.__sex
def setjob(self,job):
self.__job = job
def getjob(self):
return self.__job
def setage(self,age):
self.__age = age
def getage(self):
return self.__age
def setweight(self,weight):
self.__weight = weight
def getweight(self):
return self.__weight
def showme(self):
print(self.__name,"是她的名字.毫无疑问,我被",self.__name,"的",self.__sex,"性魅力所吸引,",self.__age,"的年龄正值青葱",self.__weight,"Kg的身材曼妙不已。","我要去了解她的工作",self.__job,"到底是什么,才能更好的靠近她。")
human = human()
human.setname("jane")
human.setsex("女")
human.setage(21)
human.setjob("精算师")
human.setweight("45")
human.showme()
human.walk()
| false |
86d3497c94cc03cb5cc5a14e548d639d8522f09e | eduardox23/CPSC-115 | /HW 11_09/Time.py | 2,247 | 4.40625 | 4 | class Time(object):
'''Represents the time of day in the 24-hour notation.
Attributes: hour, minute, second.'''
def __init__(self, hour=0, minute=0, second=0):
'''Instantiates a Time object. Unless specified otherwise, it is
initialized to 00:00:00.'''
self.hour = hour
self.minute = minute
self.second = second
def __str__(self):
'''Returns a string representation of a Time object.'''
return '%.2d:%.2d:%.2d' % (self.hour, self.minute, self.second)
def to_hours(self):
'''Returns the number of hours that the current time represents.'''
return self.hour
def to_minutes(self):
'''Returns the number of minutes that the current time represents.'''
return self.hour * 60 + self.minute
def from_hours(self, hours):
'''Sets the hours of the current time to a specified value of hours.'''
self.hour = hours % 24
def from_minutes(self, minutes):
'''Sets the minutes and, if necessary, the hours, of the current time
to a specified value of minutes.'''
self.hour = (minutes / 60) % 24
self.minute = minutes % 60
def h_increment(self, hours):
'''Increments the current time with a specified amount of hours.'''
self.from_hours(self.to_hours() + hours)
def m_increment(self, minutes):
'''Increments the current time with a specified amount of minutes.'''
self.from_minutes(self.to_minutes() + minutes)
def to_seconds(self):
'''Returns the number of seconds that the current time represents.'''
return self.hour * 60 * 60 + self.minute * 60 + self.second
def from_seconds(self, seconds):
'''Sets the seconds and, if necessary, the minutes and the seconds, of the
current time to a specified value of seconds.'''
self.hour = (seconds / 3600) % 24
self.minute = (seconds / 60) % 60
self.second = seconds % 60
def s_increment(self, seconds):
'''Increments the current time with a specified amount of seconds.'''
self.from_seconds(self.to_seconds() + seconds)
def difference(self, another_time):
'''Returns the difference between two specified times.'''
diff_time = Time()
diff_time.from_seconds(abs(self.to_seconds() - another_time.to_seconds()))
return diff_time
| true |
e09d11602f00d0f7618f4875cf781f9192aee57e | eduardox23/CPSC-115 | /lab 20-10-2010/palindrome2.py | 463 | 4.375 | 4 | #
# File: reverse.py
# Author: Vlad Burca
# Lab Section: Wednesday
#
# Created: 10/20/2010
# Last Modified: 10/20/2010
#
# Exercise 2.2
#
def reverse(s):
if len(s) == 0:
return s
else:
return s[len(s)-1] + reverse(s[0:len(s)-1])
s1 = raw_input(' Enter a word in lower-case letters: ')
s2 = reverse(s1)
if s1 == s2:
print ' The word "' + s1 + '" is a palindrome. '
else:
print ' The word "' + s1 + '" is not a palindrome. ' | true |
d65d64a8a91694e859dbea3a2e710aee86125ff8 | ian-bateman/toy-problems | /Codewars/Python/6KYU/6KYU-multiples-of-3-or-5.py | 506 | 4.25 | 4 | # https://www.codewars.com/kata/multiples-of-3-or-5/python
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
# Finish the solution so that it returns the sum of all the multiples of 3 or 5 below the number passed in.
# Note: If the number is a multiple of both 3 and 5, only count it once.
# Courtesy of ProjectEuler.net
def solution(number):
return sum(val for val in range(number) if val % 3 == 0 or val % 5 == 0) | true |
62c2795f01437e54d75d0a733903048dd2cce6af | AcubeK/LeDoMaiHanh-Fundamental-C4E23 | /Season 1/homework_no1/part1/_3.py | 235 | 4.15625 | 4 | # Write a program that converts Celsius (0C) into Fahrenheit (0F)
print("Program: Celcius to Fahrenheit converter.")
oC = int(input("Please enter the temperature in Celcius (number): "))
oF = oC*9/5 +32
print(oC, "(C) =", oF, "(F)") | true |
2c9f20b755959fcfa82990f0fb5a84a464512221 | AcubeK/LeDoMaiHanh-Fundamental-C4E23 | /Season 3/homework_03/word_jumble_1.py | 599 | 4.15625 | 4 | # scramble a specific word and let user guesses
from random import *
print("Enter x to give up.")
chsnwrd = "salvation"
b = list(chsnwrd) #break down the words into list
shuffle(b)
c = ' '.join(b) #join the shuffled words into one
print(c) #can't jam straight in?
while True:
x = input("Guess the unscrambled word: ")
if x == chsnwrd:
print("Ah-ha, correct!")
break
elif x == "x":
print("Aw, the correct word was:", chsnwrd)
break
else:
print("Try again.") | true |
94e525decfe0e7384a52041f3ab11435af9a41d9 | AcubeK/LeDoMaiHanh-Fundamental-C4E23 | /Lab/Lab 3/calculator.py | 356 | 4.15625 | 4 | a = int(input("Enter number a = "))
x = input("Operator (+, -, x, /): ")
b = int(input("Enter number b = "))
print(a, x, b, "=", end =" ")
if x == "/":
print(a/b)
if b == 0:
print("Can't divide by zero")
elif x == "x":
print(a*b)
elif x == "+":
print(a+b)
elif x == "-":
print(a-b)
else:
print("\n", "Command not valid.")
| false |
db3aa00e2feb74970034f07808784a241fa4555a | ashwin-ganesh23/curriculum_dev | /peerbuds/intro/intro_algs.py | 864 | 4.125 | 4 | """
Introduction to Algorithms
Algorithms are problem-solving methods used by software engineers
They can be thought of as step by step directions to solving a problem
"""
# write an block of code that asks for an input number from the user
# and print whether the number is even or not
not_complete = True
while not_complete:
user_num = input("Enter a whole number of your choosing: ")
try:
int(user_num)
if user_num % 2 == 0:
print("Your number is even")
else:
print("Your number is odd")
not_complete = False
except ValueError:
print("Not an integer")
# write a block of code that iterates through a string entered from input and prints the number of letters entered
input_str = input("Enter a message: ")
for letter in input_str:
count += 1
print(str(count) + " letters entered")
#or
# print(len(input_str) + " letters entered")
| true |
b5c08f84cdf53c8256a52367025efb06fd417e3f | ashwin-ganesh23/curriculum_dev | /Free_Material/Lists/lists.py | 1,863 | 4.28125 | 4 | """
Introduction to Lists
Lists are a built-in Class in python. Lists are referential structures that store sequences of objects
They are array-based sequences and are zero indexed, which means a list of length n has elements indexed from 0 to n-1
"""
#lst_name[start:stop:step]
# num_list = [0, 1, 2, 3, 4]
# print(num_list[1::2])
# count = 0
# for var in num_list:
# count = count + 1
# print(count)
# print(len(num_list))
# lst = ['a', 'b', 'c']
# final_str = ''
#
# for letter in lst:
# print(letter)
#
# for x in range(len(lst)):
# final_str += lst[x] + " "
# print(str(x) + " iteration")
#
# print(final_str)
# print(num_list[::2])
#
# name_list = ['Ashwin', 'Surag', 'Sahil', 'Chris']
#
# print(num_list + name_list)
#
# for num in num_list:
# print(num)
list_len = [1123123, 2, 3234, 43.0]
list_two = [2, 3, 5, 1]
list_len.sort()
print(list_len)
list_len += list_two
# print(list_len)
# list_len.insert(5, 3)
# list_len.append(100000)
# del list_len[-2:]
# print(list_len)
# def lst_len(lst):
# for i in list_len:
# count = count + 1\
# return(count)
# print("Swish! All money!!!!", len(list_len))
# name_list = []
#
# range_list = list(range(10)) #range(start, stop, step)
#
# print(range_list)
# len(lst) returns the number of elements in lst
# .insert(index, value) or .append(value) or .extend(sequence) methods can be used to build up a list. + or * operator can also be used
# lst[i] - accesses element at index i
# lst[start:stop:step] - returns elements from start up till stop with steps incrementing the index
# containment checks - in or not in
new_lst = sorted(list_len)
print(new_lst)
# .reverse()
# .sort()
# .index(value) / .remove() / var = lst.pop(index) / del lst[x:y]
# min(), max(), len(), sum() | true |
747dec977c91be149740c3e79e7fd7dcbdcc75a9 | BryCant/IntroToCryptography | /wk1/CaesarCipher.py | 1,716 | 4.5 | 4 | import string
# 0) Ask user whether program should encrypt or decrypt
enOrDe = input("Would you like to Encode or Decode your message? (E or D) ")
# 1) Ask user for a plaintext or ciphertext message (all lowercase).
message = input("Please enter your plaintext or ciphertext message (all lowercase): ")
# 2) Ask user for additive encryption shift
shiftNum = int(input("What is the caesar shift magnitude? "))
# 3) Shift message
shifted_message = ""
if enOrDe.lower() == 'e':
shift_dict = {i: string.ascii_lowercase[(i + shiftNum) % 26] for i in range(len(string.ascii_lowercase))}
for letter in str(message).lower():
shifted_message += shift_dict[string.ascii_letters.index(letter)] if letter in string.ascii_lowercase else letter
elif enOrDe.lower() == 'd':
shift_dict = {i: string.ascii_lowercase[(i - shiftNum) % 26] for i in range(len(string.ascii_lowercase))}
for letter in str(message).lower():
shifted_message += shift_dict[string.ascii_letters.index(letter)] if letter in string.ascii_lowercase else letter
else:
print('Invalid input!')
exit()
# 4) print shifted message.
print(f"Shifted message: \n{shifted_message}")
# alt way of shifting using ord and chr
shifted_message = ""
if enOrDe.lower() == 'e':
for letter in str(message).lower():
shifted_message += chr((((ord(letter) - 97) + shiftNum) % 26) + 97) if letter in string.ascii_lowercase else letter
elif enOrDe.lower() == 'd':
for letter in str(message).lower():
shifted_message += chr((((ord(letter) - 97) - shiftNum) % 26) + 97) if letter in string.ascii_lowercase else letter
else:
print('Invalid input!')
exit()
print(f"Shifted message again: \n{shifted_message}")
| false |
db468de1d61305df62ce44236895901519b88a45 | kmarie2/Foodtruck | /foodtruck data.py | 2,539 | 4.15625 | 4 | def customer():
print("Welcome to my food truck! I hope you are very hungry!")
name=input("What is your name, customer?")
print("Happy to serve you today",name)
def order():
print("I exclusively serve 3 food items; that may be a very small menu, but these items continue to attract and please all of my customers, so why add extra stuff, huh?")
print("My three items are fish tacos, chicken stir-fry, and my famous curry that comes in different spices of your choice! Also, you get a free cookie for each meal, my way of thanks for coming to my food truck!")
print("Ready to order? How many of each item do you want? You can say 0 if you don't want anything of something.")
def fishtacos():
fish=int(input("Do you have a taste for some fish tacos? How many of each item do you want?"))
if fish == 0:
print("Don't have a taste for that, huh?")
elif fish > 0:
print("Fintastique! Since you ordered that much, I will give you the same number in cookies!")
for arrow in range (fish):
print("Here's a cookie!")
def stirfry():
fry=int(input("Do you want the chicken stirfry? How many of each item do you want?"))
if fry == 0:
print("Don't have a taste for that, huh?")
elif fry > 0:
print("Cool! Don't let your chicken friends see you eat that though...chicken stirfry is amazing. Since you ordered that much, I will give you the same number in cookies!")
for arrow in range (fry):
print("Here's a cookie!")
def curry():
famous=int(input("Do you want to try my famous curry? How many of each item do you want?"))
if famous == 0:
print("Don't have a taste for that, huh?")
elif famous > 0:
print("Beautiful!")
spice=input("What is your spice level? Mild? Medium? Spicy?")
print("Nice. Keep on and curry on, that's my philosophy. Since you ordered that much, I will give you the same number in cookies!")
for arrow in range (famous):
print("Here's a cookie!")
def total():
num=input("Hey,I lost count of how much you have ordered.Numbers are not my thing sometimes. Can you tell me the total of food items you ordered?")
print("Okay.Sorry about that.You have ordered",num,"items!")
print("Thank you for visiting my food truck, I hope you enjoy the food. Have a nice day!")
def main():
customer()
order()
fishtacos()
stirfry()
curry()
total()
main()
| true |
96a6b198d33dec4e1b4ea26363a7262d6aa75393 | reshinto/Rock-Paper-Scissors | /RPS_class_single_player/Player.py | 1,092 | 4.125 | 4 | class Player:
num_of_players = 0
def __init__(self):
Player.num_of_players += 1
choice = input("Do you want to register your name (y/n)? ").lower()
if choice == "y":
self.name = input("Enter Player {} name: ".format(Player.num_of_players))
elif choice == "n":
self.name = "Player {}".format(Player.num_of_players)
else:
print("You have entered an invalid input! Player name will be set to default!!")
self.name = "Player {}".format(Player.num_of_players)
self.score = 0
def __repr__(self):
return self.name
def __str__(self):
return self.name
def show_score(self):
print("{}".format(self.name).ljust(20, " ") + "\t|\tScore: {}".format(str(self.score)))
def choice(self):
print("\n" + "{}'s turn".format(self.name).center(80, "#"))
text = "Choose your move!\n(r)ock, (p)aper, (s)cissors"
self.player_choice = input("{}: {}\n> ".format(self.name, text)).lower()
return self.player_choice | false |
657c7db2933cd32550df4852940852ccd340e8f7 | wandsen/PythonNotes | /StringFormatting.py | 996 | 4.125 | 4 | #String formatting using %s
myString = "Hello"
myFloat = 31.00000
myInt = 20
if myString == "Hello":
print("myString is String: %s" % myString)
if isinstance(myFloat, float) and myFloat == 31.0:
print("myFloat is Float: %f" % myFloat)
if isinstance(myInt, int) and myInt == 20:
print("myFloat is Float: %d" % myInt)
#Set the decimals for floats
print("myFloat in 2 decimal points is Float: {:.2f}".format(myFloat))
#Do note that comma is not needed in the print statement
myInt = 123
convertedIntToString = str(myInt)
print("Converted the integer: %d to string: %s" % (myInt, convertedIntToString))
#Formatting using .format
print("My String is: {0}, and my float is {1}".format(myString, myFloat))
#Combining decimals and formatting
origPrice = float(input("Enter the original price"))
discount = float(input("Enter discount percentage: "))
newPrice = (1 - discount/100) * origPrice
print("${1:.2f} discounted by {0:.0f}% is ${2:.2f} ".format(discount, origPrice, newPrice ))
| true |
613bb3c191b6817276b09938ca6d1b82e438b545 | orlova-lb/Hillil_Lilia | /Lesson14/homework_27.py | 1,222 | 4.3125 | 4 | """
Реализовать класс цифрового счетчика. Обеспечьте возможность установки максимального и минимального значений,
увеличения счетчика на 1, возвращения текущего значения.
"""
class Counter:
def __init__(self, _min, _max, _num):
if min > max or num > max or num < min:
print('Error, wrong numbers passed')
else:
self._min = _min
self._min = _max
self._min = _num
if self._num > _max:
self._num = _max
if self._num < _min:
self.num = _min
def setMax(self, x):
if self._min > x or self._num > x:
print('Error, wrong number passed')
else:
self._max = x
def setMin(self, x):
if x > self._max or self._num < x:
print('Error, wrong number passed')
else:
self._min = x
def add(self):
if self._num + 1 > self._max:
print('Error, counter overflow')
else:
self._num += 1
def showcurrent(self):
return self._num
| false |
9a622fee0de2f336b0ae8f65ee2fca18300dd03e | orlova-lb/Hillil_Lilia | /Lesson10/homework_21.py | 1,203 | 4.125 | 4 | """Необходимо написать функцию которая разворачивает исходный список наоборот.
Алгоритм прост и ваши действи заключаются в следующем: мы меняем местами 0-ый элемент с последним,
1-ый с предпоследним и д.т.
Итого количество таких обменов будет равно половине длины списка. Иначе элементы поменяются местами по-второму
кругу ивернутся в первоначальное положение.
Применять функцию revers() или срезы с шагом -1 нельзя. Так же, нельзя использовать дополнительные
переменные (можно использовать переменную цикла for) и списки."""
from random import randint
def reverse_list(lst):
for i in range(0, len(lst)//2):
lst[i], lst[len(lst)-i-1] = lst[len(lst)-i-1], lst[i]
my_list = [randint(0, 100) for _ in range(30)]
print(my_list)
reverse_list(my_list)
print(my_list)
| false |
9f156b81456f57aa41c9bc945e1814f079ab1aeb | romanosaurus/Python-programming-exercises | /ex30.py | 505 | 4.125 | 4 | '''
Define a function that can accept two strings as input and print the string with maximum length in console.
If two strings have the same length, then the function should print al l strings line by line.
'''
def compare():
arr = []
for i in range(0, 2):
arr.append(input())
print('-----------')
if (len(arr[0]) > len(arr[1])):
print(arr[0])
elif (len(arr[0]) < len(arr[1])):
print(arr[1])
else:
print(arr[0])
print(arr[1])
compare()
| true |
f9cd8f997b500e734244b991ee77c59545f612f9 | Hrishikesh-3459/coders_club | /Day_4/2.py | 265 | 4.53125 | 5 | # Write a program to calculate power of a number using inbuilt pow() function
from math import pow
base = int(input("Please enter the base number: "))
power = int(input("Please enter the power number: "))
print(f"{base} to the power {power} is {pow(base, power)}")
| true |
3796fec1dd284b6c2d5626aa56c0f8ee190a8adb | Ksammar/EduPy | /task_2.3.py | 934 | 4.1875 | 4 | # Пользователь вводит месяц в виде целого числа от 1 до 12.
# Сообщить, к какому времени года относится месяц
# (зима, весна, лето, осень). Напишите решения через list и dict.
in_month = int(input('введите номер месяца: '))
list_month = ['', 'Зима', 'Зима', 'Весна', 'Весна', 'Весна', 'Лето', 'Лето', 'Лето', 'Осень', 'Осень', 'Осень', 'Зима']
print('Решение через list:')
print(list_month[in_month])
dict_month = {1: 'Зима', 2: 'Зима', 3: 'Весна',
4: 'Весна', 5: 'Весна', 6: 'Лето',
7: 'Лето', 8: 'Лето', 9: 'Осень',
10: 'Осень', 11: 'Осень', 12: 'Весна'}
print('Решение через dict:')
print(dict_month.get(in_month))
| false |
da81733acba6aa5a77df40accdbc63ea7932c695 | Ksammar/EduPy | /task_3.6.py | 459 | 4.1875 | 4 | # Реализовать функцию int_func(), принимающую слова из маленьких
# латинских букв и возвращающую их же, но с прописной первой буквой.
# Например, print(int_func(‘text’)) -> Text.
def int_func(arg):
return str(arg).title()
print(int_func('text'))
list_str = input('insert any words ').split()
for words in list_str:
print(int_func(words))
| false |
0687f030312d9cc9a40714ca612c688c0d0dd30f | Haruho/PythonProject | /Teach/tuple1.py | 574 | 4.15625 | 4 | #元祖 元祖不可变 所以比列表安全
a = (1,2,3)
print("元祖a的元素是:" , a)
#因为元祖不可变,所以不能append和pop也不能给元素赋值
print('元祖a的第一个元素',a[0])
#声明一个空的元祖
b = ()
print("一个空元祖" , b)
#声明一个元素的元祖
c = (1,)
print("c的长度是:" , len(c))
print("c的类型是:" , type(c))
#元祖的元素中存在一个list的话,那么元祖是不是就可变了?
dd = [4,5]
d = (1,2,3,[1,5])
print("元祖d的元素有:",d)
d[3][0] = 4
print("元祖d的元素有:",d) | false |
d77928f015c12a6c9de474be342fc732d1dd25a3 | zhengqun/sword_offer | /end_start_list.py | 1,246 | 4.15625 | 4 | #(1)在不改变链表指针格式的条件下,只能先遍历整个链表的值,将这些值存放在栈中,利用栈的优点后进先出,所以性能比较好
#(2)使用Python的insert函数,list.insert(index,value)
#(3)实现方法三:使用递归(略,效率不高)
class ListNode:
def __init__(self,x):
self.val=x
self.next=None
class use_insert_fun:
def end_start_print(self,listNode):
if listNode == None:
return []
#接收传入的值
result=[]
while listNode:
result.insert(0,listNode.val) #使用insert函数下标为0,可以实现链表中的值反转,每次的值都排在第一个位置上
listNode = listNode.next
return result
#实现方法一:
class Listnode1:
def __init__(self,x):
self.val = x
self.next=None
class Solution_fun:
def end_start_list(self,listnode):
if not listnode:
return []
#使用栈结构接收值
stack =[]
while listnode:
stack.append(listnode.val) #入栈操作
listnode = listnode.next
result = []
result = stack.pop() # 出栈操作
return result
| false |
afb99140cf59e50d8f301e03091c83feb9e284cd | ChidinmaKO/Chobe-Py-Challenges | /bites/bite143.py | 904 | 4.28125 | 4 | from collections import ChainMap
NOT_FOUND = "Not found"
group1 = {'tim': 30, 'bob': 17, 'ana': 24}
group2 = {'ana': 26, 'thomas': 64, 'helen': 26}
group3 = {'brenda': 17, 'otto': 44, 'thomas': 46}
def get_person_age(name):
"""Look up name (case insensitive search) and return age.
If name in > 1 dict, return the match of the group with
greatest N (so group3 > group2 > group1)
"""
if not (type(name) == str):
return NOT_FOUND
# Method 1
for k, v in {**group1, **group2, **group3}.items():
if k == name.lower():
return v
return NOT_FOUND
# Method 2
# Another way is to use ChainMap from the collections module.
# ChainMap is used to combine several dictionaries and it returns a list of dictionaries.
chain_map = ChainMap(group3, group2, group1)
result = chain_map.get(name, NOT_FOUND)
return result
| true |
83b4b96b4e2673d2a0000f74c7bdb65a304207f9 | kronkanok/workshop_2 | /if_else/ex1_if_else.py | 521 | 4.15625 | 4 | score = int(input("Enter your score: "))
if score >= 1 and score <= 100:
if score >= 80:
print(
"grade: A",
)
elif score >= 75:
print("grade: B+")
elif score >= 70:
print("grade: B")
elif score >= 65:
print("grade: C+")
elif score >= 60:
print("grade: C")
elif score >= 55:
print("grade: D+")
elif score >= 50:
print("grade: D")
else:
print("grade: F")
else:
print("Not found!") | false |
0d0e74b084894845a2de3a926d4be0834e405c8e | 1F659162/Find_Maximum_Value | /Find_Maximum_Value.py | 612 | 4.28125 | 4 | # 6206021620159
# Kaittrakul Jaroenpong IT 1RA
# Python Chapter 5 Example 2
print(">> Program Find maximum value <<")
number = int(input("Enter number of value : "))
if number < 3 :
number = 3
elif number > 10 :
number = 10
Max = 0
Str = " "
print(f"\nProgram get value {number} numbers.")
for i in range(1,number+1) :
value = int(input(f"Enter value #{i} : "))
if Max < value :
Max = value
if Str == " " :
Str = str(value)
else :
Str += ", " + str(value)
print(f"Your enter number : {Str}")
print(f"Maximum value number is {Max}")
print("Exit Program")
| false |
4b70649ee270c4c1395663d423745835eaac9227 | sauravvgh/sauravreacts.github.io | /44.py | 985 | 4.5625 | 5 | #Write a Python program to slice a tuple.
#create a tuple
tuplex = (2, 4, 3, 5, 4, 6, 7, 8, 6, 1)
#used tuple[start:stop] the start index is inclusive and the stop index
_slice = tuplex[3:5]
#is exclusive
print(_slice)
#if the start index isn't defined, is taken from the beg inning of the tuple
_slice = tuplex[:6]
print(_slice)
#if the end index isn't defined, is taken until the end of the tuple
_slice = tuplex[5:]
print(_slice)
#if neither is defined, returns the full tuple
_slice = tuplex[:]
print(_slice)
#The indexes can be defined with negative values
_slice = tuplex[-8:-4]
print(_slice)
#create another tuple
tuplex = tuple("HELLO WORLD")
print(tuplex)
#step specify an increment between the elements to cut of the tuple
#tuple[start:stop:step]
_slice = tuplex[2:9:2]
print(_slice)
#returns a tuple with a jump every 3 items
_slice = tuplex[::4]
print(_slice)
#when step is negative the jump is made back
_slice = tuplex[9:2:-4]
print(_slice) | true |
897912977c6e75a46421a368be580d4836a67fdb | Puzyrinwrk/University-practice | /1. The basics.py | 913 | 4.40625 | 4 | # Task_1
# Write a simple function that calculates day of the week for given day of the month and given day of the week for the first day of the month.
# For example, if given day of the month is 7 and day of the week for the first day of the month is 3 (Wednesday) than function should return 2 (which means Tuesday).
# Function signature: def get_day_week (day, starting_dotw)
# Task_2
# Write a simple function which will count number of digits of an natural (integer positive) number.
# Function signature: def count_digits(n)
# Hint: len(str(n)) is wrong, these are features from next chapters, use functions from math 'module'
import math
def get_day_week(day, starting_dotw):
print((day + starting_dotw - 2) % 7 + 1)
a = int(input())
b = int(input())
get_day_week(a, b)
def count_digits(n):
return math.floor(math.log(n, 10) + 1)
n = 3714
print("Number of digits : % d" % (count_digits(n)))
| true |
7b8189dab313de8d53d74598fff7bd268073c424 | dewanshu77/Python717 | /ARITHMETIC OPERATIONS.py | 598 | 4.25 | 4 | print('welcome to the new topic which is arithmetic operations')
#
# If we wanna do mathematical equations while coding you can do it by doing this
o=10
o=o+5
print (o)
#we can use
#+ for addition
#- for substraction
#* for multiplication
#% for getting remainder
#/ for division and getting answer in float
#// for division and getting integer
#** for getting exponent
#gives 15 as answer
#AUGMENTED ASSIGNMENT OPERATOR
T=(52)
T+=7
print(T)
r=(23)
r/=500#= assignment operator being used here
print(r)
# and many more mathematical equations can be done
print('perfect') | true |
95554c78c4e7dad9cce79369cd536bb6c593f5a3 | ms0680146/leetcode-python | /Array/121_Best_Time_to_Buy_and_Sell_Stock.py | 1,091 | 4.1875 | 4 | '''
If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock),
design an algorithm to find the maximum profit.
Example1:
Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Not 7-1 = 6, as selling price needs to be larger than buying price.
Example2:
Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
'''
def maxProfit(prices):
min_price = float('inf')
max_profit = 0
for price in prices:
if price < min_price:
min_price = price
else:
max_profit = max(max_profit, price - min_price)
return max_profit
print(maxProfit([7,1,5,3,6,4])) # 5
print(maxProfit([7,6,4,3,1])) # 0
'''
解法:
設定最低股價及最高獲利。
遍歷一週的股價。
若股價小於最低股價的話,則將此價格更新為最低股價; 若股價大於最低股價的話,去計算獲利,若獲利大於最高獲利則更新最大獲利。
'''
| true |
2de1a8d9010df95d9ffba0079f98c2b9d3d07f76 | metasophiea/python3learning | /computationConcepts/mastermind/combinatorics.py | 1,194 | 4.15625 | 4 | import random
def fac(n):
""" factorial function: n! """
if n == 0: return 1
else: return (fac(n-1) * n)
def k_permutations(items, n):
""" yields every possible permutation of a list of length 'n', which only contains elements from the array 'items' """
if n==0: yield []
else:
for i in range(len(items)):
for ss in k_permutations(items, n-1):
if (not items[i] in ss):
yield [items[i]]+ss
def permutations(items):
""" yields every possible permutation of the array 'items' """
return k_permutations(items,len(items))
def random_permutation(list):
""" returns a random permutation of the array 'items' """
length = len(list);
max = fac(length);
index = random.randrange(0, max)
i = 0
for p in permutations(list):
if i == index:
return p
i += 1
def all_colours(colours, positions):
""" yields every possible permutation of a list of length 'n', which only contains elements from the array 'colours' which is in a randomized order """
colours = random_permutation(colours)
for s in k_permutations(colours, positions):
yield(s) | true |
54642386ed060e56875628c254d89a65cf98f375 | metasophiea/python3learning | /modules/standardFunctions/defaultFunctions.py | 2,897 | 4.34375 | 4 | # open
print("- open")
print("\topens a file and returns a link to said file")
file_ = open("data.txt","w")
print("42 is the answer, but what is the question?", file=file_)
file_.close()
print()
# zip
print("- zip")
print("\ttakes multiple lists and produces an iterator of tuples, matching the lists together")
print("\tthis iterator can be made into a list, or a dictionary")
zipList = zip( ["item_1", "item_2", "item_3", "item_4", "ignored item"], ["1_item", "2_item", "3_item", "4_item"],[1,2,3,4])
print( zipList )
print( list(zipList) )
print( dict( zip( ["item_1", "item_2", "item_3", "item_4"], ["1_item", "2_item", "3_item", "4_item"]) ) ) #zip remade as iterator was spent
print()
# max
# max(iterable[, key])
# max(arg1, arg2, *args[, key])
print("- max")
print("\ttakes a list or tuples and returns the element within that object with the highest value")
maximum = max( [1,2,3] )
print(maximum)
print()
# one can also find the highest value in a dictionary with this function like so
dictionary = {"key1":1,"key2":20,"key3":3}
print( max(dictionary) ) # this gets the largest key
print( max(dictionary,key=dictionary.get) ) # this gets the key with the largest value
print()
# range
print("- range")
print("\ttakes some argument are produces an iterator of values")
print("\trange(begin,end, step)")
print(list( range(9) ))
print(list( range(0,8) ))
print(list( range(0,8,2) ))
print(list( list(range(10,-10,-1)) ))
print()
# locals
print("- locals")
print("\treturns all the local scope variables in dictionary form")
print( locals() )
print()
# dir
print("- dir")
print("\tprints the valid attributes and methods for the namespace provided")
print("if none is provided, the current local scope is used")
print( dir() )
print()
# filter(func, seq)
# func - some input function
# seq - a sequence of objects (eg. list) upon which the func will be applied one by one. Function must return a boolean value
# this function returns an iterator or the results
# This function applies the function 'func' to each object in the sequence, if the result of that function is 'true' the object is added to the returned sequence
aList = [0,1,2,3,4,5,6,7,8,9]
noOdds = lambda input : input%2!=0
noEvens = lambda input : input%2==0
print(list( filter(noOdds,aList) ))
print(list( filter(noEvens,aList) ))
print()
# getattr(obj, attribute, default)
# obj - the object of interest
# attribute - the attribute in the object to access (as a string)
# default - the value to return if the object cannot return a value for the attribute
# this function searches the object for the attribute provided (in the usual way) if none is found, the default attribute is returned
class exampleClass:
pass
anObj = exampleClass()
anObj.newAttribute = "Hello"
print( anObj.newAttribute )
print( getattr(anObj ,"newAttribute", "oops") )
print( getattr(anObj, "fakeAttribute", "oops") )
print() | true |
e32a0b6da0c6a4eb57bbe7b5b9de245fbaae2325 | georgek2/Learn_Programming | /Projects/Pandas.py | 886 | 4.15625 | 4 | '''
students = ['Ben', 'Abel', 'Zach', 'Fine', 'Jane', 'Luke', 'Kev', 'Mercy']
indexes = [42, 50, 36, 17, 28]
indexes.insert(-1, 788)
print(indexes)
students.append(indexes)
print(students)
'''
import pandas as pd
'''
web = {'Day': [1, 2, 3, 4, 5, 6], "Visitors": [34, 65, 45, 45, 34, 35], 'Bounce': [3, 4, 2, 2, 4, 3]}
df = pd.DataFrame(web)
"Slicing the dataframe by printing the number of required rows using HEAD AND TAIL functions"
print(df.head(4))
print(df.tail(4))
'''
"Merging data frames "
df1 = pd.DataFrame({'HPI': [40, 46, 78, 60, 84], 'INT_rate': [3, 4, 6, 3, 2], 'GDP': [56, 54, 67, 87, 34]},
index=[2004, 2005, 2006, 2007, 2008])
df2 = pd.DataFrame({'HPI': [40, 46, 78, 60, 84], 'INT_rate': [3, 4, 6, 3, 2], 'GDP': [56, 54, 67, 87, 34]},
index=[2009, 2010, 2011, 2012, 2013])
axe = pd.merge(df1, df2)
print(axe)
| false |
e93503baf9143fa48c09d1972928db9fd4db236b | neilmarshall/Project_Euler | /059/PE_59.py | 2,871 | 4.34375 | 4 | #! /usr/bin/env python3.7
"""
Each character on a computer is assigned a unique code and the preferred
standard is ASCII (American Standard Code for Information Interchange). For
example, uppercase A = 65, asterisk (*) = 42, and lowercase k = 107.
A modern encryption method is to take a text file, convert the bytes to ASCII,
then XOR each byte with a given value, taken from a secret key. The advantage
with the XOR function is that using the same encryption key on the cipher text,
restores the plain text; for example, 65 XOR 42 = 107, then 107 XOR 42 = 65.
For unbreakable encryption, the key is the same length as the plain text
message, and the key is made up of random bytes. The user would keep the
encrypted message and the encryption key in different locations, and without
both "halves", it is impossible to decrypt the message.
Unfortunately, this method is impractical for most users, so the modified
method is to use a password as a key. If the password is shorter than the
message, which is likely, the key is repeated cyclically throughout the
message. The balance for this method is using a sufficiently long password key
for security, but short enough to be memorable.
Your task has been made easy, as the encryption key consists of three lower
case characters. Using cipher.txt (right click and 'Save Link/Target As...'),
a file containing the encrypted ASCII codes, and the knowledge that the plain
text must contain common English words, decrypt the message and find the sum of
the ASCII values in the original text.
Solution: 107359
"""
from itertools import cycle
class Cypher(object):
"""
Class to decrypt a string of ASCII character codes using the XOR
encryption / decryption algorithm, for a given key
"""
def __init__(self, key):
"""
Initialise with key to decrypt messages; if key is shorter than
message to be decrypted then the key will repeat
"""
self.key = key
def encrypt(self, message):
"""
Return encrypted message
Args:
message (string): Message to be encrypted
Returns:
int list: List of ASCII character codes for encrypted message
"""
return [ord(k) ^ ord(c) for k, c in zip(cycle(self.key), message)]
def decrypt(self, characters):
"""
Return decrypted message
Args:
characters (int list): List of ASCII character codes to decrypt
Returns:
string: Decrypted message
"""
return ''.join(chr(ord(k) ^ c) for k, c in zip(cycle(self.key), characters))
if __name__ == '__main__':
with open("p059_cipher.txt", 'rt') as f:
characters = map(int, f.read().split(','))
message = Cypher("god").decrypt(characters)
print(message, f"\nSolution: {sum(ord(c) for c in message)}", sep='\n')
| true |
baaf344a6ed8af5ab83b23783d98ca92ce08e27b | neilmarshall/Project_Euler | /038/PE_38.py | 2,051 | 4.1875 | 4 | """
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?
NOTES:
Since n > 1, we will be concatenating an integer with a tuple at least
equal to (1, 2) - so the integer cannot be greater than 4 digits in length,
i.e. it must be no greater than 9,999.
So we check each integer from 1 to 9,999. For each integer, consecutively
check if integer x n (starting from n = 1) contains previously seen digits,
and if not if the concatenated products are 1-through-9 pandigital.
Solution: 932718654
"""
from itertools import count
def PE_38():
"""
>>> PE_38()
932718654
"""
def is_pandigital(number):
return len(number) == 9 and set(str(number)) == set('123456789')
def generate_pandigital_number(base):
observed_digits, concatenated_products = set(), ''
for n in count(1):
product = str(base * n)
if observed_digits.isdisjoint(set(product)):
observed_digits |= set(product)
concatenated_products += product
if is_pandigital(concatenated_products):
return int(concatenated_products)
else:
return None
pandigital_numbers = set()
for base in range(1, 9999):
pandigital_number = generate_pandigital_number(base)
if pandigital_number is not None:
pandigital_numbers.add(pandigital_number)
return max(pandigital_numbers)
if __name__ == '__main__':
import doctest; doctest.testmod(verbose=True)
| true |
3a1092294d0a3c2e12235ab029b67733885d9aaa | gaonita/my_little_project | /hellopink/Sessions/2.if,while,pseudocode,errors/ex2.14.calculator.py | 790 | 4.15625 | 4 | while True:
print("0.Quit\n1.Add two numbers\n2.Subtract two numbers\n3.Multiply two numbers\n4.Divide two numbers")
response = int(input("Which operation do you want to do?"))
if response == 0:
exit()
elif response == 1:
a = int(input("choose first number"))
b = int(input("choose second number"))
print(a+b)
elif response == 2:
a = int(input("choose first number"))
b = int(input("choose second number"))
print(a-b)
elif response == 3:
a = int(input("choose first number"))
b = int(input("choose second number"))
print(a*b)
elif response == 4:
a = int(input("choose first number"))
b = int(input("choose second number"))
print(a/b)
else:
print() | false |
bb90979aa36ab33fb6f3130fd1674d2189146b5d | gaonita/my_little_project | /hellopink/Review/re_ex5.py | 1,307 | 4.15625 | 4 | #Add a try-except statment to the body of this function which handles a possible IndexError,
# which could occur if the index provided exceeds the length of the list. print an error message if this happens.
#
# def print_list_element(thelist, index):
# try:
# thelist[index]
# except (IndexError):
# print("Oops")
# print (thelist[index])
#
# mange=["mango",'maker','mange']
# print_list_element(mange,4)
#print or Return ??????
#12 This function adds an element to a list inside a dic of lists.
# Rewrite it to use a try-except statement which handles a possible KeyError
# if the list with the name provided doesn't exist in the dictionary yet, instead of checking beforehand
#whether it does.
#
def add_to_list_in_dict(thedict, listname, element):
try:
thedict[listname]
except KeyError:
print("There is no such list!")
if listname in thedict:
l = thedict[listname]
print ("{0} already has {1} elements.".format(listname, len(l)))
else:
thedict[listname] = []
print ("Created %s." % listname)
thedict[listname].append(element)
print ("Added {0} to {1}.".format(element, listname))
färg = ['en blå','en grön','en rosa']
magnus = {"färg":färg}
add_to_list_in_dict(magnus,'A','abc')
print(magnus)
| true |
b7f15ed7ea4958503fa701ff4321519d145b7271 | shefer87/Shefer_project | /season.py | 1,005 | 4.21875 | 4 | #Написать функцию season, принимающую 1 аргумент — номер месяца (от 1 до 12),
#и возвращающую время года, которому этот месяц принадлежит (зима, весна, лето или осень).
while True:
try:
month = int(input("Введите номер месяца от 1 до 12 "))
if month == 1 or month ==2 or month ==12:
print('Это зимний месяц')
elif month == 3 or month ==4 or month ==5:
print('Это весенний месяц')
elif month == 6 or month ==7 or month ==8:
print('Это летний месяц')
elif month == 9 or month ==10 or month ==11:
print('Это осенний месяц')
else:
print("Такого месяца не существует")
except ValueError:
print('Необходимо ввести число ') | false |
f75ec0a3ee5e904dc4adbadfdfd272e18c285e01 | usjanrana101/factorial-using-c-and-python- | /fact_using_py.py | 547 | 4.40625 | 4 | #This is the code to calculate factorial using funtion
import timeit
def factorial(n):
if n == 1:
return n
else:
return n*factorial(n-1)
# take input from the user
num = int(input("Enter a number n to get n! : "))
# check whether the number is negative
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of",num,"is",factorial(num))
print("Time taken to execute the code :> ",timeit.timeit(),"sec")
| true |
4e1c82be0a9012229058abe2a3cce4c4e23eab68 | Cor-Wysz/workbook_exercises | /ex3/ex3.py | 1,119 | 4.3125 | 4 | print("I will now count my chickens:") # An overview of PEMDAS
print("Hens", 25 + 30 / 6) # First; 30 / 6 = 5, then 25 + 5 = 30.0
print("Roosters", 100 - 25 * 3 % 4) # First; 25 * 3 = 75, then 75 % 4 = 3. Finally, 100 - 3 = 97.
# print(75 % 4) % is a module. The left integer is divided by the right. The value is equal to the remainder.
print("Now I will count the eggs:")
print(3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6) # First 1 / 4 = 0.25. Next, 4 % 2 = 0, because 4 / 2 has no remainder. Then 3 + 2 + 1 - 5 + (0) - 0.25 + 6 = 6.75
print("Is it true 3 + 2 < 5 - 7?") # 5 is not < -2, so line 12 is False.
print(3 + 2 < 5 - 7)
print("What is 3 + 2?", 3 + 2) # A question, an operation with addition.
print("What is 5-7?", 5 - 7) # A question, an operation with subtraction.
print("Oh, that's why it's False.")
print("How about some more.")
print("Is it greater?", 5 > -2) # 5 is greater than -2, so line 23 is True.
print("Is it greater or equal?", 5>= -2) # 5 is greater than or equal to -2, so line 24 is True.
print("Is it less or equal?", 5<= -2) # 5 is NOT less than or qual to -2, so line 26 is False.
| true |
20464e594503a90ae9b3da84523a44532a203e61 | haimyannai/AutoShop | /Python Files/VegetableClass.py | 2,302 | 4.3125 | 4 |
class Vegetable:
"""
A class used to represent Vegetable
...
Attributes
----------
vegName : str
The name of the website = Kishurit
vegPrice : str
The price of the vegetable
vegUnit : str
The unit of the vegetable
webSite : str
The website that this vegetable is sold
baseProd : str
The base name of a vegetable that is mostly close to in terms of meaning
Methods
-------
printVegetableDetails(self)
Prints the vegetable details - name, price, unit, website, base name
getRow(self)
Returns a tuple of the vegetable details (name, price, unit, website, base name)
"""
def __init__(self, name, price, unit, webSite, baseProd, prodIdWeb=None, link=None):
"""
Parameters
----------
name : str
The name of the Vegetable
price : str
The price that the Vegetable is sold for
unit : str
The unit that the vegetable is sold for
webSite : str
The website that the vegetable came from
baseProd : str
The base name of a vegetable that this vegetable is mostly close to in terms of meaning
"""
self.vegName = name
self.vegPrice = price
self.vegUnit = unit
self.webSite = webSite
self.baseProd = baseProd
self.prodIdWeb = prodIdWeb
self.Checked = False
self.link = link
def printVegetableDetails(self):
"""Prints the vegetable details - name, price, unit, website, base name
"""
print(self.vegName)
print(str(self.vegPrice))
print(self.vegUnit)
print(self.webSite)
print(self.baseProd)
print(self.prodIdWeb)
def getRow(self):
"""Returns a tuple of the vegetable details (name, price, unit, website, base name)
"""
return \
(self.vegName, self.vegUnit, float(self.vegPrice), self.webSite, self.baseProd, self.prodIdWeb, self.link, self.Checked)
| true |
c90de80e46f8ed78987cd1e2866f5694a544bf29 | lcnodc/wttd_exercicios | /w3resource/string/string.py | 2,644 | 4.5625 | 5 | # -*- coding: utf-8 -*-
'''
Exercises string.
'''
'''
1. Write a Python program to calculate the length of a string
'''
def calc_length_str(string):
return len ( string )
'''
8. Write a Python function that takes a list of words and returns the length of the longest one.
'''
def get_the_longest(args):
longest = 0
index_longest = 0
for i , arg in enumerate ( args ):
if len ( arg ) > longest:
longest = len ( arg )
index_longest = i
return args[index_longest]
'''
10. Write a Python program to change a given string to a new string where the first and last chars have been exchanged.
'''
def change_first_last(string):
return ''.join ( [string[-1] , string[1:-1] , string[0]] )
'''
11. Write a Python program to remove the characters which have odd index values of a given string.
'''
def remove_odd_index(string):
new_string = ''
for i in range ( len ( string ) ):
if i % 2 == 0:
new_string += string[i]
return new_string
'''
17. Write a Python function to get a string made of 4 copies of the last two characters of a specified string (length must be at least 2).
Sample function and result :
insert_end('Python') -> onononon
insert_end('Exercises') -> eseseses
'''
def change_str(string):
return string[-2:] * 4
'''
28. Write a Python program to add a prefix text to all of the lines in a string.
'''
def add_prefix(string):
return string.replace('\n','\n>')
'''
29. Write a Python program to set the indentation of the first line.
'''
# Corrigir
def set_indent(string):
return ''.join ( ['\t' , string] )
'''
34. Write a Python program to print the following integers with '*' on the right of specified width.
'''
def print_format(value):
return '{:*<4d}'.format ( value )
'''
47. Write a Python program to lowercase first n characters in a string.
'''
def lowercase_chars(string , n):
return string[:n].lowercase + string[n:]
'''
48. Write a Python program to swap comma and dot in a string.
#Sample string: \"32.054,23\"
# Expected Output: \"32,054.23\"
'''
# Corrigir
def format_decimal(string):
return string.replace ( ',' , '.' ).replace ( '.' , ',' , 1 )
if __name__ == "__main__":
sample_text = '''
Python is a widely used high-level, general-purpose, interpreted,
dynamic programming language. Its design philosophy emphasizes
code readability, and its syntax allows programmers to express
concepts in fewer lines of code than possible in languages such
as C++ or Java.
'''
print ( add_prefix ( sample_text ) )
| true |
d207187b177bc431bd880af1389042e916a682b2 | SDgrupo16Git/python01 | /ipython01.py | 1,083 | 4.21875 | 4 | # -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <codecell>
'''
Ejercicio: 01 Botella de Ron
Autores: Emilio Bello Villanueva y Juan Carlos de la Torre Macías
Fecha: 10/03/2015
Asignatura: Sistemas Distribuidos
Comentarios:
Para la resolución del ejercicio, se ha optado por la creación de una lista
que se inicia en el número 99 y acaba en el 0 y es recorrida mediante un bucle
for (recordemos que la condición se cumplirá mientras la variable numero no tome
el valor cero). Con el parámetro -1 indicamos que recorra la lista con saltos de
un solo elemento en sentido descendente.
La variable numero es de tipo int, por lo que debemos hacerle un casting a string
para poder usarla con print, se ha optado por el uso del operador %, si bien se podría
haber optado por:
print str(numero) + "bottles of ..."
'''
for numero in range(99,0,-1):
print "\t%s bottles of beer on the wall, %s bottles of beer.\n\tTake one down, pass it around, %s bottles of beer on the wall.\n" %(numero,numero,numero-1)
# <codecell>
| false |
4e9e03881b710c2ed214d9caea8b2eb7ce8d3ac4 | MrZakbug/MITx-6.00.1x | /Week 1/Problem 1.py | 402 | 4.25 | 4 | # Assume s is a string of lower case characters.
# Write a program that counts up the number of vowels contained in the string s. Valid vowels are: 'a', 'e', 'i', 'o',
# and 'u'. For example, if s = 'azcbobobegghakl', your program should print:
s = 'azcbobobegghakl' # example
count = 0
for c in s:
if c is 'a' or c is 'e' or c is 'i' or c is 'o' or c is 'u':
count += 1
print(count) | true |
5218485e7d23a06ef08df370e93388f255921155 | emre641/DevOps-Engineer-Assignment | /fibonacci.py | 353 | 4.25 | 4 | def fibonacci(n):
point1 = 0
point2 = 1
print(point1)
print(point2)
for i in range(n - 2):
point3 = point2 + point1
print(point3)
point1 = point2
point2 = point3
n = int(input("Bir n değeri giriniz..."))
print("Girdiğiniz n değerine kadar Fibonacci dizisinin sonucu : ")
fibonacci(n) | false |
2f53449a4deb2987c850325405fbceebac0deb77 | BlueTeche/Python | /Buiding a Basic Calculator.py | 305 | 4.3125 | 4 |
num1 = input("Enter a number: ")
num2 = input("Enter another number: ")
# result = num1 + num2 # will show only String
# result = int(num1) + int(num2) # this will make integer number.
result = float(num1) + float(num2) # this will make float number that can print decimal numbers
print(result) | true |
8ae768c932ab29605e6c1fd5f206d7bd1e4fc606 | thenavdeeprathore/LearnPython3 | /08_modules/12_RandInt_RandRange_Module.py | 908 | 4.46875 | 4 | # randint() Function:
"""
To generate random integer between two given numbers (inclusive)
random() in between 0 and 1 (not inclusive)
uniform(x,y) in between x and y ( not inclusive)
randint(x,y) in between x and y ( inclusive)
"""
from random import *
print(randint(1, 10)) # generate random int value between 1 and 10 (inclusive)
# randrange ([start], stop, [step])
"""
Returns a random number from range
start <= x < stop
start argument is optional and default value is 0
step argument is optional and default value is 1
randrange(10) generates a number from 0 to 9
randrange(1,11) generates a number from 1 to 10
randrange(1,11,2) generates a number from 1,3,5,7,9
"""
from random import *
print(randrange(10)) # generates a number from 0 to 9
print(randrange(1, 11)) # generates a number from 1 to 10
print(randrange(1, 11, 2)) # generates a number from 1,3,5,7,9
| true |
2889b84429d5d2517dafd3fddfc7a50d38b4b397 | thenavdeeprathore/LearnPython3 | /06_2_data_structure_tuple/Tuple_NestedTuple.py | 1,025 | 4.5625 | 5 | """
Nested Tuples:
-------------
Tuple inside another tuple is called nested tuple
Tuple of Tuples:
-------------
import itertools
tuple(itertools.chain(*tupleName))
"""
n = (10, 20, (30, 40))
print(n) # (10, 20, (30, 40))
print(n[0]) # 10
print(n[1]) # 20
print(n[2]) # (30, 40)
print(n[2][0]) # 30
print(n[2][1]) # 40
# Nested Tuple as Matrix:
n = ((10, 20, 30), (40, 50, 60), (70, 80, 90))
print(n) # ((10, 20, 30), (40, 50, 60), (70, 80, 90))
print("Elements by row wise: ")
for row in n:
print(row)
# Elements by row wise:
# (10, 20, 30)
# (40, 50, 60)
# (70, 80, 90)
print("Elements by Matrix style: ")
for row in n:
for col in row:
print(col, end=' ')
print()
# Elements by Matrix style:
# 10 20 30
# 40 50 60
# 70 80 90
# Convert nested tuples into normal tuple:
import itertools
tuple1 = ((1, 2, 3), (4, 5), (6,), (7, 8, 9), (0,))
print(tuple1) # ((1, 2, 3), (4, 5), (6,), (7, 8, 9), (0,))
tuple2 = tuple(itertools.chain(*tuple1))
print(tuple2) # (1, 2, 3, 4, 5, 6, 7, 8, 9, 0)
| false |
05f48e24bde63d2a4642c722bf3fa1732e5a6dea | thenavdeeprathore/LearnPython3 | /01_language_fundamentals/13_Collections.py | 1,738 | 4.3125 | 4 | # Collections
"""
# A group of objects represented as a single entity is called Collections:
list
tuple
set
frozenset
dictionary
range
bytes
bytearray
"""
# list
"""
1) []
2) Heterogeneous objects are allowed {different data types}
3) Order is preserved
4) Duplicates are allowed
5) Indexing and Slicing
6) Growable in nature
7) Mutable --> can change
"""
# tuple
"""
()
Exactly same as list except tuple is Immutable.
Read only version of list is Tuple
"""
# set
"""
{}
Mutable -- can change
List vs Set:
-------------
1) In set, Duplicates are not allowed
2) In set, Order is not preserved
"""
# frozenset
"""
1) It is exactly same as set except that it is immutable.
2) Hence we cannot use add or remove functions.
tuple vs frozenset:
-------------------
1) In frozenset, order is not preserved
2) In frozenset, duplicates are not allowed
3) In frozenset, indexing and slicing are not allowed
"""
# dict
"""
If we want to represent a group of values as key-value pairs then we should go for dict data type.
Eg: d = {101:'tom',102:'jerry',103:'john'}
Duplicate keys are not allowed but values can be duplicated.
If we are trying to insert an entry with duplicate key then old value will be replaced with new value
Note: Dict is Mutable
List vs Dict:
-------------
1) In Dict, Order is not preserved
2) In Dict, indexing and slicing are not allowed
"""
# range
"""
range Data Type represents a sequence of numbers.
The elements present in range Data type are not modifiable. i.e range Data type is
immutable.
"""
r = range(10)
print(r) # range(0, 10)
print(type(r)) # <class 'range'>
for i in r:
print(i)
# 0 to 9
# Mutable vs Immutable
"""
bytearray
list
set
dict
These are the only mutable data types
""" | true |
b5465b1ca335a9e3298077f92f3c838f4a895861 | thenavdeeprathore/LearnPython3 | /01_language_fundamentals/12_ImmutabilityVsMutability.py | 1,573 | 4.3125 | 4 | # All fundamental data types are Immutable {Can't change}
# Mutable -- Changeable
# Immutable -- Non changeable
"""
Fundamental Data Types vs Immutability:
--------------------------------------
=> All Fundamental Data types are immutable. i.e once we creates an object, we cannot
perform any changes in that object. If we are trying to change then with those changes
a new object will be created. This non-changeable behaviour is called immutability.
=> In Python if a new object is required, then PVM won’t create object immediately. First
it will check is any object available with the required content or not. If available then
existing object will be reused. If it is not available then only a new object will be
created. The advantage of this approach is memory utilization and performance will be
improved.
=> But the problem in this approach is, several references pointing to the same object, by
using one reference if we are allowed to change the content in the existing object then
the remaining references will be effected. To prevent this immutability concept is
required. According to this once creates an object we are not allowed to change
content. If we are trying to change with those changes a new object will be created
"""
a = 10
b = 10
print(a is b) # True
print(id(a)) # 1626208320
print(id(b)) # 1626208320
# Mutable -- List
l1 = [10, 20, 30]
l2 = l1
print(id(l1)) # 29947336
print(id(l2)) # 29947336
l1[0] = 100
print(l1) # [100, 20, 30]
print(l2) # [100, 20, 30]
l2[1] = 200
print(l1) # [100, 200, 30]
print(l2) # [100, 200, 30]
| true |
d0aa0e9130f2053a58b52759329dd389e8471117 | thenavdeeprathore/LearnPython3 | /Programs/String_Programs/String_SortFirstAlphabets.py | 532 | 4.125 | 4 | # Program to sort characters of the string, first alphabet symbols followed by digits
s = 'B4A1D3'
print(s) # B4A1D3
# first digits then alphabets
sort_string = sorted(s)
print(sort_string) # ['1', '3', '4', 'A', 'B', 'D']
# first alphabets then digits
alphabets = []
digits = []
for ch in s:
if ch.isalpha():
alphabets.append(ch)
else:
digits.append(ch)
print(alphabets) # ['B', 'A', 'D']
print(digits) # ['4', '1', '3']
output = ''.join(sorted(alphabets) + sorted(digits))
print(output) # ABD134
| true |
c3d4b8552262b50f63595502edd8b5b345c28cc9 | thenavdeeprathore/LearnPython3 | /03_input_output/Print.py | 2,544 | 4.8125 | 5 | """
Output Statements:
------------------
We can use print() function to display output.
=> print() without any argument
Just it prints new line character
Note:
=> If both arguments are String type then + operator acts as concatenation operator.
=> If one argument is string type and second is any other type like int then we will get Error.
=> If both arguments are number type then + operator acts as arithmetic addition operator.
"""
# case 1: Just it prints new line character
print()
# case 2:
print("Hello World")
# We can use escape characters also
print("Hello \n World")
print("Hello\tWorld")
# We can use repetition operator (*) in the string
print(10 * "Hello")
print("Hello" * 10)
# We can use + operator also
print("Hello" + "World")
# case 3:
print("Hello" + "World") # HelloWorld
print("Hello", "World") # Hello World
# case 4:
a, b, c = 10, 20, 30
print("the values are: ", a, b, c) # The Values are : 10 20 30
# NOTE: By default output values are separated by space.
# If we want we can specify separator by using "sep" attribute
a, b, c = 10, 20, 30
print(a, b, c) # 10 20 30
print(a, b, c, sep='') # 102030
print(a, b, c, sep=' ') # 10 20 30
print(a, b, c, sep=',') # 10,20,30
print(a, b, c, sep=':') # 10:20:30
# case 5: print() with end attribute
# Note: The default value for end attribute is \n, which is nothing but new line character.
print("hello")
print("good")
print("morning")
# If we want output in the same line with space
print("hello", end=' ')
print("good", end=' ')
print("morning")
# hello good morning
# case 6: print(object) statement
l = [10, 20, 30, 40]
t = (10, 20, 30, 40)
print(l)
print(t)
# case 7: print (formatted string)
'''
1) %i int
2) %d int
3) %f float
4) %s String type
Syntax: print("formatted string" %(variable list))
'''
a = 10
b = 20
c = 30
print("a value is %i" % a)
print("b value is %d and c value is %d" % (b, c))
# case 8: Different ways to print statements in Python3
eid = int(input("Enter your id: "))
ename = input("Enter your name: ")
esal = float(input("Enter your salary: "))
print(eid)
print(ename)
print(esal)
print(eid, ename, esal)
print("Employee ID: ", eid)
print("Employee Name: ", ename)
print('Employee Salary: ', esal)
print(f"Employee ID: {eid}")
print(f"Employee Name: {ename}")
print(f"Employee Salary: {esal}")
print("Emp id={} Emp name={} Emp sal={}".format(eid, ename, esal))
print("Emp id={0} Emp name={1} Emp sal={2}".format(eid, ename, esal))
print("EmpID=%d EmpName=%s EmpSal=%g" % (eid, ename, esal))
| true |
d51bd73810a7d324b68ae7abe569e922ffdcbff5 | thenavdeeprathore/LearnPython3 | /08_modules/01_WriteAndUseModule.py | 1,212 | 4.28125 | 4 | # Module
"""
A group of functions, variables and classes saved to a file, is known as module.
Every Python file (.py) acts as a module.
"""
# Imagine this a file named as -- mymath.py
x = 100
def add(a, b):
print("The Sum:", a + b)
def product(a, b):
print("The Product:", a * b)
class A:
pass
"""
mymath.py module contains one variable and 2 functions.
If we want to use members of module in our program then we should import that
module.
import modulename
We can access members by using module name.
modulename.variable
modulename.function()
"""
# Imagine this is a test file named as -- test.py
import mymath
print(mymath.x) # 100
mymath.add(10, 20) # The Sum: 30
mymath.product(10, 20) # The Product: 200
"""
Module Advantages:
------------------
Code re-usability --> write once use many times
Code readability --> length of the code will be reduced
Maintainability --> Make changes only in one file
"""
# Note 1:
# Whenever we are using a module in our program, for that module compiled file (.pyc)
# will be generated and stored in the folder (__pycache__) permanently.
# 100 test files can use the same one compiled file (mymth.pyc) from the folder (__pycache__)
| true |
3ac430c45f5322985d92c691f5f4871a23ef01e9 | thenavdeeprathore/LearnPython3 | /01_language_fundamentals/11_TypeCasting.py | 1,902 | 4.71875 | 5 | """
Type Casting:
------------
We can convert one type value to another type. This conversion is called Typecasting or Type coersion.
The following are various inbuilt functions for type casting.
1) int()
2) float()
3) complex()
4) bool()
5) str()
"""
# int()
"""
Note:
1) We can convert from any type to int except complex type.
2) If we want to convert str type to int type, compulsory str should contain only integral
value and should be specified in base-10.
"""
print(int(12.456)) # 12
# print(int(10+20j)) # TypeError: can't convert complex to int
print(int("10") + 10) # 20
# print(int("hello")) # ValueError: invalid literal for int() with base 10: 'hello'
# print(int("10.5")) # ValueError: invalid literal for int() with base 10: '10.5'
print(int(True)) # 1
print(int(False)) # 0
# float()
"""
We can use float() function to convert other type values to float type.
Note:
1) We can convert any type value to float type except complex type.
2) Whenever we are trying to convert str type to float type compulsory str should be
either integral or floating point literal and should be specified only in base-10.
"""
print(float(10)) # 10.0
print(float(10.5)) # 10.5
# print(float(10+20j)) # TypeError: can't convert complex to float
print(float("10")) # 10.0
print(float("10.20")) # 10.2
print(float(True)) # 1.0
print(float(False)) # 0.0
# bool()
"""
We can use this function to convert other type values to bool type.
"""
print(bool(0)) # False
print(bool(1)) # True
print(bool(10)) # True
print(bool(10.5)) # True
print(bool(0.008)) # False
print(bool(0.0)) # False
print(bool(True)) # True
print(bool(False)) # False
print(bool(-0.0123)) # True
print(bool(0+0j)) # False
print(bool(1+0j)) # True
print(bool("")) # False
print(bool()) # False
print(bool("yes")) # True
print(bool("no")) # True
print(bool('True')) # True
print(bool('False')) # True
| true |
fe38c6a18e7aea77158a5294b22fa47135b5d0a6 | thenavdeeprathore/LearnPython3 | /01_language_fundamentals/06_BaseConversion.py | 623 | 4.53125 | 5 | """
Base Conversions:
Python provide the following in-built functions for base conversions
bin()
oct()
hex()
1) bin():
---------
We can use bin() to convert from any base to binary
2) oct():
---------
We can use oct() to convert from any base to octal
3) hex():
---------
We can use hex() to convert from any base to hexa decimal
"""
# Decimal to Binary
print(bin(15)) # 0b1111
# Octal to Binary
print(bin(0o11)) # 0b1001
# Hexadecimal to Binary
print(bin(0x10)) # 0b10000
# Decimal to Octal
print(oct(10)) # 0o12
# Binary to Octal
print(oct(0B1111)) # 0o17
# Hexadecimal to Octal
print(oct(0X123)) # 0o443
| false |
2d7a464189ea811357d40b0595a7824f6e09a118 | thenavdeeprathore/LearnPython3 | /08_modules/07_ModuleReloading.py | 1,250 | 4.125 | 4 | # Reloading a Module:
# By default module will be loaded only once even though we are importing multiple times
"""
module1.py:
print("This is from module1")
test.py
import module1
import module1
import module1
import module1
print("This is test module")
Output
This is from module1
This is test module
"""
# In the above program test module will be loaded only once even though we are importing
# multiple times.
# The problem in this approach is after loading a module if it is updated outside then
# updated version of module1 is not available to our program.
# We can solve this problem by reloading module explicitly based on our requirement
# We can reload by using reload() function of imp module.
# import imp
# imp.reload(module1)
"""
test.py:
import module1
import module1
from imp import reload
reload(module1)
reload(module1)
reload(module1)
print("This is test module")
In the above program module1 will be loaded 4 times in that 1 time by default and 3 times
explicitly. In this case output is
This is from module1
This is from module1
This is from module1
This is from module1
This is test module
The main advantage of explicit module reloading is we can ensure that updated version is
always available to our program.
"""
| true |
1cc06ade628de9159369cd737cad38a4922981fd | thenavdeeprathore/LearnPython3 | /01_language_fundamentals/05_DataTypes_Int.py | 1,675 | 4.71875 | 5 | # int:
"""
int Data Type:
We can use int data type to represent whole numbers (integral values)
Eg: a = 10
type(a) #int
Note:
- In Python2 we have long data type to represent very large integral values.
- But in Python3 there is no long type explicitly and we can represent long values also by
using int type only.
We can represent int values in the following ways:
1) Decimal form
2) Binary form
3) Octal form
4) Hexa decimal form
"""
a = 10 # decimal
b = 0b10 # binary
c = 0o10 # octal
d = 0X10 # hexadecimal
print(a)
print(b)
print(c)
print(d)
"""
I) Decimal Form (Base-10):
- It is the default number system in Python
- The allowed digits are: 0 to 9
- Eg: a =10
"""
d = 10
print("Decimal: ", d)
"""
II) Binary Form (Base-2):
- The allowed digits are : 0 & 1
- Literal value should be prefixed with 0b or 0B
- Eg: a = 0B1111
a = 0B111
a = 0b111
"""
b = 0B1111
print("Binary: ", b)
b = 0b111
print("Binary: ", b)
"""
III) Octal Form (Base-8):
- The allowed digits are : 0 to 7
- Literal value should be prefixed with 0o or 0O.
- Eg: a = 0o123
a = 0o786
"""
o = 0o123
print("Octal: ", o)
o = 0O111
print("Octal: ", o)
"""
IV) Hexa Decimal Form (Base-16):
- The allowed digits are: 0 to 9, a-f (both lower and upper cases are allowed)
- Literal value should be prefixed with 0x or 0X
- Eg: a = 0XFACE
a = 0XBeef
a = 0XBeer
"""
h = 0xBeef
print("Hexadecimal: ", h)
h = 0X10
print("Hexadecimal: ", h)
# Note: Being a programmer we can specify literal values in decimal, binary, octal and hexa
# decimal forms. But PVM will always provide values only in decimal form.
a = 10
b = 0o10
c = 0X10
d = 0B10
print(a) # 10
print(b) # 8
print(c) # 16
print(d) # 2
| true |
4d9eb6d34244fba4010485c2803577e7b4ff3194 | thenavdeeprathore/LearnPython3 | /02_operators/05_LogicalOperators.py | 1,195 | 4.28125 | 4 | """
4) Logical Operators: and, or, not
----------------------------------
We can apply for all types.
For boolean Types Behaviour:
and If both arguments are True then only result is True
or If at-least one argument is True then result is True
not Complement
True and False False
True or False True
not False True
For non-boolean Types Behaviour:
0 means False
non-zero means True
empty string is always treated as False
"""
# and
print(True and True) # True
print(True and False) # False
print(False and True) # False
print(False and False) # False
# If first argument is zero then result is zero otherwise result is y
print(10 and 20) # 20
print(0 and 20) # 0
# or
print(True or True) # True
print(True or False) # True
print(False or True) # True
print(False or False) # False
# If x evaluates to True then result is x otherwise result is y
print(10 or 20) # 10
print(0 or 20) # 20
# not
print(not True) # False
print(not False) # True
# If x is evaluates to False then result is True otherwise False
print(not 10) # False
print(not 0) # True
print(not "") # True
| true |
e128d4ac294c9877b6b1055f1b777e9cf1cab3fe | thenavdeeprathore/LearnPython3 | /06_1_data_structure_list/List_Comprehension.py | 2,462 | 4.46875 | 4 | """
List Comprehensions:
-------------------
It is very easy and compact way of creating list objects from any iterable objects
(Like List, Tuple, Dictionary, Range etc) based on some condition.
Syntax: list = [expression for item in list if condition]
"""
# Way 1:
list_of_numbers = [i for i in range(0, 10)]
print(list_of_numbers) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Way 2: Much easier
list_of_range = list(range(10))
print(list_of_range) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Even numbers less than 10
list_of_even = [i for i in range(0, 10, 2)]
print(list_of_even) # [0, 2, 4, 6, 8]
list_of_even_range = list(range(0, 10, 2))
print(list_of_even_range) # [0, 2, 4, 6, 8]
# program 1: square number list
list_square = [x * x for x in range(1, 11)]
print(list_square) # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# program 2: 2 power list
list_power = [2 ** x for x in range(1, 11)]
print(list_power) # [2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]
# program 3: divisible by ten
list_10_divisible = [x for x in range(1, 101) if x % 10 == 0]
print(list_10_divisible) # [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
# program 4: list1 doesn't contain list2 items
num1 = [10, 20, 30, 40]
num2 = [30, 40, 50, 60]
num3 = [x for x in num1 if x not in num2]
print(num3) # [10, 20]
# program 5: fetch only first word from each list items
city = ['Mumbai', 'Pune', 'Tokyo', 'London']
first_word = [x[0] for x in city]
print(first_word) # ['M', 'P', 'T', 'L']
# program 6: split string into list
words = "the quick brown fox jumps over the lazy dog".split()
print(words) # ['the', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
list_count = [[x.upper(), len(x)] for x in words]
print(list_count)
# [['THE', 3], ['QUICK', 5], ['BROWN', 5], ['FOX', 3], ['JUMPS', 5], ['OVER', 4], ['THE', 3], ['LAZY', 4], ['DOG', 3]]
# Q) Write a Program to display unique vowels {a, e, i, o, u} present in the given Word?
# without list comprehension
vowels = ['a', 'e', 'i', 'o', 'u']
s = input("Enter a string value: ")
result = []
for letter in s:
if letter in vowels:
if letter not in result:
result.append(letter)
print(result)
print(f"The number of unique vowels present in {s} is {len(result)}")
# with list comprehension
vowels = ['a', 'e', 'i', 'o', 'u']
s = input("Enter a string value: ")
result = [letter for letter in vowels if letter in s]
print(result)
print(f"The number of unique vowels present in {s} is {len(result)}")
| true |
c593c7b797175c314a29e87be8d65ae62f7f8ff3 | thenavdeeprathore/LearnPython3 | /10_oops/14_NestedMethods.py | 475 | 4.25 | 4 | """
Nested methods:
-----------------
- We can declare a method inside another method, such types of methods are called Nested methods
Advantage:
---------
- Code re-usability
"""
class Test:
def m1(self):
def calc(a, b):
print("Sum: ", a + b)
print("Mul: ", a * b)
calc(10, 20)
calc(100, 200)
calc(1000, 2000)
t = Test()
t.m1()
# Sum: 30
# Mul: 200
# Sum: 300
# Mul: 20000
# Sum: 3000
# Mul: 2000000
| true |
2753d16b602c4959fe63c41bb62c48b16b604b08 | Hephzibah56/PythonWork | /practiceProblem9.py | 838 | 4.21875 | 4 | """
Pretend that you have just opened a new savings account that earns 4 percent interest
per year. The interest that you earn is paid at the end of the year, and is added
to the balance of the savings account. Write a program that begins by reading the
amount of money deposited into the account from the user. Then your program should
compute and display the amount in the savings account after 1, 2, and 3 years. Display
each amount so that it is rounded to 2 decimal places
"""
x= float(input("Enter the current amount of money you have in your account: "))
# amount in the first year
y = float((x*0.04) + x)
# amount in the second year
z = float((y*0.04) + y)
# amount in the third year
m =float((z*0.04) + z)
print("%.2f"% (y + z + m) + " is the total money you have in your bank account")
#print("%.2f happy birthday "%345.45678)
| true |
6749a1c603e9c73041ed3b9f511899d53eae6ede | Hephzibah56/PythonWork | /Python project.py | 749 | 4.25 | 4 |
import random
#pick a random number
print("to exit enter -1")
unknown_number = random.randint(1,150)
guess= int(input("input number between 0 and 150 "))
if guess >= 150:
print("your number should not exceed 150")
while unknown_number!=guess and guess!=-1:
if guess>unknown_number:
guess=int(input("choose a lesser number: "))
if guess >= 150:
print("your number should not exceed 150")
break
elif guess< unknown_number:
guess=int(input("choose a larger number: "))
if guess >= 150:
print("your number should not exceed 150")
break
if guess==unknown_number :
print(" CONGRATS! You got it")
| true |
f3bd9eb4d72270e0f865a9a7eab9dfcaf1c9ac13 | rob-blackbourn/scratch-python | /blog-graphql-server/jetblack/blog/utils/linq.py | 1,193 | 4.1875 | 4 | def group_by(iterable, key_selector, projection=None):
"""
Returns an iterator which groups the iterable with a key provided by the
supplied function. The source iterable does not need to be sorted.
:param iterable: The items over which to iterate.
:param key_selector: A function which selects the key to group on.
:return: A tuple of the key and the list of items matching the key.
"""
groups = {}
for item in iterable:
key = key_selector(item)
value = projection(item) if projection else item
if key in groups:
groups[key].append(value)
else:
groups[key] = [value]
return groups
def first_or_default(iterable, predicate=None, default=None):
"""First the first value matching a perdicate otherwise a default value.
:param iterable: The items over which to iterate.
:param predicate: A predicate to apply to each item.
:param default: The value to return if no item matches.
:return: The first value matching a predicate otherwise the default value.
"""
for item in iterable:
if not predicate or predicate(item):
return item
return default
| true |
dbc7065335d48d147ebe5998d6ef2655188d5958 | Camicb/python-for-everybody | /c3tarea2.py | 916 | 4.25 | 4 | #Each student will have a distinct data file for the assignment - so only use
#your own data file for analysis. The file contains much of the text from the
#introduction of the textbook except that random numbers are inserted
#throughout the text. The basic outline of this problem is to read the file,
#look for integers using the re.findall(), looking for a regular expression
#of '[0-9]+' and then converting the extracted strings to integers and summing
#up the integers. Enter the sum from the actual data and your Python code below:
#Sum: (ends with 295)
import re
fh=open('actualdata.txt')
lista=list()
for line in fh:
line=line.rstrip()
buscar=re.findall('([0-9]+)',line) #() alrededor de [0-9]+ reemplaza re.search
for num in buscar:
if len(buscar) > 0: #queda xq hay muchos vacios
num=int(num)
lista.append(num)
print(sum(lista))
| true |
a4e089243025c056ebf8f5f3fa23d203352732c9 | Camicb/python-for-everybody | /c2tarea5.py | 828 | 4.5 | 4 | #8.4 Open the file romeo.txt and read it line by line. For each line, split
#the line into a list of words using the split() method. The program should
#build a list of words. For each word on each line check to see if the word is
#already in the list and if not append it to the list. When the program
#completes, sort and print the resulting words in alphabetical order.
#You can download the sample data at http://www.py4e.com/code3/romeo.txt
fname = input("Enter file name: ")
if len(fname) < 1 : fname = "mbox-short.txt"
fh = open(fname)
count = 0
for line in fh:
#line=line.rstrip
if not line.startswith("From: "):
continue
count=count+1
words=line.split()
print(words[1])
print("There were", count, "lines in the file with From as the first word")
| true |
b4f592b9f070fb892891248783f39369aa01ea93 | zyhsna/Leetcode_practice | /problems/subtract-the-product-and-sum-of-digits-of-an-integer.py | 433 | 4.125 | 4 | # _*_ coding:UTF-8 _*_
# 开发人员:zyh
# 开发时间:2020/7/28 17:21
# 文件名:subtract-the-product-and-sum-of-digits-of-an-integer.py
# 开发工具:PyCharm
def subtractProductAndSum(self, n):
"""
:type n: int
:rtype: int
"""
sum = 0
multi = 1
while n > 0:
temp = n%10
sum += temp
multi *= temp
n //= 10
print(multi - sum)
subtractProductAndSum(1, 4421) | false |
244ccbfa9bffc12487785d71ae4b20442184d8df | ThomasDegallaix/CS101 | /sort/quick_sort.py | 1,536 | 4.15625 | 4 | import os
"""
Explanation from GeekForGeeks :
QuickSort is a Divide and Conquer algorithm. It picks an element as pivot and partitions the given array around the picked pivot.
There are many different versions of quickSort that pick pivot in different ways.
Always pick first element as pivot.
Always pick last element as pivot (implemented below)
Pick a random element as pivot.
Pick median as pivot.
The key process in quickSort is partition().
Target of partitions is, given an array and an element x of array as pivot,
put x at its correct position in sorted array and put all smaller elements (smaller than x) before x,
and put all greater elements (greater than x) after x. All this should be done in linear time.
Average-performance: O(n log n)
Worst-case performance: O(n^2)
"""
#We take the last element as pivot
def partition(array, low, high):
i = (low - 1) #index of smaller element
pivot = array[high]
for j in range(low, high):
if array[j] <= pivot :
i = i + 1
array[i], array[j] = array[j], array[i]
array[i+1], array[high] = array[high], array[i+1]
return (i+1)
def quickSort(array, low, high):
if low < high :
p = partition(array, low, high)
quickSort(array, low, p-1)
quickSort(array, p+1, high)
return array
if __name__ == '__main__':
array = [4, 2, 17, 8, 1, 5, 7, 12, 21, 18]
sorted_array = quickSort(array, 0, len(array)-1 )
#print(sorted_array)
print(sorted_array) | true |
a41d6b66fc41d5fbefde05a50f0f82f83c0e74b0 | xusun-CMU/hello-python | /basics/string_formatting.py | 885 | 4.5 | 4 | #Python uses C-style string formatting to create new, formatted strings.
#The "%" operator is used to format a set of variables enclosed in a "tuple"
#(a fixed size list), together with a format string,
#which contains normal text together with "argument specifiers",
#special symbols like "%s" and "%d".
def string_formatter_101():
#String use %s
#integers use %d
name = "John"
age = 23
print "%s is %d years old." % (name, age) #(name, age) is the tuple
#lists use %s as well
mylist = [1,2,3]
print "A list: %s" % mylist
# %s - String (or any object with a string representation, like numbers, lists)
# %d - Integers
# %f - Floating point numbers
# %.<number of digits>f - Floating point numbers with a fixed amount of digits to the right of the dot.
# %x/%X - Integers in hex representation (lowercase/uppercase)
if __name__ == '__main__':
string_formatter_101() | true |
97b6cfe64bb8292fb90501b872e8e400314880ab | med-cab1/CSPT15_BST_GP | /Binary_Search_Trees/05_minimumDepthBinaryTree.py | 906 | 4.28125 | 4 | """
You are given a binary tree and you are asked to write a function that finds its minimum depth. The minimum depth can be defined as the number of nodes along the shortest path from the root down to the nearest leaf node. As a reminder, a leaf node is a node with no children.
Example:
Given the binary tree [5,7,22,None,None,17,9],
5
/ \
7 22
/ \
17 9
your function should return its minimum depth = 2.
[execution time limit] 4 seconds (py3)
[input] tree.integer root
[output] integer
"""
#
# Binary trees are already defined with this interface:
# class Tree(object):
# def __init__(self, x):
# self.value = x
# self.left = None
# self.right = None
def minimumDepthBinaryTree(root):
if root is None:
return 0
else:
return 1 + min(
minimumDepthBinaryTree(root.left),
minimumDepthBinaryTree(root.right)
)
| true |
4e7895bebc769c612264f1ac1e83d70f6bb1efe6 | libaoshen/python_study | /com/libaoshen/python/cookbook/ch4/Iteration.py | 625 | 4.25 | 4 | # coding:utf-8
"""
迭代器
"""
# 1.遍历可迭代对象
a = [1, 2, 3, 4, 5]
b = iter(a)
print(next(b))
# 2.生成器
def generatrNum(start, end, incresement):
a = start
while a < end:
yield a
a += incresement
a = generatrNum(1, 10, 2)
print(next(a))
print(next(a))
print(next(a))
# 3.奇数数列生成器
def oddGenerator(n):
a = 1
count = 1
while count <= n:
yield a
a += 2
count+=1
b = oddGenerator(10)
print(next(b))
print(next(b))
print(next(b))
print(next(b))
print(next(b))
print(next(b))
# 循环使用
for n in oddGenerator(10):
print(n) | false |
623569ec9a942b798b5047ecc80c7cefa53fe6d1 | dlsnoopy95052/test1 | /test73.py | 378 | 4.15625 | 4 | cube = lambda x: x ** 3# complete the lambda function
def fibonacci(n):
# return a list of fibonacci numbers
f = []
k = [0,1]
for i in range(n):
if i >= 2:
f.append((f[i-1]+f[i-2]))
else:
f.append(k[i])
return f
if __name__ == '__main__':
n = int(input())
print(list(map(cube, fibonacci(n)))) | false |
f134cf659e2b0ba1ae512662ef9bb33ef3b76e6b | NicholasColonna6/Flask-BlogAPI | /hash_table.py | 2,269 | 4.21875 | 4 | # Basic Implementation of the Hash Table data structure
# class to represent linked lists at each index of the hash table
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
# class to represent key/value pairs as the data within our node/linked-list
class Data:
def __init__(self, key, value):
self.key = key
self.value = value
# class to represent the hash table
class HashTable:
def __init__(self, table_size):
self.table_size = table_size
self.hash_table = [None] * table_size
# converts a key into a hash value
def custom_hash(self, key):
hash_value = 0
for i in key:
hash_value += ord(i)
hash_value = (hash_value * ord(i)) % self.table_size
return hash_value
# adds key/value pair to the hash table
def add_key_value(self, key, value):
hashed_key = self.custom_hash(key)
if self.hash_table[hashed_key] is None:
self.hash_table[hashed_key] = Node(Data(key, value), None)
else:
node = self.hash_table[hashed_key]
while node.next is not None:
node = node.next
node.next = Node(Data(key, value), None)
# retrieves value from hash table given a key, returns None if not there
def get_value(self, key):
hashed_key = self.custom_hash(key)
if self.hash_table[hashed_key] is not None:
node = self.hash_table[hashed_key]
if node.next is None:
return node.data.value
while node is not None:
if key == node.data.key:
return node.data.value
node = node.next
return None
# prints the hash table
def print_table(self):
print("{")
for i, val in enumerate(self.hash_table):
if val is not None:
llist_string = ""
node = val
if node.next is not None:
while node is not None:
llist_string += (str(node.data.key) + " : " + str(node.data.value) + " --> ")
node = node.next
llist_string += "None"
print(f" [{i}] {llist_string}")
else:
print(f" [{i}] {val.data.key} : {val.data.value}")
else:
print(f" [{i}] {val}")
print("}")
"""
ht = HashTable(4)
ht.add_key_value("test", "one")
ht.add_key_value("testing", "two")
ht.add_key_value("test", "three")
ht.add_key_value("key", "value")
ht.print_table()
""" | true |
fe168a709afbb27226458099b579d868d575b17b | KevinXuxuxu/intro_to_algo | /chapter2/merge_sort.py | 1,139 | 4.40625 | 4 | # 2.3.1
from typing import List
from utils.sort_utils import get_compare
def merge_sort(nums: List[int], reverse: bool = False) -> List[int]:
'''
Implementation of merge sort on integer list
Will sort input list in ascending order by default
:param nums: list of integers to be sorted
:param reverse: will sort in descending order if True
'''
compare = get_compare(reverse)
if len(nums) <= 1:
return nums
if len(nums) == 2:
if compare(nums[0], nums[1]):
# swap the 2 elements
return [nums[1], nums[0]]
else:
return nums
mid = len(nums) // 2
left = merge_sort(nums[:mid], reverse)
right = merge_sort(nums[mid:], reverse)
i, j = 0, 0
result = []
while i < len(left) or j < len(right):
# pick right[j]
if i == len(left) or (j < len(right) and compare(left[i], right[j])):
result.append(right[j])
j += 1
# pick left[i]
elif j == len(right) or (i < len(left) and compare(right[j], left[i])):
result.append(left[i])
i += 1
return result
| true |
af45ddf2dd9fd42f5b3b667df6f7cb5ecdd3d30c | KevinXuxuxu/intro_to_algo | /chapter9/quick_select.py | 701 | 4.15625 | 4 | # 9.2
from typing import List
from chapter7.quick_sort import partition
def quick_select(nums: List[int], i: int, reverse: bool = False) -> int:
'''
Implementation of quick select to select ith smallest number from a list
:param nums: list of integers to select from
:param i: ith smallest number (0-indexed)
:param reverse: will select ith largest number if True
'''
l, r = 0, len(nums) - 1
while l < r:
j = partition(nums, l, r, reverse)
if j == i:
return nums[j]
if j > i:
if r == j:
j -= 1
r = j
elif j < i:
l = j
return nums[l] # probably will never hit here
| true |
ccc6137770c7498cb6a32cae704e778798e265ce | YaroslavaMykhailenko/homework_forigortereshchenko | /Lab2/Lab2(task1).py | 1,316 | 4.15625 | 4 | '''
Скласти програму виведення всіх натуральних чисел, менших n, квадрат суми цифр яких дорівнює заданому числу m.
'''
print("Михайленко Ярослава Євгенівна \nЛабораторна робота №2 \nВаріант 10 \nВиведення чисел \n")
import re
def func():
upper_border =input("Введіть значення верхньої межі n(≥1):")
result_upper =int((re.search(r'\d', upper_border)).group())
if result_upper<1:
print("n має бути ≥ 1")
func()
argument =input("Введіть значення аргумента функції:")
result_argument =int((re.search(r'\d', argument)).group())
if result_argument == 0:
print("Введіть ненулевий аргумент функції!")
argument =input("Введіть значення аргумента функції:")
multiplication = 1
for down_border in range(result_upper):
down_border = down_border + 1
multiplication = multiplication * (result_argument+down_border)/(down_border ** 2)
print(multiplication)
c = input("Продовжити тестування програми? +/-")
if c == "+":
func()
else:
return()
func()
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.