blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
989d8d4ad415764c97332ce8008f1946c5a90d24 | thuaung23/rock-paper-scissors | /main.py | 2,083 | 4.28125 | 4 | # This is a simple game of Rock, Paper, Scissor
# Written by: Thu Aung
# Written on: Sept 10,2020
print('Welcome to the game of Rock, Paper and Scissor!!!')
import random
rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
__________)
(____)
---.__(___)
'''
print("Welcome to the game of Rock, Paper, Scissor.")
user_choice = input("Choose 0 for Rock, 1 for Paper or 2 for Scissor.\n")
comp_choice = random.randint(0,2)
if user_choice == '0' and comp_choice == 0:
print("Your choice: Rock\n", rock)
print("Computer choice: Rock\n", rock)
print("This round is a draw.")
elif user_choice == '0' and comp_choice == 1:
print("Your choice: Rock\n", rock)
print("Computer choice: Paper\n", paper)
print("You lose.")
elif user_choice == '0' and comp_choice == 2:
print("Your choice: Rock\n", rock)
print("Computer choice: Scissors\n", scissors)
print("You win.")
elif user_choice == '1' and comp_choice == 0:
print("Your choice: Paper\n", paper)
print("Computer choice: Rock\n", rock)
print("You win.")
elif user_choice == '1' and comp_choice == 1:
print("Your choice: Paper\n", paper)
print("Computer choice: Paper\n", paper)
print("This round is a draw.")
elif user_choice == '1' and comp_choice == 2:
print("Your choice: Paper\n", paper)
print("Computer choice: Scissors\n", scissors)
print("You lose.")
elif user_choice == '2' and comp_choice == 0:
print("Your choice: Scissors\n", scissors)
print("Computer choice: Rock\n", rock)
print("You lose.")
elif user_choice == '2' and comp_choice == 1:
print("Your choice: Scissors\n", scissors)
print("Computer choice: Paper\n", paper)
print("You win.")
elif user_choice == '2' and comp_choice == 2:
print("Your choice: Scissors\n", scissors)
print("Computer choice: Scissors\n", scissors)
print("This round is a draw.")
else:
print("Invalid entry.")
| false |
ef219d587fb46ba7dd01c69f55e05aca2b0de6f1 | sn1p3r46/pyspacexy | /psyspacexy/point.py | 1,610 | 4.4375 | 4 | #!/usr/bin/python3
from numbers import Number
class Point:
"""
This class is meant to describe and represent points in a 2D plane,it also
implements some basic operations.
"""
def __init__(self,x,y):
if not isinstance(x,Number) or not isinstance(y,Number):
TypeError("Coordinates x and y must be numbers")
self.x = x
self.y = y
def __str__(self):
return "Point(x:{} y:{})".format(self.x,self.y)
def __repr__(self):
return self.__str__()
def __add__(self,other):
if isinstance(other,Point):
return Point(self.x + other.x, self.y + other.y)
else:
return Point(self.x + other, self.y + other)
def __eq__(self,other):
if self is None or other is None:
return False
return self.x == other.x and self.y == other.y
def __mul__(self,val):
return Point(self.x*val,self.y*val)
def distancePoint(self,other):
"""Computers the distance with the Point provided as input"""
return self.distance(other.x,other.y)
def distance(self,x,y):
"""Computers the distance with the coordinates provided as input"""
return ((self.x - x)**2+(self.y - y)**2)**0.5
def half(self):
"""Multiplies both coordinates (x and y) by 0.5"""
return self*(0.5)
def quarter(self):
"""Multiplies both coordinates (x and y) by 0.25"""
return self*(0.25)
def scale(self,factor):
"""Multiplies both coordinates (x and y) by factor"""
return self*factor
| true |
3a934cf92f631e657b1191106a0db02e70f707da | JAYASANKARG/cracking_the_coding_interview_solution | /is_unique.py | 892 | 4.21875 | 4 | """Is Unique: Implement an algorithm to determine if a string has all unique characters. What if you
cannot use additional data structures clear
"""
"""s=input("Enter the string : ")
before_set=len(s)
s=set(s)
after_Set=len(s)
if(before_set==after_Set):
print("all is unique")
else:
print("Not unique")
o(1)
result=True
s=input("Enter the string : ")
for i in range(0,len(s)):
for j in range(i+1,len(s)):
if(s[i]==s[j]):
result=False
break
if(result):
print("unqiue")
else:
print("Not unique")
o(n2)->n*n
"""
"""Bitwise operator
a=0,b=1,c=2
a=97
b=98
"""
def unique(s):
flag=0
for i in range(len(s)):
temp=ord(s[i])-ord('a')
if(flag & (1<<temp)>0):
return False
flag |=1<<temp
return True
s=input("enter the string : ")
if(unique(s)):
print("unique")
else:
print("not unique") | true |
e90427b98d48bc2feab9fdc1d3091a538f99cbaf | willtseng12/dsp | /python/q8_parsing.py | 2,105 | 4.59375 | 5 | # The football.csv file contains the results from the English Premier League.
# The columns labeled ‘Goals’ and ‘Goals Allowed’ contain the total number of
# goals scored for and against each team in that season (so Arsenal scored 79 goals
# against opponents, and had 36 goals scored against them). Write a program to read the file,
# then print the name of the team with the smallest difference in ‘for’ and ‘against’ goals.
# Don't use pandas.
# Following functions will be called like this:
# footballTable = read_data('football.csv')
# minRow = get_index_with_min_abs_score_difference(footballTable)
# print str(get_team(minRow, footballTable))
import csv
def read_data(filename):
"""Returns a list of lists representing the rows of the csv file data.
Arguments: filename is the name of a csv file (as a string)
Returns: list of lists of strings, where every line is split into a list of values.
ex: ['Arsenal', 38, 26, 9, 3, 79, 36, 87]
"""
lol = []
with open(filename, 'r') as csvFile:
readCSV = csv.reader(csvFile, delimiter = ',')
for line in readCSV:
lol.append(line)
return lol
def get_index_with_min_abs_score_difference(goals):
"""Returns the index of the team with the smallest difference
between 'for' and 'against' goals, in terms of absolute value.
Arguments: parsed_data is a list of lists of cleaned strings
Returns: integer row index
"""
minDiff = abs(int(goals[1][5]) - int(goals[1][6])) # first obs as benchmark.
minIndex = 1 # row 0 is header
for team in goals[2:]:
currentDiff = abs(int(team[5]) - int(team[6]))
if currentDiff < minDiff:
minDiff = currentDiff
minIndex = goals.index(team)
return minIndex
def get_team(index_value, parsed_data):
"""Returns the team name at a given index.
Arguments: index_value is an integer row index
parsed_data is the output of `read_data` above
Returns: the team name
"""
return parsed_data[index_value][0] | true |
4ff04cb313be5cb69b00b116cfaf71cfd771ba25 | spicy-crispy/python | /py4e/iterationtest.py | 373 | 4.25 | 4 | count = 0
print('Before:', count)
# This loop goes through the numbers in the list and counts their position
for thing in [9, 41, 12, 3, 74, 15]:
count = count + 1
print(count, thing)
print('After:', count)
print('Summing in a loop')
sum = 0
print('Before:', sum)
for item in [9, 41, 12, 3, 74, 15]:
sum = sum + item
print(sum, item)
print('After:', sum)
| true |
0f541ff7da0c1b58ddc9dba2b5a2b8c31e6dfe9b | spicy-crispy/python | /bio/symbol_array.py | 1,058 | 4.15625 | 4 | def symbol_array(genome, symbol):
array = {}
n = len(genome)
extended_genome = genome + genome[0:n//2 - 1] # extended because circular DNA,
# so must extend genome by length of the window (minus 1) to catch the tail to head fusion nucleotides.
# note: if you dont -1, still get same answer, just redundancy. in this case we want to add 3 nucleotides to genome to make extended genome
for i in range(n):
array[i] = pattern_count(extended_genome[i:i+(n//2)], symbol)
return array
def pattern_count(str, pattern):
count = 0
for i in range(len(str)-len(pattern)+1):
if str[i:i+len(pattern)] == pattern:
count = count + 1
return count
genome = "AAAAGGGG"
symbol = "A"
print('{0: 4, 1: 3, 2: 2, 3: 1, 4: 0, 5: 1, 6: 2, 7: 3} is correct answer')
print(symbol_array(genome, symbol), "is the result")
# array starting at i = 0 means window starting from 0 has 4 A's
# since we selected length/2 as the window (4), that means 4 A's in the [0:4] window,
# [1:5] window has 3 A's, etc | true |
ae24e94f4658933a32895c4531daecc4b537e83a | amkolotov/homework_python | /homework_6/homework_6.2.py | 566 | 4.28125 | 4 | # Реализовать класс Road (дорога)
# Определить метод расчета массы асфальта, необходимого для покрытия всего дорожного полотна
class Road:
def __init__(self, length, width):
self._length = length
self._width = width
self.__thick = 0.05
self.__consumption = 25
def mass(self):
self.mass = self._length * self._width * self.__thick * self.__consumption
return self.mass
m = Road(1000, 10)
print(m.mass())
| false |
adc84c39f426a9010de6de00f2b1c27bdf2b6807 | TiffanyD/Hangman | /GuessingWithLimit.py | 2,660 | 4.1875 | 4 | from math import pi
spaces = " "
spaces2 = " "
print ("%sShapes available to compute: Triangle, Square, Rectangle, Circle" %spaces)
def multiplier(counter,number,retain,shape):
return number if counter == 1 else multiplier(counter-1, number+retain, retain, shape)
def square():
print "%s------Enter dimensions of the square------" % spaces
side = (raw_input("%sEnter side: " % spaces2))
if side.isdigit():
area = multiplier(int(side), int(side), int(side), "square")
return area
else:
return square()
def rectangle():
print "%s------Enter dimensions of the rectangle------" % spaces
length, width = raw_input("%sEnter length: " % spaces2), raw_input("%sEnter width: " % spaces2)
if length.isdigit() and width.isdigit():
area = multiplier(int(length), int(width), int(width), "rectangle")
return area
else:
return rectangle()
def circle():
print "%s------Enter dimensions of the circle------" % spaces
radius = raw_input("%sEnter radius: " % spaces2)
if radius.isdigit():
area = multiplier(int(radius), int(radius), int(radius), "circle")
area1 = multiplier(area, pi, pi, "circle")
return area1
else:
return circle()
def triangle():
print "%s------Enter dimensions of the triangle------" % spaces
base, height = raw_input("%sEnter base: " % spaces2), raw_input("%sEnter height: " % spaces2)
if base.isdigit() and height.isdigit():
area = multiplier(multiplier(int(base), int(height), int(height), "triangle"), .5, .5, "triangle")
return area
else:
return triangle()
list_of_area = [square(), rectangle(), circle(), triangle()]
highest = max(list_of_area)
if highest == list_of_area[0]:
highest_shape = "SQUARE"
elif highest == list_of_area[1]:
highest_shape = "RECTANGLE"
elif highest == list_of_area[2]:
highest_shape = "CIRCLE"
else:
highest_shape = "TRIANGLE"
guess = (raw_input("%sEnter guess: " % spaces2).upper())
def guessing(count,highest,guess):
if count > 1:
guess2 = (raw_input("%sWRONG ANSWER, TRY AGAIN\n%s(You have one more try): " % (spaces2, spaces2)).upper())
guessing(count-1, highest, guess2)
return guess2
if highest_shape != guess:
result = guessing(2, highest_shape, guess)
if result == highest_shape:
print "%sYOU WON!" % spaces2
else:
print "%sYOU LOSE! THE CORRECT ANSWER IS %s!" % (spaces, highest_shape)
else:
print "%sYOU WIN THE GAME! CONGRATS!" % spaces2 | true |
fdcc00bc129f576f5f339c853b5919ed3963cbbd | cavan33/My_OpenBT_Backup | /PyScripts/Scikit-Learn Learning/StatisticalLearning_ScikitLearn.py | 2,549 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
================================
Statistical learning: the setting and
the estimator object in scikit-learn
================================
This section of the tutorial...
"""
from sklearn import datasets
iris=datasets.load_iris()
data=iris.data
data.shape
# Example of reshaping data to (n_samples, n_features)
digits = datasets.load_digits()
digits.images.shape
import matplotlib.pyplot as plt
plt.imshow(digits.images[-1],
cmap=plt.cm.gray_r)
data = digits.images.reshape(digits.images.shape[0], -1)
# This can be avoided in the first place with:
# X_digits, y_digits = datasets.load_digits(return_X_y=True)
# X_digits = X_digits / X_digits.max()
# Estimators generic usage:
"""
estimator = Estimator(param1=1, param2=2)
estimator.param1
estimator.estimated_param
"""
# KNN (k nearest neighbors) classification example
# Split iris data in train and test data
# A random permutation, to split the data randomly
import numpy as np
from sklearn import datasets
iris_X, iris_y = datasets.load_iris(return_X_y=True)
np.unique(iris_y)
np.random.seed(0)
indices = np.random.permutation(len(iris_X))
iris_X_train = iris_X[indices[:-10]]
iris_y_train = iris_y[indices[:-10]]
iris_X_test = iris_X[indices[-10:]]
iris_y_test = iris_y[indices[-10:]]
# Create and fit a nearest-neighbor classifier
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier()
knn.fit(iris_X_train, iris_y_train)
print(knn.predict(iris_X_test))
print(iris_y_test)
# ^Got all but one correct!
# Linear Regression Usage Example:
diabetes_X, diabetes_y = datasets.load_diabetes(return_X_y=True)
diabetes_X_train = diabetes_X[:-20]
diabetes_X_test = diabetes_X[-20:]
diabetes_y_train = diabetes_y[:-20]
diabetes_y_test = diabetes_y[-20:]
from sklearn import linear_model
regr = linear_model.LinearRegression()
regr.fit(diabetes_X_train, diabetes_y_train)
print(regr.coef_)
# The mean square error
np.mean((regr.predict(diabetes_X_test) - diabetes_y_test)**2)
# Explained variance score: 1 is perfect prediction
# and 0 means that there is no linear relationship
# between X and y.
regr.score(diabetes_X_test, diabetes_y_test)
# Ridge and Lasso examples omitted; see tutorial for code. I know them, but only conceptually
# For classification, linear regression is bad because it weights data poorly.
# Solution: Fit a sigmoid function (logistic curve)
log = linear_model.LogisticRegression(C=1e5)
log.fit(iris_X_train, iris_y_train)
# SVMs left out; revisit if you need it later | true |
113024536e704d0d7852f867f4f6b42cf2b592f1 | qqqq5566/pythonTest | /ex5.py | 852 | 4.3125 | 4 | #-*- coding:utf-8 -*-
#python 中的格式化输出变量
#如果在{0}有数字,则其他的{n},必须也是数字
my_name = 'Zend A. Shaw'
my_age = 35
my_height = 74
my_weight = 180
my_eyes = 'blue'
my_teeth = 'White'
my_hair = 'Brown'
#f 是format的意思
#print(f'Let\'s talk about {my_name}') #这中格式化字符串从Python3.6开始使用
print("Let's talk about {}.".format(my_name))
print("He's {0} inches tall".format(my_height))
print("He's {} pounds heavy".format(my_weight))
print("Actually that's not too heavy")
print("He's got {0} eyes and {1} hair.".format(my_eyes,my_hair))
print("He's teeth are usually {} depending on the coffee.".format(my_teeth))
#this line is tricky,try to get it exactly right
total = my_age + my_height + my_weight
print("If I add {0},{1},and {2} I get {3}".format(my_age,my_height,my_weight,total))
| true |
2df2ae4378929ad2fdd58be254c9795c0ee7c2aa | AadeshSalecha/HackerRank---Python-Domain | /Classes/ClassesDealingwithComplexNumbers.py | 2,658 | 4.3125 | 4 | #Classes: Dealing with Complex Numbers
#by harsh_beria93
#Problem
#Submissions
#Leaderboard
#Discussions
#Editorial
#For this challenge, you are given two complex numbers, and you have to print the result of their addition, subtraction, multiplication, division and modulus operations.
#
#The real and imaginary precision part should be correct up to two decimal places.
#
#Input Format
#
#One line of input: The real and imaginary part of a number separated by a space.
#
#Output Format
#
#For two complex numbers and , the output should be in the following sequence on separate lines:
#
#
#For complex numbers with non-zero real and complex part, the output should be in the following format:
#
#Replace the plus symbol with a minus symbol when .
#
#For complex numbers with a zero complex part i.e. real numbers, the output should be:
#
#For complex numbers where the real part is zero and the complex part is non-zero, the output should be:
#
#Sample Input
#
#2 1
#5 6
#Sample Output
#
#7.00+7.00i
#-3.00-5.00i
#4.00+17.00i
#0.26-0.11i
#2.24+0.00i
#7.81+0.00i
#Concept
#
#Python is a fully object-oriented language like C++, Java, etc. For reading about classes, refer here.
#
#Methods with a double underscore before and after their name are considered as built-in methods. They are used by interpreters and are generally used in the implementation of overloaded operators or other built-in functionality.
#
#__add__-> Can be overloaded for + operation
#
#__sub__ -> Can be overloaded for - operation
#
#__mul__ -> Can be overloaded for * operation
class complex_number:
def __init__(self, complex_num):
self.cn = complex_num
def print_num(self):
if self.cn.imag > 0.00:
print str(format(self.cn.real, '.2f')) + '+' + str(format(self.cn.imag, '.2f')) + 'i'
elif self.cn.imag < 0.00:
print str(format(self.cn.real, '.2f')) + str(format(self.cn.imag, '.2f')) + 'i'
elif self.cn.imag == float(0.00):
print str(format(self.cn.real, '.2f')) + '+' + str(format(0.00,'.2f')) + 'i'
def add(c1, c2):
complex_number(c1+c2).print_num()
def sub(c1, c2):
complex_number(c1-c2).print_num()
def mul(c1, c2):
complex_number(c1*c2).print_num()
def div(c1, c2):
complex_number(c1/c2).print_num()
def mod(c):
complex_number(abs(c)).print_num()
c_a, c_c = map(float, str(raw_input()).split())
c = (complex(c_a, c_c))
d_a, d_c = map(float, str(raw_input()).split())
d = (complex(d_a, d_c))
add(c,d)
sub(c,d)
mul(c,d)
div(c,d)
mod(c)
mod(d)
| true |
8239b18b51180346a0d573b10a46ffb9d6ceec56 | fapers/python-beginners-example | /dicionario.py | 787 | 4.53125 | 5 | '''Tuplas (), o conteúdo não pode ser alterado ou removido'''
teste = (1,2,3)
print(teste[1])
'''Dicionário {}, possui chave e valor e pode ser acessado pela chave'''
pins = {"Mike":1234, "Joe":1111, "Jack":2222}
print(pins['Jack'])
print(pins.keys())
print(pins.values())
person97 = {"name":"Jack", "surname":"Smith", "age":"29"}
print(person97)
# Removing pair "name":"Jack"
person97.pop("name")
print(person97)
# Adding new pair "name":"Jack"
person97["name"] = "Jack"
print(person97)
{'surname': 'Smith', 'age': '29', 'name': 'Jack'}
# Changing an existing value
person97["age"] = 30
print(person97)
{'surname': 'Smith', 'age': 30, 'name': 'Jack'}
# Mapping two lists to a dictionary:
keys = ["a", "b", "c"]
values = [1, 2, 3]
mydict = dict(zip(keys, values))
print(mydict)
| false |
cd9f1f81a4b28f44315851db386f710356a8ffe7 | Seemasikander116/ASSIGNMENT-1-2-AND-3 | /Assignment 3.py | 1,760 | 4.125 | 4 | #!/usr/bin/env python
# coding: utf-8
# Seema Sikander
# seemasikander116@gmail.com
# Assignment #3
# PY04134
# question 1: Make calculator with addition , subtraction, multiplication, division and power
# In[1]:
print('***Calculator***')
x=int(input('Enter Number1:'))
y=int(input('Enter Number2:'))
print('Sum of {} + {} = '.format(x,y))
print(x+y)
print('Subtraction of {} - {} = '.format(x,y))
print(x-y)
print('Multiplication of {} x {} = '.format(x,y))
print(x*y)
print('Division of {} / {} = '.format(x,y))
print(x/y)
print('Power of Number1 {}= '.format(x))
print(x*x)
print('Power of Number2 {}= '.format(y))
print(y*y)
# Question 2:Check if any numeric value present in the list.
# In[2]:
list1 = [1,5,-19,7,89,-99]
for num in list1:
if num >= 0:
print(num,end=" ")
# Question 3:Add a key to a dictionery
# In[3]:
a = {0:30, 12:10}
print(a)
a.update({9:40})
print(a)
# Question 4:Sum all numeric items in the dictionery
# In[4]:
d={'A':100,'B':540,'C':239}
print("Total sum of values in the dictionary:")
print(sum(d.values()))
# Question 5:Identify dublicate values.
# In[5]:
my_list = [20,30,50,30,6,50,15,11,20,40,50,15,6,7]
my_list.sort()
print(my_list)
new_list = sorted(set(my_list))
dup_list =[]
for i in range(len(new_list)):
if (my_list.count(new_list[i]) > 1 ):
dup_list.append(new_list[i])
print(dup_list)
# Question 6:Check of given key is already exits in a dictionery.
# In[6]:
def checkKey(dict, key):
if key in dict:
print("Present, ", end =" ")
print("value =", dict[key])
else:
print("Not present")
dict = {'a': 100, 'b':200, 'c':300}
key = 'b'
checkKey(dict, key)
key = 'w'
checkKey(dict, key)
# In[ ]:
| true |
772101a29feadcb198dcba45f0a2300edfd54ecc | suniljarad/unity | /Assignment2_3.py | 1,113 | 4.53125 | 5 | #
#Step 1 : Understand the problem statement
#step 2 : Write the Algorithm
#Step 3 : Decide the programming language
#Step 4 : Write the Program
#Step 5 : Test the Written Program
#program statement:
# accept one number from user and return its factorial.
##################################################################################################
#Algorithm
#Start
#Accept one number from user as no
#Display Factorial of that number on screen
##End
####################################################################################################
#Function Name: Factorial()
#input :Integer
#output:integer
#Description:Display Factorial of number on screen
#Author: Sunil Bhagwan Jarad
#Date:19/2/2021
####################################################################################################
def Factorial(no):
fact=1
for i in range(1,no+1):
fact=fact*i
print("Factorial No is:",fact)
def main():
value=int(input("Enter the Number:"))
Factorial(value)
if __name__ == "__main__":
main()
| true |
32ba947924046228ab39a8ac4ff350d3e38613eb | suniljarad/unity | /Assignment1_3.py | 1,294 | 4.28125 | 4 | #
#Step 1 : Understand the problem statement
#step 2 : Write the Algorithm
#Step 3 : Decide the programming language
#Step 4 : Write the Program
#Step 5 : Test the Written Program
#program statement:
# Take one function named as Add() which accepts two numbers from user and return addition of that two numbers.
##################################################################################################
#Algorithm
#Start
#Accept first number as no1
#Accept second number as no2
#return addition of no1 & no2
#Display Addition of the user
#End
####################################################################################################
#Function Name: Add()
#input :Integer,Integer
#output:Integer
#Description: Perform addition of Two numbers
#Author: Sunil Bhagwan Jarad
#Date:19/2/2021
####################################################################################################
def Add(no1,no2):
ans=no1+no2
return ans
def main():
print("Enter first number:")
value1=int(input())
print("Enter second number:")
value2=int(input())
Ret=Add(value1,value2)
print("Addition of {} and {} is {} ".format(value1,value2,Ret))
if __name__ == "__main__":
main()
| true |
7f2a3f00292a7cd74e77020f9ac27c9f142f9c04 | suniljarad/unity | /Assignment1_8.py | 1,066 | 4.5 | 4 | #
#Step 1 : Understand the problem statement
#step 2 : Write the Algorithm
#Step 3 : Decide the programming language
#Step 4 : Write the Program
#Step 5 : Test the Written Program
#program statement:
# accept number from user and print that number of “*” on screen
##################################################################################################
#Algorithm
#Start
#Accept number as no1
#Display * on Screen
##End
####################################################################################################
#Function Name: DisplayStar()
#input :Integer
#output:string
#Description: display number of "*" on screen
#Author: Sunil Bhagwan Jarad
#Date:19/2/2021
####################################################################################################
def DisplayStar(no1):
icnt=0
for icnt in range(0,no1):
print("*")
def main():
print("Enter number:")
value=int(input())
DisplayStar(value)
if __name__ == "__main__":
main()
| true |
80c369d21ed6c57919bc5700a044d51c26cb6857 | suniljarad/unity | /Assignment2_1.py | 1,936 | 4.125 | 4 | #
#Step 1 : Understand the problem statement
#step 2 : Write the Algorithm
#Step 3 : Decide the programming language
#Step 4 : Write the Program
#Step 5 : Test the Written Program
#program statement:
#Create on module named as Arithmetic which contains 4 functions as Add()for addition,Sub()for subtraction,Mult()for multiplication and Div()for division.
# All functions accepts two parameters as number and perform the operation.
##################################################################################################
#Algorithm
#Start
#Accept first number as no1
#Accept second number as no2
#perform all operation (addition,subtraction,multiplication,division) given as two parameters as number
#Display addition,subtraction,multiplication,division on Screen
##End
####################################################################################################
#Function Name: Display()
#input :Integer,Integer
#output:Integer
#Description:Display addition,subtraction,multiplication,division on Screen
#Author: Sunil Bhagwan Jarad
#Date:19/2/2021
####################################################################################################
#import Arithmetic
#import Arithmetic as AR
#from Arithmetic import Add,Sub,Mult,Div
from Arithmetic import *
def main():
print("enter first number:")
value1 = int(input())
print("enter second number:")
value2=int(input())
ret1 = Add(value1,value2)
print("Addition of {} and {} is {}".format(value1, value2, ret1))
ret2 = Sub(value1,value2)
print("Substraction of {} and {} is {}".format(value1,value2,ret2))
ret3 = Mult(value1,value2)
print("Substraction of {} and {} is {}".format(value1,value2,ret3))
ret4 = Div(value1,value2)
print("Substraction of {} and {} is {}".format(value1,value2,ret4))
if __name__ =="__main__":
main()
| true |
41ca92cc3e3850e3e24d28a55e594ae386bab853 | Bhumiika16/Python_Assignment | /Problem(2.5).py | 520 | 4.28125 | 4 | #Length, Breadth and Heigth of both the cuboid is taken as an input from user.
dimensions_x = list(map(int, input().split(",")))
dimensions_y = list(map(int, input().split(",")))
#Initialized volume of both the cuboid as One.
volume_of_x, volume_of_y = 1, 1
#Loop is run 3 times to multiply all the 3 dimesnions of the cuboid.
for i in range(3):
volume_of_x = volume_of_x * dimensions_x[i]
volume_of_y = volume_of_y * dimensions_y[i]
print("Difference in volume of cuboid is : ",volume_of_y - volume_of_x) | true |
7e8d417286b457522937ab5bf79664b56322ee38 | chiren/kaggle-micro-courses | /python/lesson-03/ex-02.py | 339 | 4.125 | 4 | """
Exercise 02:
Define a function named avg2 which takes 2 arguments n1, n2 and return the average
of n1, n2.
Then run your avg2 function with 2 numbers, and print out the result
ex:
result = avg2(3, 4)
print("Result:", result)
"""
# define your function here
# Call your function with 2 numbers, and print out your result here
| true |
a0d2d1375a743c8efc7264405b0698de33eb9f45 | chiren/kaggle-micro-courses | /python/lesson-03/ex-05-solution.py | 698 | 4.25 | 4 | """
Exercise 05:
Define 2 functions. The first one named larger which takes 2 numbers,
and return the larger of the 2 numbers. The second one named smaller which
takes 2 numbers and return the smaller one.
Call your functions with 2 number, and print out the results
ex:
a, b = 4, -5
print("The larger of a and b is", larger(a, b))
print("The smaller of a and b is", smaller(a, b))
"""
# define your functions here
def larger(n1, n2):
return n1 if n1 > n2 else n2
def smaller(n1, n2):
return n1 if n1 < n2 else n2
# Call your functions and print out your results here
a, b = 4, -5
print("The larger of a and b is", larger(a, b))
print("The smaller of a and b is", smaller(a, b))
| true |
596798d01ca2ddc3e7498da16e9066dec7c042c1 | chiren/kaggle-micro-courses | /python/lesson-04/ex-01-solution.py | 752 | 4.125 | 4 | """
Function Name: first_item
Function Arguments: list
Return: The first item of the list
Function Name: last_item
Function Arguments: list
Return: The last item of the list
"""
# define your function here
def first_item(list):
return list[0]
def last_item(list):
return list[-1]
# The following codes test your functions
list = [1, 2, 3, 4, 5, 6, 7]
expect_first, expect_last = 1, 7
return_first = first_item(list)
return_last = last_item(list)
assert return_first == expect_first, f"\nFailed: first_item({list})\nYour answer is {return_first} and expected answer is {expect_first}."
assert return_last == expect_last, f"\nFailed: last_item({list})\nYour answer is {return_last} and expected answer is {expect_last}"
print("Correct!") | true |
8c83babb242becf48e9f9da462432a43addbdf5f | chiren/kaggle-micro-courses | /python/lesson-05/ex-09.py | 992 | 4.5 | 4 | """
Define a function which takes a list of grades, and calculates the Grade Point Average(GPA)
for the courses taken. Assuming each course has the same weight.
Function Name: gpa
Function Arguments: grades which is a list of grades
Returns gpa which is a decimal number
** NOTE **
This time there is no grade_to_point function.
Remember in lesson 4, we learn a list method index(item) which
return the index value of item found in the list.
To convert grade to point, we can use a list with items like: ['F', 'D', 'C', 'B', 'A']
and use its index method to get index value as the grade's point.
For example: to find out B's point, B's index value in the ['F', 'D', 'C', 'B', 'A']
is 3 which happens to be grade B's point
"""
# define your function here
# The following codes test your function
grades = ['C', 'A', 'B', 'A', 'D']
expected = 2.8
result = gpa(grades)
assert result == expected, f"\nFailed: \nYour answer is {result}\nExpected answer is {expected}."
print("Correct!") | true |
30ab097763c7edfee6c142b052a27726973723a4 | Choumingzhao/ProgrammingProjectList | /TextProcessing/PigLatin.py | 566 | 4.15625 | 4 | # -*- encoding:utf-8 -*-
import re
def pigLatin(word):
if word.isalpha() is False:
raise TypeError
lower = word.lower()
# When word is not started with vowel letter
if all([not lower.startswith(i) for i in 'aeiou']):
head = re.match(r'[bcdfghjklmnpqrstvwxyz]+', lower).group()
result = lower.replace(head, '')+head+'ay'
else:
result = word+"way"
if word[0].isupper():
return result.capitalize()
else:
return result
if __name__ == "__main__":
word = "Hello"
print(pigLatin(word))
| false |
dda91b44d572827db5ce113732a936e22058d125 | hoops92/Intro-Python-I | /src/05_lists.py | 545 | 4.34375 | 4 | # For the exercise, look up the methods and functions that are available for use
# with Python lists.
x = [1, 2, 3]
y = [5, 6, 7]
# For the following, DO NOT USE AN ASSIGNMENT (=).
# Change x so that it is [1, 2, 3, 4]
# YOUR CODE HERE
x.append(4)
print(x)
# Using y, change x so that it is [1, 2, 3, 4, 8, 9, 10]
# YOUR CODE HERE
for i in y:
x.append(i)
print(x)
# Change x so that it is [1, 2, 3, 4, 9, 10]
# YOUR CODE HERE
x.pop(4)
print(x)
# Change x so that it is [1, 2, 3, 4, 9, 99, 10]
# YOUR CODE HERE
x.insert(5, 99)
print(x)
| true |
ced82fd1194a648e6f884744d02261fa3c4758a8 | yusuf-zain/1786-voting-simulator | /1786-voting-simulator.py | 1,378 | 4.125 | 4 | import sys
print("""""")
print("""Welcome to Voting Simulator 1786.
Before we can decide whether you could vote,
we will have to ask you some questions.
Please answer in a yes/no format (besides age).
""")
closing = """Thank you for playing!"""
landowner = (input("Do you own any land? ").lower())
if landowner is not {"no", "yes"}:
print("please answer with yes or no")
landowner = (input("Do you own any land? ").lower())
if landowner == "no":
print(""" Sorry you would not be able to vote""")
print(closing)
sys.exit()
Ethnicity = (input("Are you Caucasian? ").lower())
if Ethnicity is not {"no", "yes"}:
print("please answer with yes or no")
Ethnicity = (input("Are you Caucasian? ").lower())
if Ethnicity == "no":
print(" Sorry you would not be able to vote")
print(closing)
sys.exit()
gender = (input("Are you female? ").lower())
if gender is not {"no", "yes"}:
print("please answer with yes or no")
gender = (input("Are you female? ").lower())
if gender == "yes":
print(" Sorry you would not be able to vote")
print(closing)
sys.exit()
age = (int(input("How old are you? ")))
if age < 21:
print(" Sorry you would not be able to vote")
print(closing)
sys.exit()
if age >= 21:
print(" Congratulations! You are a part of the 20% of the population who could vote at that time!")
print(closing)
sys.exit()
| true |
4fb31538c36bc9ed15236ec487ef579ae17855e9 | reisenbrandt/python102 | /sequences.py | 1,182 | 4.5 | 4 | # strings
'example string'
empty_string = ''
# integers
7
# floats
7.7
# booleans
True
False
# list => indicated by square brackets
languages = ['python', 'javascript', 'html', 'css']
empty_list = []
# lists use a zero based index => ALWAYS starts at 0
# lists have two indexes => a positive index and a negative index
# accessing items at certain index
print(languages[2])
# console prints html ^
# accessing an index that doesnt exist like languages[6]
# makes console throw IndexError
# accesses list from end and go towards to the beginning
print(languages[-1])
# console prints css ^
print(languages[1:3])
# will print another array with those indexes
# always goes left to right
print(languages[1:3:1])
print(languages[::-1])
# prints the list backwards
print(languages.index('css'))
# prints the index of the item in the list
string = 'example'
print(string[3])
# prints the letter m because example is a sequence in the variable
# in the form of a string
#
#
#
#
index = 0
while index < len(languages):
print (f'No, {languages[index]} is the best language')
index += 1
for lang in languages:
print('No, ' + lang + ' is the best language.') | true |
7cdf8971bb0c2e8cfd7886227578219128aa9e18 | gxgarciat/Playground-PythonPractice | /D4_p.py | 2,491 | 4.3125 | 4 | # Type a program that will play Rock, Paper, Scissors against the user
# Use the ASCII code to show the selection from the computer and the user
import random
computerRound = 0
rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
__________)
(____)
---.__(___)
'''
# Input Block
print("Welcome to Rock, Paper, Scissors")
print("")
print("***********************************")
print(" Let's start ")
print("***********************************")
print("")
userRound = int(input("What do you choose? Type 0 for Rock, 1 for Paper or 2 for Scissors. \n"))
if userRound == 0:
print(rock)
elif userRound == 1:
print(paper)
else:
print(scissors)
# Operation block
computerRound = random.randint(0,2)
print("Computer chose:")
if computerRound == 0:
print("Rock")
print(rock)
elif computerRound == 1:
print("Paper")
print(paper)
else:
print("Scissors")
print(scissors)
# Both are equal
if computerRound == userRound:
print("***********************************")
print(" Draw")
print("***********************************")
# Rock wins against scissors
if computerRound == 0 and userRound == 2:
print("***********************************")
print(" Computer win")
print("***********************************")
elif computerRound == 2 and userRound == 0:
print("***********************************")
print(" You win")
print("***********************************")
# Paper wins against rock
if computerRound == 1 and userRound == 0:
print("***********************************")
print(" Computer win")
print("***********************************")
elif computerRound == 0 and userRound == 1:
print("***********************************")
print(" You win")
print("***********************************")
# Scissors win against paper
if computerRound == 2 and userRound == 1:
print("***********************************")
print(" Computer win")
print("***********************************")
elif computerRound == 1 and userRound == 2:
print("***********************************")
print(" You win")
print("***********************************")
# Output block
| true |
6f05809c55668ea82385da806958702556da9912 | gxgarciat/Playground-PythonPractice | /D3_c4.py | 1,205 | 4.40625 | 4 | # Build a program that create an automatic pizza order
# Consider that there are three types of pizza: Small ($15), Medium ($20) and large ($25)
# If you want to add pepperoni, you will need to add $2 for a small pizza
# For the Medium or large one, you will need to add $3
# If you want extra cheese, the added price will be $1, for any size
totalBill = 0
# Input block
print("Welcome to Python Pizza Deliveries!")
pizzaSize = input("What size of pizza do you want? S, M L \n")
pepperoniOption = input("Do you want pepperoni? Y, N \n")
extraCheese = input("Do you want extra cheese? Y, N \n")
# Operations block
smallP = 15
mediumP = 20
largeP = 25
if pizzaSize == "S":
totalBill = totalBill + smallP
if pepperoniOption == "Y":
totalBill = totalBill + 2
elif pizzaSize == "M":
totalBill = totalBill + mediumP
else:
totalBill = totalBill + largeP
if pepperoniOption == "Y" and pizzaSize != "Y":
totalBill = totalBill + 3
if extraCheese == "Y":
totalBill = totalBill + 1
totalBill = round(totalBill,2)
# Output block
print("\n****************************************")
print(f" The final bill is ${totalBill}.")
print("****************************************")
| true |
ecd967ece7662a1551df91ec391e81c29d947220 | soyo-kaze/PythonTuT101 | /Chap2 Functions.py | 770 | 4.28125 | 4 | """
-Chapter 2-
\Functions/
->It is systematic way of solving a problem by dividing the problem into several
sub-problems and then integrating them and form final program.
->This approach also called stepwise refinement method or modular approach.
=Built-in Functions=
1. input function: accepts string from user without evaluating its value.
Example-
"""
name=input("Enter a name:")
print("---------\n")
"""
2. eval function: evaluates the value of string.
Example-
"""
eval('15+10')
print("---------\n")
"""
3. Composition function: value returned by fun may be used as an argument for another
fun in a nested manner. Its called composition.
"""
n1=eval(input("Enter a number: "))
n2=eval(input("Enter arithmetic expression: "))
"""
More Content coming
"""
| true |
932d18a22a09731d2782c046f68b299a8b6906f1 | SadraZg/python_mini_projects | /Queue.py | 1,264 | 4.21875 | 4 | from LinkedList import *
class Queue:
def __init__(self):
self.queue = LinkedList()
def is_empty(self):
return self.queue.is_empty()
def enqueue(self, element):
self.queue.insert_last(element)
def dequeue(self):
return self.queue.delete_first()
def print_queue(self):
self.queue.print_list()
class QueueByList:
""" Using Python built-in list functions are a bit
more expensive than using the LinkedList class """
def __init__(self):
self.queue = []
def is_empty(self):
if len(self.queue) == 0:
return True
else:
return False
def enqueue(self, element):
self.queue.insert(0, element)
def dequeue(self):
return self.queue.pop()
def print_queue(self):
print(self.queue)
def use_queue():
q = QueueByList()
q.enqueue(1)
q.enqueue(2)
q.enqueue(3)
q.enqueue(4)
q.enqueue(5)
q.print_queue()
q.dequeue()
q.dequeue()
q.print_queue()
print(q.is_empty())
while not q.is_empty():
q.dequeue()
print(q.is_empty())
q.print_queue()
if __name__ == '__main__':
use_queue()
| false |
af65992a62e81fb46ac24b27ce8c2f6bb1c2ccbd | SadraZg/python_mini_projects | /DoubleLinkedList.py | 1,336 | 4.3125 | 4 | class Node:
def __init__(self, element=None):
self.element = element
self.next_node = None
self.prev_node = None
class DoubleLinkedList:
""" A double LinkedList has both way arrows ' ↔ ' between nodes """
def __init__(self):
self.head = None
def is_empty(self):
if self.head is None:
return True
else:
return False
def delete_first(self):
n = self.head
self.head = n.next_node
if self.head is not None:
self.head.prev_node = None
n.next_node = None
def insert_first(self, element):
n = Node(element)
if self.head is None:
self.head = n
else:
self.head.prev_node = n
n.next_node = self.head
self.head = n
def print_list(self):
n = self.head
print('[', end=' ')
while n is not None:
print(n.element, end=' ')
n = n.next_node
print(']')
def double_linked_list():
d = DoubleLinkedList()
d.insert_first(1)
d.insert_first(2)
d.insert_first(3)
d.print_list()
while not d.is_empty():
d.delete_first()
d.print_list()
if __name__ == '__main__':
double_linked_list()
| false |
cbab49aae4192297353906881985b65627eafa20 | mateusrmoreira/Curso-EM-Video | /desafios/desafio04.py | 521 | 4.4375 | 4 | ''' 13/03/2020 by jan Mesu
Escreva um valor e printe o tipo primitivo
e todas as informações sobre ele.
'''
from cores import cores
n = input('Digite alguma coisa: ')
print(
f"""{cores['vermelho']}
O tipo primitivo de {n} é {type(n)}
Alphanumerico {n.isalpha()}
É numerico {n.isnumeric()}
lowercase {n.islower()}
Idenficador {n.isidentifier()}
Digito {n.isdigit()}
Title {n.istitle()}
Printavel {n.isprintable()}
uppercase {n.isupper()}
Space {n.isspace()}
{cores['limpar']}
""") | false |
6108cfde46b2d1acd5996aebd89ea52d074929f4 | mateusrmoreira/Curso-EM-Video | /desafios/desafio37.py | 473 | 4.25 | 4 | """ 25/03/2020 jan Mesu
Escreva um programa que peça um número inteiro qualquer
e peça para o usuário escrever uma base de conversão.
[1] Converter para Binários
[2] Converter para octal
[3] Converter para hexadecimal
"""
select = int(input("""
Escolha uma base numéria para conversão
1 - Para binários
2 - Para octal
3 - Para Hexadecimal
Escolha um número # """))
answer = int(input('Escreva um número para converter na base escolhida $ '))
if select == 1:
answer = bin(answer)
elif select == 2:
answer = oct(answer)
elif select == 3:
answer = hex(answer)
elif select > 3:
print('Opção inválida tente novamente ')
print(answer)
| false |
dce5e0e8c42cb355700d961c51b1a4f7f508ed3b | vidyakinjarapu/Automate_the_boring_stuff | /ch_6/bulletPointAdder.py | 603 | 4.1875 | 4 | '''
get the text from the clipboard, add a star and space to the beginning of each
line, and then paste this new text to the clipboard.
1.Paste text from the clipboard.
2.Do something to it.
3.Copy the new text to the clipboard. '''
#!python
import pyperclip
text = pyperclip.paste()
# print(text)
#Code to add star and a space
lines = text.split('.')
print(lines)
for i in range(len(lines)):
lines[i] = '* ' + lines[i]
print (lines[i])
text = '\n'.join(lines)
pyperclip.copy(text)
# Lists of animals
# Lists of aquarium life
# Lists of biologists by authorabbreviation
# Lists of cultivars
| true |
c0cb1ce6d8aabc41c28bc63f22e137c4a939c6ed | vidyakinjarapu/Automate_the_boring_stuff | /ch_2/rpsown.py | 1,879 | 4.21875 | 4 | """
ROCK, PAPER, SCISSORS
0 Wins, 0 Losses, 0 Ties
Enter your move: (r)ock (p)aper (s)cissors or (q)uit
p
PAPER versus...
PAPER
It is a tie!
0 Wins, 1 Losses, 1 Ties
Enter your move: (r)ock (p)aper (s)cissors or (q)uit
s
SCISSORS versus...
PAPER
You win!
1 Wins, 1 Losses, 1 Ties
Enter your move: (r)ock (p)aper (s)cissors or (q)uit
q
"""
import random, sys
print("ROCK, PAPER, SCISSORS")
Wins = 0
Losses = 0
Ties = 0
while True:
print("%s wins, %s losses, %s ties" %(Wins, Losses, Ties))
while True:
user_move = input("Enter your move: (r)ock (p)aper (s)cissors or (q)uit : ")
if user_move == 'q' :
sys.exit()
elif user_move == 'r' or user_move == 'p' or user_move == 's':
break
print("Please enter ony one of r, p, s")
#Printing the user's move.
if user_move == 'r':
print('ROCK verses...')
elif user_move == 'p':
print('PAPER verses...')
else :
print('SCISSORS verses...')
#printing what computer choose
li = ['r', 'p', 's']
comp_move = random.choice(li)
if comp_move == 'r':
print('ROCK')
elif comp_move == 'p':
print('PAPER')
else :
print('SCISSORS')
#Game to find wind and Losses
if user_move == comp_move :
print("It's a tie")
Ties += 1
elif user_move == 'p' and comp_move == 'r':
print("You win")
Wins += 1
elif user_move == 'p' and comp_move == 's':
print("You lost")
Losses += 1
elif user_move == 'r' and comp_move == 'p':
print("You lost")
Losses += 1
elif user_move == 'r' and comp_move == 's':
print("You win")
Wins += 1
elif user_move == 's' and comp_move == 'r':
print("You lost")
Losses += 1
elif user_move == 's' and comp_move == 'p':
print("You win")
Wins += 1
| false |
2845bdc789527ab56b480d192a93288088d5484f | myGitRao/Python | /Operators.py | 640 | 4.15625 | 4 | # Arithmetic
print("Arithmetic operators")
print("5 + 6 = ", 5 + 6)
print("5 - 6 = ", 5 - 6)
print("5 * 6 = ", 5 * 6)
print("5 / 6 = ", 5 / 6)
print("5 ** 6 = ", 5 ** 6)
print("5 // 6 = ", 5 // 6)
print("5 % 6 = ", 5 % 6)
# Assignment
print("Assignment operators")
x = 5
print(x)
x -= 7
print(x)
# Comparison
print("Comparison operators")
i = 5
print(i == 8)
print(i <= 10)
print(i != 12)
# Logical
a = True
b = False
print(a or b)
print(a and b)
# identity
print(a is not b)
print (a is b)
# Bitwise
cc =0
aa = 1
bb = 2
print(aa | bb)
print(aa & bb)
print(aa | cc)
print(aa & cc)
# Membership
list = [2,5,89,12,3,4]
print(5 in list)
| false |
f6f37a78f00dd4ae18d8a3b203f6420365d9baac | Sai-Bharadwaj/JenkinsWorking | /input.py | 403 | 4.15625 | 4 | x=int(input("Enter First Number:"))
y=int(input("Enter Second Number:"))
#z=int(input("Enter Third Number:"))
#if(x>y):
# print("First number is greater,",x)
#else:
# print("Second Number is greater,",12)
#l= x if x>y and x>z else y if y>z else z
#print("Max values is:",l)
l = "Both Numbers are equaly" if x==y else "First number is greater" if x>y else "First number is Smallest:"
print(l)
| true |
b2ae37fbc3424ab6abf424c972dfcf0f71c029ef | Dominic-Perez/CSE | /LuckySevens/More Python Notes.py | 1,620 | 4.46875 | 4 | #shopping_list(0) = "2% milk"
#print(shopping_list)
#print(shopping_list[0])
# Looping through lists
#for item in shopping_list:
# print(item)
'''
1. Make a list
2. change the 3rd thing on the list
3. print the item
4.print the full list
'''
#List = ["straw", "nut", "glass", "lime", "table", "chair", "Tonatiuh", "Kacchan", "Adam"]
#List[2] = "5&"
#print(List[2])
#print(List)
# new_list = {"eggs", "cheese", "oranges"}
# new_list[2] = "apples"
# print("The last thing in the list is %s" % new_list[len(new_list] - 1)
# print(new_list)
# Getting part of a list
#print(new_list[1:4])
# print(new_list[1:])
#print(new_list[:2])
# Adding things to a list
#holiday_list = []
# holiday_list.append("Tacos")
# holiday_list.append("Bumblebee")
# holiday_list.append("Red Dead Redemption 2")
# print(holiday_list)
# Notice this is object.method(Parameters)"
# Removing things from a list
# holiday_list.remove("Tacos")
# print(holiday_list)
#List = ["Cheese, Bacon, Eggs"]
#List[2] = "Milk"
#List.remove("Milk")
#brands = ("Apple", "Samsung", "HTC") # notice the parentheses
colors = ['blue', 'cyan', 'teal', 'red', 'green', 'orange', 'purple', 'clear', 'grey', 'black', 'white', 'pink', 'rose']
#print(len(colors))
# Find the index
print(colors.index("green"))
# Changing things into a list
string1 = "grey"
list1 = list(string1)
print(list1)
# Changing lists into strings
print("ree".join(list1))
for character in list1:
if character == "r":
# replace with a *
current_index = list1.index(character)
list1.pop(current_index)
list1.insert(current_index, "*") | true |
0d533fc1830ec11bab5fef1a327a42f1c5a7574b | morningred88/data-structure-algorithms-in-python | /Array/string-slicing.py | 957 | 4.25 | 4 | def sliceString(s):
# Specify the start index and the end index, separated by a colon, to return a part of the string. The end index is not included
# llo, get the characters from position 2 to position 5 (not included)
s = s[2:5]
# Slice from the start
# hello world, whole string
s = s[:]
# hello, get the characters from the start to position 5 (not included)
s = s[:5]
# Negative Indexing, the last character is -1
# hello worl, does not include the last character
s = s[:-1]
# hello wor, does not include the last 2 characters
s = s[:-2]
# Slice to the end
# llo world, from position 2 all the way to the end
s = s[2:]
# slice in steps
s = s[::-1] # dlrow olleh, move backwards in 1 step - reverse string
s = s[::-2] # drwolh, move backwords in 2 steps
s = s[::+2] # hlowrd, move forwards in 2 steps
return s
if __name__ == '__main__':
print(sliceString('hello world'))
| true |
70478953dc18bd961f381cea434778136ad37f03 | morningred88/data-structure-algorithms-in-python | /Stack-Queue/stack.py | 1,301 | 4.125 | 4 | # LIFO:last item we insert is the first item we take out
class Stack():
# Use one dimensional array as underlying data structure
def __init__(self):
self.stack = []
# Insert item into the stack //O(1)
def push(self, data):
self.stack.append(data)
# remove and return the last item we have insert (LIFO) //O(1)
def pop(self):
if self.stack_size() <1:
return -1
data = self.stack[-1]
del self.stack[-1]
return data
# Get the value of last added item without removing it //O(1)
def peek(self):
return self.stack[-1]
# has 0(1) running time
def is_empty(self):
return self.stack == []
def stack_size(self):
return len(self.stack)
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
print(f'Stack size: {stack.stack_size()}')
print(f'Popped item: {stack.pop()}')
print(f'Stack size: {stack.stack_size()}')
print(f'Peeked item: {stack.peek()}')
print(f'Stack size: {stack.stack_size()}')
print(f'Popped item: {stack.pop()}')
print(f'Popped item: {stack.pop()}')
print(f'Popped item: {stack.pop()}')
print(f'Popped item: {stack.pop()}')
# Result:
# Stack size: 3
# Popped item: 3
# Stack size: 2
# Peeked item: 2
# Stack size: 2
# Popped item: 2
# Popped item: 1
# Popped item: -1
# Popped item: -1
| true |
a2c12bafe8d659445718e4ad683d41205e2b07e7 | rahulmajjage/Learning | /exercisescripts/list_methods.py | 1,353 | 4.375 | 4 | #High Scores program
#Demonstrate List methods
#Create an empty list
scores = []
choice = None
#Print the options
while choice !="0":
print (\
"""
\t High Scores Keeper
0: Exit
1: Show score
2: Add a score
3: Delete a score
4: Sort scores
""")
choice= input ("Choice: ")
# Exit
if (choice == "0"):
print ("\nGood bye")
# Show scores
elif (choice == "1"):
print ("\nHigh Scores:")
for score in scores:
print (score)
# Adding a score
elif (choice == "2"):
score = int (input("\nEnter the score you wish to add: "))
scores.append(score)
#Deleting a score
elif (choice == "3"):
score = int (input ("\nEnter the score you want to delete: "))
if score in scores:
scores.remove(score)
print ("\nRemoved", score)
else:
print ("\n", score, "Entered is not one of the high scores.")
# Sorting the scores
elif (choice == "4"):
scores.sort()
# As scores are sorted in ascending order and program needs high scores first
#We will reverse the list after sorting
scores.reverse()
print ("\nScores after sorting are:\n", scores)
else:
print ("\nInvalid option entered")
input ("\nPress enter to exit")
| true |
a1d8aa288a9d40f7068da878e79bc3a8e476df31 | rahulmajjage/Learning | /exercisescripts/for loop demo.py | 216 | 4.5 | 4 | #loopy string
#Demonstrates the for loop with a string.
word= input ("Enter the word: ")
print ("\n Here is each letter in your word:")
for letter in word:
print (letter)
input ("Press enter to exit")
| true |
f05c61c8cdb3877fbf8da2554e16860d1b6eb848 | rahulmajjage/Learning | /exercisescripts/exercise5_3.py | 2,403 | 4.4375 | 4 | #Exercise 5.3
#Daddy_Son_Program
# Daddy_Son Dictionary
daddy_son = { "Rahul" : "Shivalingappa",
"Nikita" : "Ramesh",
"Rohit" : "Rachappa" }
#To display the name of Father with Son's name
son = input ("\n\nEnter the name of son to get the father name: ")
if son in daddy_son:
print ("\nFather of", son , "is:\t", daddy_son[son])
else:
print ("\nSon not in list\n")
print ("\n\n")
#Display menu
choice = None
while choice != 0:
print ("""\
0: Quit
1: Add
2: Delete
3: Replace
4: List Sons
5: List Fathers
6: List daddy son pair""")
choice = int (input ("\n\nEnter your choice: "))
if choice == 0:
print ("\n\n Good Bye")
#Adding new entry
elif choice == 1:
son_new = input ("\n\nEnter the name of the son to be added: ")
if son_new not in daddy_son:
daddy_new = input ("\n\nEnter the name of the father: ")
daddy_son [son_new] = daddy_new
else:
print ("\n\nThe name of Son is already present")
# Deleting an entry
elif choice == 2:
son_new = input ("\n\nEnter the name of the son to be deleted: ")
if son_new in daddy_son:
del daddy_son [son_new]
else:
print ("\n\nThe name of Son is already present")
#Replacing an entry
elif choice == 3:
son_new = input ("\n\nEnter the name of the son whose father needs to be replaced: ")
if son_new in daddy_son:
daddy_new = input ("\n\nEnter the name of the new father: ")
daddy_son [son_new] = daddy_new
else:
print ("\n\nThe name of Son is already present")
#Displaying only the list of Sons
elif choice == 4:
print ("\n\nThe name of all the sons are:", daddy_son.keys())
#Displaying only the list of Fathers
elif choice == 5:
print ("\n\nThe name of all the Fathers are:", daddy_son.values())
#Displaying only the list of Sons and father pair
elif choice == 6:
print ("\n\nThe name of all the sons are:", daddy_son.items())
#Invalid entry
else:
print ("\n\nYou have entered an invalid entry")
input ("\n\nPress Enter to exit")
| false |
5f716a6bb3b96a3b862808a15b0a70db2573a9bf | amit0-git/simple-python-program | /English-alphabets.py | 1,048 | 4.1875 | 4 | '''Python program to print English alphabets'''
def A():
for row in range(6):
for col in range(11):
if (row+col==5) or (col-row==5) or (row==3 and row+col in[7,9]):
print('*',end='')
else:
print(end=' ')
print()
#########################
def M():
for row in range(6):
for col in range(11):
if (col==0) or (col-row==0) or (row+col==10) or (col==10):
print('*',end='')
else:
print(end=' ')
print()
#########################
def I():
for row in range(7):
for col in range(11):
if (col==5):
print('*',end='')
else:
print(end=' ')
print()
#########################
def T():
for row in range(6):
for col in range(11):
if (col != 5 and row== 0) or (col==5):
print('*',end='')
else:
print(end=' ')
print()
#########################
def V():
for row in range(6):
for col in range(11):
if (row+col==10) or (row-col==0):
print('*',end='')
else:
print(end=' ')
print()
#########################
A()
print('\v')
M()
print('\v')
I()
print('\v')
T() | false |
c28f5affcc831d411bdb327406790022a8aca2c6 | rupeshjaiswar/ekLakshya-Assignments | /Python Codes/Day 2 Assignments/6_code.py | 656 | 4.15625 | 4 | import math as m
# area of triangle with base and height given
b = int(input("Enter the base of the triangle:"))
h = int(input("Enter the height of thr triangle: "))
a = 0.5 * b * h
print(f"Area of triangle with base {b} and height {h} is {a} square meters")
# area of triangle with three sides given
x = int(input("Enter the base of the triangle:"))
y = int(input("Enter the base of the triangle:"))
z = int(input("Enter the height of thr triangle: "))
p = (x + y + z) / 2
r = m.sqrt((p * (p - x) * (p - y) * (p - z)))
r = round(r, 2)
print(f"Area of triangle with side one {x} side two {y} and side three {z} is {r} square meters") | false |
0d35bfe204dd9c003ced7b934546c60829c43e2e | rupeshjaiswar/ekLakshya-Assignments | /Python Codes/Day 2 Assignments/23_code.py | 345 | 4.3125 | 4 | str = input("Enter a string:")
print("The String is:", str)
str1 = str[0:3]
print("The first three characters in the string str:", str1)
for i in str1:
print(f"The ASCII value of the character {i} in str1 is:", ord(i))
print("The position of str1 in str is:", str.find(str1))
print("Count of str1 in str is:", str.count(str1)) | true |
b4ef894611376eae065beacbaf46be978a7500a9 | mary-lev/algo | /bubble_sort.py | 706 | 4.21875 | 4 | def bubble(numbers):
"""
Реализация алгоритма сортировки пузырьком.
"""
length = len(numbers)
for x in range(length - 1):
check = False
for y in range(length - 1 - x):
if numbers[y] > numbers[y + 1]:
check = True
numbers[y], numbers[y + 1] = numbers[y + 1], numbers[y]
if not check:
break
return numbers
if __name__ == '__main__':
print(bubble([1, 4, 7, 2, 10, 15, 20, 3, 45]))
print(bubble([1, 0]))
print(bubble([0]))
print(bubble([-23, 0, 6, -4, 34]) == sorted([-23, 0, 6, -4, 34]))
print(bubble([0, 5, 2, 3, 2]) == sorted([0, 5, 2, 3, 2])) | false |
3aa080aba1880282d9dc15b06b648c870ce78ede | presian/HackBulgaria | /Programming0-1/Week_6/2-String-Functions/strings.py | 1,026 | 4.1875 | 4 | def str_reverse(string):
return string[::-1]
# print(str_reverse("Python"))
# print(str_reverse("kapak"))
# print(str_reverse(""))
def join(delimiter, items):
return delimiter.join(items)
# print(join(" ", ["Radoslav", "Yordanov", "Georgiev"]))
# print(join("\n", ["line1", "line2"]))
def startswith(search, string):
if search in string and string.index(search) == 0:
return True
return False
# print(startswith("Py", "Python"))
# print(startswith("py", "Python"))
# print(startswith("baba", "asdbaba"))
def endswith(search, string):
if startswith(str_reverse(search), str_reverse(string)):
return True
return False
# print(endswith(".py", "hello.py"))
# print(endswith("kapak", "babakapak"))
# print(endswith(" ", "Python "))
# print(endswith("py", "python"))
def trim(string):
return string.strip()
# print(trim(" asda "))
# print(trim(" spacious "))
# print(trim("no here but yes at end "))
# print(trim(" "))
# print(trim("python"))
| false |
7e6ee9617f1a07ea20de8eb3c7c3e3dfcf08bdc4 | presian/HackBulgaria | /Algo1/Week_4/Monday/my_queue.py | 1,533 | 4.15625 | 4 | from vector import Vector
class Queue:
def __init__(self):
self.__queue = Vector()
# Adds value to the end of the Queue.
# Complexity: O(1)
def push(self, value):
self.__queue.add(value)
# Returns value from the front of the Queue and removes it.
# Complexity: O(1)
def pop(self):
if self.__queue.size() > 0:
first_elemet = self.__queue.get(0)
temp_vector = Vector()
for i in range(0, self.__queue.size()):
if i > 0:
temp_vector.add(self.__queue.get(i))
self.__queue = temp_vector
return first_elemet
else:
return None
# Returns value from the front of the Queue without removing it.
# Complexity: O(1)
def peak(self):
if self.__queue.size != 0:
return self.__queue.get(0)
return None
# Returns the number of elements in the Queue.
# Complexity: O(1)
def size(self):
return self.__queue.size()
def getQueue(self):
return self.__queue.getVector()
def main():
q = Queue()
print(q.getQueue())
q.push(5)
q.push(6)
q.push(7)
# q.push(5)
# q.push(6)
# q.push(7)
# q.push(5)
# q.push(6)
# q.push(7)
# q.push(5)
# q.push(6)
# q.push(7)
print(q.getQueue())
print(q.pop())
print(q.getQueue())
print(q.peak())
print(q.getQueue())
print(q.getQueue())
print(q.size())
if __name__ == '__main__':
main()
| true |
2939d0c2b6cbf0f63e1f9a9c3ade0f9a699f661b | willzh0u/Python | /ex34.py | 2,085 | 4.625 | 5 | # Accessing Elements of Lists
# REMEMBER: Python start its lists at 0 rather than 1.
# ordinal numbers, because they indicate an ordering of things. Ordial numbers tell the order of things in a set, first, second, third.
# cardinal numbre means you can pick at random, so there needs to be a 0 element. Cardial numbers tells how many.
# everytime you want the 3rd animal, you translate this "ordinal" number to a "cardinal" number by subtracting 1.
# the 3rd animal is at idnex 2 and is the penguin.
# you have to do this because you have spent your whole life using ordinal numbers, and you have to think in cardinal.
# Just subtract 1 and you will be good.
# REMEMBER: ordinal == ordered, 1st; cardinal == cards at random, 0.
animals = ['bear', 'python', 'peacock', 'kangaroo', 'whale', 'platypus']
# bear = animals[0]
# python = animals[1]
# peacock = animals[2]
# kangaroo = animals[3]
# whale = animals[4]
# platypus = animals[5]
print 'There are 6 animals in the race, enter a number to find our which animal finished in that place:'
while True:
rank = int(raw_input())
print "Number %d animal is: %s" % (rank, animals[rank - 1])
# 1. The animal at 1.
# # The 2nd animal is at 1 and is a Python. The animal at 1 is the 2nd animal and is a Python.
# 2. The 3rd animal.
# # the 3rd animal is at 2 and is a Peacock. The animal at 2 is the 3rd animal and is a Peacock.
# 3. The 1st animal.
# # the 1st animal is at 0 and is a bear. The animal at 0 is the 1st animal and is a bear.
# 4. The animal at 3.
# # the animal at 3 is the 4th animal and is a kangaroo. The 4th animal is at 3 and is a kangaroo.
# 5. The 5th animal.
# # the animal at 4 is the 5th animal and is a whale. The 5th animal is at 4 and is a whale.
# 6. The animal at 2.
# # the animal at 2 is the 3rd animal and is peacock. The 3rd animal is at 2 and is a peacock.
# 7. The 6th animal.
# # the 6th animal is at 5 and is a platypus. The 6th animal is at 5 and is a platypus.
# 8. The animal at 4.
# # the animal at 4 is the 5th animal and is a whale. The 5th animal is at 4 and is a whale.
| true |
aaa1b169899f0e91693b98f042442080f13d0c13 | YanteLB/pracs | /week1/python/weeek.py | 440 | 4.34375 | 4 |
#getting current day
currentDay = input("Enter the number of our current day: ")
currentDay = int(currentDay)
#getting the length of the holiday
holidayLength = input("How long is your holiday: ")
holidayLength = int(holidayLength)
returnDay = currentDay + holidayLength
if returnDay < 7:
print("You will return on day number ", returnDay)
else:
returnDay = returnDay%7
print("You will return on day number ", returnDay)
| true |
cae2f7f0945939ecdf220fd7cb06a402e7638348 | moakes010/ThinkPython | /Chapter17/Chapter17_Exercise3.py | 321 | 4.25 | 4 | '''
Exercise 3
Write a str method for the Point class. Create a Point object and print it.
'''
class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return "Point (x,y) at (%.2d,%.2d)" % (self.x, self.y)
p = Point(10, 11)
print(p) | true |
3114191f140ad280a6a71b3855580606f036cc93 | moakes010/ThinkPython | /Chapter11/Chapter11_Exercise10.py | 1,084 | 4.21875 | 4 | '''
Exercise 10
Two words are “rotate pairs” if you can rotate one of them and get the other (see rotate_word in Exercise 12).
'''
import os
def rotate_pairs(word, word_dict):
for i in range(1, 14):
r = rotate_word(word, i)
if r in word_dict:
print(word, i, r)
def rotate_letter(letter, n):
"""Rotates a letter by n places. Does not change other chars.
letter: single-letter string
n: int
Returns: single-letter string
"""
if letter.isupper():
start = ord('A')
elif letter.islower():
start = ord('a')
else:
return letter
c = ord(letter) - start
i = (c + n) % 26 + start
return chr(i)
def rotate_word(word, n):
"""Rotates a word by n places.
word: string
n: integer
Returns: string
"""
res = ''
for letter in word:
res += rotate_letter(letter, n)
return res
dword={}
cwd = os.getcwd()
for l in open(os.path.join(cwd, 'words.txt')):
word = l.strip()
dword[word] = word.lower()
for w in dword:
rotate_pairs(w, dword)
| true |
58b91fc4ac376d1f0b197c704cad38ba602b4200 | bmatis/atbswp | /chapter12/multiplicationTable.py | 1,259 | 4.28125 | 4 | #!/usr/bin/env python3
# multiplicationTable.py - takes a number (N) from command line and creates
# an N x N mulitplication table in an Excel spreadsheet
# example: multiplicationTable.py 6 to create a 6 x 6 multiplication table
import sys, openpyxl
from openpyxl.styles import Font
from openpyxl.utils import get_column_letter
# get command line argument
try:
value = int(sys.argv[1])
except:
print('Error: invalid command line argument. Please provide an int.')
exit()
# open an Excel workbook and get active sheet
wb = openpyxl.Workbook()
sheet = wb.active
# create a font object for cells that should be bold
boldFont = Font(bold=True)
# generate x axis legend
for col in range(1, value+1):
col_letter = get_column_letter(col+1)
cell = col_letter + str(1)
sheet[cell] = col
sheet[cell].font = boldFont
# generate y axis legend
for row in range(1, value+1):
cell = 'A' + str(row + 1)
sheet[cell] = row
sheet[cell].font = boldFont
# generate multiplication table
for row in range(1, value+1):
for col in range(1, value+1):
col_letter = get_column_letter(col+1)
sheet[col_letter + str(row+1)] = int(row) * int(col)
# save the workbook
wb.save('multiplicationTable_' + str(value) + '.xlsx') | true |
7183239071eca81ac679704880918eb4d22b86da | SimantaKarki/Python | /class4.py | 983 | 4.125 | 4 | #Basic2
is_old = True
is_licenced = True
#if is_old:
# print("You are old enough to drive!")
# elif is_licenced:
# print("You can Drive on Highway")
# else:
# print("Your age is not eligible to drive!")
# print("end if")
if (is_licenced and is_old):
print("You are in age and you can drive")
print("hey i am here")
# Truthy and Falsy
password = '123'
username = 'simanta'
if password and username:
print("Not empty form")
#ternary operator
#condition_if_true_ if condition else condition_if_false
is_friend = True
# can_message = "Messaging is allowed" if is_friend else "Not allowed"
# print(can_message)
# #short circuitng in python is or operator
# #logical operator
# #> < >+ == <= != and or not
# print('Hello'=="Hello")
# print(1<2<3<4)
# print(0 != 0)
# is_magician = False
# is_expert = True
# is vs ==
print(True is True)
print('1' is '1')
print([] == 1)
print(10 is 10)
print([] == [])
| true |
4ed2886bafb58f67dcb6fa4b0e0160357b4ecd19 | alvas-education-foundation/ISE_3rd_Year_Coding_challenge | /4AL17IS012_Danush_Kumar/SharanSir_codingchallenge/SharanSir_codingchallenge2/prg1.py | 686 | 4.5625 | 5 | ''' We are given 3 strings: str1, str2, and str3. Str3 is said to be a shuffle of str1 and str2
if it can be formed by interleaving the characters of str1 and str2 in a way that maintains
the left to right ordering of the characters from each string.
For example, given str1="abc" and str2="def", str3="dabecf" is a valid shuffle since it preserves
the character ordering of the two strings. So, given these 3 strings write a function that detects
whether str3 is a valid shuffle of str1 and str2. '''
def shuffle(str1,str2,str3):
a=sorted(str1+str2)
b=sorted(str3)
if(a==b):
print("Yes")
else:
print("No")
str1=input()
str2=input()
str3=input()
shuffle(str1,str2,str3) | true |
4c18f4a6bfefdb2c2de251e5a11cc4c215abb468 | alvas-education-foundation/ISE_3rd_Year_Coding_challenge | /4AL17IS001_Ahimsa_Jain/SK-Challenge-1/s2.py | 1,182 | 4.15625 | 4 | 2) Given an array,A, of N integers and an array, W, representing the respective weights of A's elements, calculate and print the weighted mean of A's elements. Your answer should be rounded to a scale of decimal place
Input format:
1. The first line contains an integer, N, denoting the number of elements in arrays A and W.
2. The second line contains N space-separated integers describing the respective elements of array A .
3. The third line contains N space-separated integers describing the respective elements of W array .
Output format:
• Print the weighted mean on a new line. Your answer should be rounded to a scale of 1 decimal place (i.e., format).
Constraints:
• N=[5 to 50]
• ai=[0 to 100]
• Wi=[0 to. 100]
def wMean(X,W,n) :
sum = 0
numWeight = 0
i = 0
while i < n :
numWeight = numWeight + X[i] * W[i]
sum = sum + W[i]
i = i + 1
return (float)(numWeight / sum)
X = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
W = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
n = len(X)
m = len(W)
if (n == m) :
print weightedMean(X, W, n)
else :
print "-1" | true |
c2920b0657f7a2d5bec5230c29e894dff78571f5 | alvas-education-foundation/ISE_3rd_Year_Coding_challenge | /4AL17IS006_VISHAK_AMIN/22May20/fourth.py | 1,126 | 4.15625 | 4 | # Given the names and grades for each student in a Physics class of students, store them in a nested list and print the name(s) of any student(s) having the second lowest grade.
# Note: If there are multiple students with the same grade, order their names alphabetically and print each name on a new line.
# Input Format
# The first line contains an integer, , the number of students.
# The subsequent lines describe each student over lines; the first line contains a student's name, and the second line contains their grade.
# Constraints
# There will always be one or more students having the second lowest grade.
# Output Format
# Print the name(s) of any student(s) having the second lowest grade in Physics; if there are multiple students, order their names alphabetically and print each one on a new line.
mark = []
scoresh = []
if __name__ == '__main__':
for _ in range(int(input())):
name = input()
score = float(input())
mark += [[name, score]]
scoresh += [score]
x = sorted(set(scoresh))[1]
for n , s in sorted(mark):
if s == x:
print(n) | true |
54672ba72d2d620401fe22b3eea9873b352c6b86 | suvo-oko/intermediate-python-course | /dice_roller.py | 956 | 4.25 | 4 | import random
def main():
dice_rolls = int(input('How many dice would you like to roll? '))
dice_size = int(input('How many sides are the dice? '))
dice_sum = 0
for i in range(0, dice_rolls): # for every Index in this range, do this:
roll = random.randint(1,dice_size) # the random.randint function takes 2 integers as parameters, with the beginning and end included in the range.
dice_sum += roll # this is the same as dice_sum = dice_sum + roll
if roll == 1:
print(f'You rolled a {roll}! Critical Fail!')
elif roll == dice_size:
print(f'You rolled a {roll}! Critical Success!')
else:
print(f'You rolled a {roll}')
print(f'You have rolled a total of {dice_sum}')
if __name__== "__main__": # this is an if statement that calls the function main, which will run whenever you run the Python script.
main() | true |
368cf1d3c85fe5a6cdad6b15036627fb17f3bd6e | Faiax/Python_Basics | /dictionaries.py | 954 | 4.125 | 4 | fruit = {"orange":"a sweet orange citrus fruit",
"apple":"good for making cider",
"lemon":"a sour yellow citrus fruit",
"grape":"a small sweet fruit growing in brunches",
"lime":"a sour green citrus fruit",
"banana":"long yellow tasty things"}
print(fruit)
#ordered_keys = list(fruit.keys())
#ordered_keys.sort()
#ordered_keys = sorted(list(fruit.keys()))
#for f in ordered_keys:
# print(f + "_" + fruit[f])
#for f in sorted(fruit.key(())):
#for f in fruit:
# print(f + "_" + fruit[f])
#
#for val in fruit.values():
# print(val)
#
#print("__"*50)
#
#for key in fruit:
# print(fruit[key])
#fruit_keys =fruit.keys()
#print(fruit_keys)
#
#fruit["tomato"] = "not good with ice cream "
#print(fruit_keys)
print(fruit)
print(fruit.items())
f_tuple = tuple(fruit.items())
print(f_tuple)
for snacks in f_tuple:
item, description = snacks
print(item + " is " + description)
print(dict(f_tuple)) | true |
27b480f773db0209aca8871b367e96c1c2a8fefe | S-web7272/tanu_sri_pro | /strings/creating_string.py | 844 | 4.15625 | 4 | # for creating a single line string value
name = "Abraham "
bookname = "An Ancient Journey"
# for creating multi line string value
author_info = '''Most of us wonder if there is a God
and if He really is the God of the Bible.
In the Bible God says ‘I will make your name great’
and today the name of Abraham/Abram is known worldwide.
'''
bookinfo = """A look at Israel’s history in the book of Genesis in
the Bible reveals that 4000 years ago a man, who is now very well known,
went on a camping trip in that part of the world. The Bible says that his story affects our future.
A look at Israel’s history in the book of Genesis in the Bible reveals that 4000 years ago a man,
who is now very well known, went on a camping trip in that part of the world.
"""
print(name)
print(author_info)
print(bookname)
print(bookinfo) | true |
a392c805c1a02400e0d31a6b34a2d4065ba12785 | DX9807/General-Practice-Code | /datetime1.py | 809 | 4.125 | 4 | from datetime import datetime
now = datetime.now()
mm = str(now.month)
dd = str(now.day)
yyyy = str(now.year)
hour = str(now.hour)
mi = str(now.minute)
ss = str(now.second)
print (mm + "/" + dd + "/" + yyyy + " " + hour + ":" + mi + ":" + ss)
now = datetime.now()
print()
print("Current date and time using str method of datetime object:")
print(str(now))
print()
print("Current date and time using instance attributes:")
print("Current year: %d" % now.year)
print("Current month: %d" % now.month)
print("Current day: %d" % now.day)
print("Current hour: %d" % now.hour)
print("Current minute: %d" % now.minute)
print("Current second: %d" % now.second)
print("Current microsecond: %d" % now.microsecond)
print()
print("Current date and time using strftime:")
print(now.strftime("%Y-%m-%d %H:%M")) | false |
c6e39018e2f32eda3bc2df390274b9473b4e9891 | daviddumas/mcs275spring2021 | /samplecode/debugging/puzzle2/biggest_number.py | 2,117 | 4.125 | 4 | """Debugging puzzle: Script to find largest integer in a
text file (allowing Python int literal syntax for hexadecimal,
binary, etc.)"""
# MCS 275 Spring 2021 Lecture 11
# This script is written in a way that avoids some constructions
# that would make the code more concise (e.g. list comprehensions).
# This gives more lines of code to step through during debugging.
import sys
punctuation = ".,;:-'\""
def line_words(s):
"""Break a line of text into words"""
# Replace punctuation with whitespace
for c in punctuation:
s = s.replace(c," ")
return s.split()
def is_bin_digit(c):
"""Check whether character c is a binary digit"""
return c in "01"
def is_hex_digit(c):
"""Check whether character c is a hexadecimal digit"""
return c in "0123456789abcdefABCDEF"
def is_octal_digit(c):
"""Check whether character c is an octal digit"""
return c in "01234567"
def looks_like_integer(w):
"""Does string w look like an integer literal?"""
if w.isdigit():
return True
if w[:2] == "0x":
return all( [is_hex_digit(c) for c in w[2:]] )
if w[:2] == "0b":
return all( [is_bin_digit(c) for c in w[2:]] )
if w[:2] == "0o":
return all( [is_octal_digit(c) for c in w[2:]] )
return False
def to_integer(w):
"""Convert a string to an integer, allowing binary, hex, and octal"""
if w.isdigit():
return int(w)
if w[:2] == "0x":
return hex(w)
if w[:2] == "0b":
return bin(w)
if w[:2] == "0o":
return oct(w)
def line_integers(s):
"""Find integer literals on a line and return a list of
corresponding integers"""
words = line_words(s)
integers = []
for w in words:
if looks_like_integer(w):
integers.append(to_integer(w))
return integers
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Exactly one argument required: input filename")
exit(1)
values = []
with open(sys.argv[1],"rt") as infile:
for line in infile:
values += line_integers(line)
print(max(values)) | true |
8b14536bc036c4716ac3a321b47bc018f83cdb1f | daviddumas/mcs275spring2021 | /projects/lookup.py | 2,787 | 4.125 | 4 | # MCS 275 Spring 2021 Project 3 Solution
# David Dumas
# Project description:
# https://www.dumas.io/teaching/2021/spring/mcs275/nbview/projects/project3.html
"""
Reads a list of chromaticities and names from the CSV file
(name given as first command line argument) and provides a
lookup service using keyboard input. Each time the user
enters a chromaticity in the format
r g b
the name will be found and printed, or a message will be
shown indicating the chromaticity was not in the CSV file.
Entering a blank line ends the program.
"""
import sys
import csv
from chroma import Chroma, ChromaNameMapping
if len(sys.argv) != 2:
print("ERROR: Required command line argument missing.\n")
print("Usage: {} FILENAME".format(sys.argv[0]))
print("Reads chromaticity dictionary from FILENAME (CSV)")
print("then performs interactive name lookup.")
sys.exit(1)
names = ChromaNameMapping()
with open(sys.argv[1], "rt", newline="") as infile:
rdr = csv.DictReader(infile)
for row in rdr:
components = [int(row[k]) for k in ("red", "green", "blue")]
c = Chroma(*components)
names[c] = row["name"]
# Main command loop: Read a line, parse it, look it up
for line in sys.stdin:
line = line.strip() # ignore leading and trailing whitespace
# blank line? If so, exit the loop (ending the program)
if not line:
break
# Attempt to make a Chromaticity from the values on the input line.
# By converting all of the items on the line into integers and passing them
# to Chroma(), there is a chance of a failure due to non-integer values
# (generating a ValueError at int(x)), values that do not for a chromatcitiy
# (generating a ValueError at Chroma(...)), or the wrong number of values,
# generating a TypeError at Chroma(...).
try:
fields = [int(x) for x in line.split()]
c = Chroma(*fields)
except (ValueError, TypeError):
print("<invalid>")
continue
# Here we use Python's feature where multiple exception types can be caught
# in a single except block by giving a tuple of exception types. This is
# included as a nice demonstration of a code-saving move in cases where
# several exception types need to be handled in the same way. This wasn't
# something we covered in lecture though, so it was expected you would do
# the same thing with e.g.
# except ValueError:
# print("<invalid>")
# continue
# except TypeError:
# print("<invalid>")
# continue
# or by manually checking for the correct number of arguments before calling
# Chroma()
# Find the chromaticity's name
try:
print(names[c])
except KeyError:
print("<not found>")
| true |
a30fa837584e9b52c04c8d75a2489790900f331d | wfgiles/P3FE | /Week 7/Exercise 5..10.1.py | 1,425 | 4.21875 | 4 | ##number = raw_input('Enter number: ')
##num = int(number)
##print num
##
##Write a program which repeatedly reads numbers until the
##user enters "done". Once done is entered, print out the
##total, count and average of the numbers. If the user enters
##anything other than a number, detect the mistake usinf a try
##and except and print the error message and skip to the next
##number.
##
##Enter a number: 4
##Enter a number: 5
##Enter a number: bad data
##Invalid input
##Enter a number: 7
##Enter a number: done
##
##16 3 5.33333333333
##
##CORRECT CODE
##EXERCISE 5.10.1
##
##count = 0
##total = 0
##
##while True:
## inp = raw_input('Enter a number: ')
##
## ##Handle the edge cases
## if inp == 'done':
## print total, count, total/count
## break
## if len(inp) < 1 : break #Check for empty line
##
## try:
## num = float(inp)
## count = count + 1
## total = total + num
## except:
## print 'Invalid input'
## continue
##
##EXERCISE 5.10.2
##
##while True:
## inp = raw_input('Enter a number: ')
##
## ##Handle the edge cases
## if inp == 'done':
## print "Maximum:", max(num)
## print 'Minimum:', min(num)
## break
## if len(inp) < 1 : break #Check for empty line
##
## try:
## num = int(inp)
##
## except:
## print 'Invalid input'
## continue
##
| true |
aeb8a93ddc74b60d01ab138b526cdc1c7d899faa | wfgiles/P3FE | /Week 8 Ch6/Week 6 slide examples.py | 2,101 | 4.21875 | 4 | ##INDEFINITE - WHILE STATEMENT
##
##fruit = 'banana'
##index = 0
##while index < len(fruit):
## letter = fruit[index]
## print index, letter
## index = index + 1
##
##----------------------------
##DEFINITE - FOR STATEMENT
##
##fruit = 'banana'
##for letter in fruit:
## print letter
##
##-------------------------------
##LOOPING AND COUNTING
##
##word = 'banana'
##count = 0
##for letter in word:
## if letter == 'a':
## count = count + 1
##print count
##
##------------------------------
##IN AS LOGICAL OPERATOR
##
##fruit = 'banana'
##'m' in fruit
##
##-----------------------------
##
##STRING COMPARUISON
##
##word = 'banana'
##word = 'airplane'
##word = 'zeplin'
##
##if word == 'banana':
## print 'All right, bananas'
##
##if word < 'banana':
## print 'Your word, ' + word + ', comes before banana.'
##elif word > 'banana':
## print 'Your word, ' + word + ', comes after banana.'
##
##else:
## print 'All right, bananas.'
##greet = 'Hello Bill'
##zap = greet.lower()
##
##print zap
##
##spiz = greet.upper()
##
##print spiz
##
##fer = greet.title()
##
##print fer
##
##up = greet.capitalize()
##
##print up
##stuff = 'Hello World'
##type(stuff)
##-----------------------
##fruit = 'banana'
##pos = fruit.find('na')
##print pos
##greet = 'Hello Bob'
##print greet
##nstr = greet.replace('Bob', 'Jane')
##print nstr
##xstr = greet.replace('B', 'X')
##print xstr
##greet = ' Hello Bob '
##print greet.lstrip()
##print greet.rstrip()
##print greet.strip()
##line = 'Please have a nice day'
##line.startswith('Please')
##--------------------------------------
##Parsing and Extracting
##
##data = 'From stephen.marguard@uct.ac.za Sat Jan 5 09:14:16 2008'
##atpos = data.find('@')
##print atpos
##
##sppos = data.find(' ',atpos)
##print sppos
##
##host = data[atpos+1 : sppos]
##print host
##str = '123'
##print str
##
##print int(str) + 1
text = "X-DSPAM-Confidence: 0.8475";
nbr = text.find('0')
print nbr
trt = text.find('5')
print trt
tyt = text[23:29]
print tyt
tyt = float(tyt)
print tyt
| false |
02dcca5997e80c2d3f6b49f96a3a95b836e5d01e | kermitt/challenges | /py/bouncing_ball.py | 1,820 | 4.34375 | 4 | """
https://www.codewars.com/kata/5544c7a5cb454edb3c000047/train/python
A child is playing with a ball on the nth floor of a tall building. The height of this floor, h, is known.
He drops the ball out of the window. The ball bounces (for example), to two-thirds of its height (a bounce of 0.66).
His mother looks out of a window 1.5 meters from the ground.
How many times will the mother see the ball pass in front of her window (including when it's falling and bouncing?
Three conditions must be met for a valid experiment:
Float parameter "h" in meters must be greater than 0
Float parameter "bounce" must be greater than 0 and less than 1
Float parameter "window" must be less than h.
If all three conditions above are fulfilled, return a positive integer, otherwise return -1.
"""
# if h < 0 or ( bounce <= 0 or bounce >= 1 ) or window > h :
# return -1
# loop = -1
# while h > window and loop < 100:
# #print( "{} H {} % {} w {} ".format( loop, h, bounce, window))
# h *= bounce
# loop += 2
# return loop
def bouncing_ball(h, bounce, window):
if h < 0 or ( bounce <= 0 or bounce >= 1 ) or window > h :
return -1
loop = -1
while h > window and loop < 100:
#print( "{} H {} % {} w {} ".format( loop, h, bounce, window))
h *= bounce
loop += 2
return loop
def testing(h, bounce, window, expected):
actual = bouncing_ball(h, bounce, window)
#Test.assert_equals(actual, exp)
if actual == expected:
print("PASS {} {} ".format( actual, expected))
else:
print("FAIL {} {} ".format( actual, expected))
def tests():
testing(2, 0.5, 1, 1)
testing(3, 0.66, 1.5, 3)
testing(30, 0.66, 1.5, 15)
testing(30, 0.75, 1.5, 21)
tests() | true |
ab96c922d0b0fc454e81188cdd9195956402e578 | truongductri01/Hackerrank_problems_solutions | /Problem_Solving/Data_Structure/Linked_list/Reverse_linked_list.py | 1,519 | 4.21875 | 4 | # Link: https://www.hackerrank.com/challenges/reverse-a-linked-list/problem
class SinglyLinkedListNode:
def __init__(self, node_data):
self.data = node_data
self.next = None
class SinglyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def insert_node(self, node_data):
node = SinglyLinkedListNode(node_data)
if not self.head:
self.head = node
else:
self.tail.next = node
self.tail = node
def reverse(self):
prev = None
current = self.head
while current != None:
temp = current.next
current.next = prev
prev = current
current = temp
self.head = prev
return self.head
# Complete the reverse function below.
#
# For your reference:
#
# SinglyLinkedListNode:
# int data
# SinglyLinkedListNode next
#
#
if __name__ == '__main__':
tests = int(input())
for tests_itr in range(tests):
llist_count = int(input())
llist = SinglyLinkedList()
for _ in range(llist_count):
llist_item = int(input())
llist.insert_node(llist_item)
# current = llist.head
# # print(current)
# while current != None:
# print(current.data)
# current = current.next
llist.reverse()
current = llist.head
while current != None:
print(current.data)
current = current.next
| true |
ca4f516b17d4ba871e9cb61e65e8d392621c5a42 | truongductri01/Hackerrank_problems_solutions | /Problem_Solving/Medium/Almost_Sorted/Almost_Sorted.py | 2,418 | 4.3125 | 4 | # link: https://www.hackerrank.com/challenges/almost-sorted/problem
explanation = ''' Output Format
If the array is already sorted, output yes on the first line. You do not need to output anything else.
If you can sort this array using one single operation (from the two permitted operations)
then output yes on the first line and then:
a. If elements can be swapped, and , output swap l r in the second line.
l and r are the indices of the elements to be swapped, assuming that the array is indexed from l to r.
b. Otherwise, when reversing the segment , output reverse l r in the second line.
l and r are the indices of the first and last elements of the subsequence to be reversed, assuming that the array is indexed from l to r.
represents the sub-sequence of the array, beginning at index and ending at index , both inclusive.
If an array can be sorted by either swapping or reversing, choose swap.
If you cannot sort the array either way, output no on the first line.
'''
# left = index + 1
# right = index (in reverse way) + len(arr) + 1
def almostSorted(arr):
copy_array = arr.copy()
copy_array.sort()
# print(copy_array)
# print(arr)
if arr == copy_array:
print("yes")
else:
count = 0
for i in range(len(copy_array)):
if arr[i] != copy_array[i]:
count += 1
for i in range(len(copy_array)):
if arr[i] != copy_array[i]:
left = i
break
for i in range(-1, -len(copy_array) - 1, -1):
if arr[i] != copy_array[i]:
right = i
break
# print(left, right)
# print(count)
if count == 2:
print("yes")
print("swap", left+1, right+len(copy_array)+1)
else:
# reverse case
sub_array = arr[left:right+len(copy_array)+1]
# print(sub_array)
sub_array.reverse()
# print(sub_array)
if sub_array == copy_array[left:right+len(copy_array)+1]:
print("yes")
print("reverse", left+1, right+len(copy_array)+1)
else: # no case
print("no")
if __name__ == "__main__":
f = open("Input")
number = int(f.readline())
array = list(map(int, f.readline().rstrip().split()))
almostSorted(array)
f.close() | true |
5ac6c88180aef91c17cdcd01f13ce4f58d59575b | Code-Institute-Submissions/battleships-7 | /rock-paper-scissors.py | 1,080 | 4.21875 | 4 | from random import randint
# Options for player to chose
Choices = ["ROCK", "PAPER", "SCISSORS"]
# Computer chosing random move between Rock, Paper or Scissors
while True:
Computer = Choices[randint(0, 2)]
Player = input("Pick Rock, Paper, Or Scissors Or Press X To Quit: \n ").upper()
if Player == "X":
print("Game Ended")
break
elif Player == Computer:
print("Draw!")
elif Player == "ROCK":
if Computer == "PAPER":
print("You Lose HAHA", Computer, "Beats", Player)
else:
print("You Win YAY!!", Player, "Beats", Computer)
elif Player == "PAPER":
if Computer == "SCISSORS":
print("HAHA you lose!", Computer, "Beats", Player)
else:
print("You Win YAY!!", Player, "Beats", Computer)
elif Player == "SCISSORS":
if Computer == "ROCK":
print("You lose HAHA!!", Computer, "Beats", Player)
else:
print("Winner Woo Hoo!", Player, "Beats", Computer)
else:
print("That's not a valid input. Try again")
| false |
b2c4a4dc511a2263f1a9a0df93b5c20893297b78 | KiemNguyen/data-structures-and-algorithms | /coding_challenges/lists/find_second_largest.py | 342 | 4.125 | 4 | # Returns second maximum value from given list
def find_second_largest(arr):
largest = 0
second_largest = 0
for i in range(len(arr)):
if arr[i] > largest:
second_largest = largest
largest = arr[i]
elif arr[i] > second_largest:
second_largest = arr[i]
return second_largest
| false |
aa3893ed9501800385b644fc8ba7945f54962830 | KiemNguyen/data-structures-and-algorithms | /coding_challenges/linked_lists/delete.py | 1,999 | 4.3125 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
# Function to initialize head
def __init__(self):
self.head = Node(-1)
# Function to insert a new node at the beginning
def insert_at_head(self, new_data):
# 2. Create a new node
# 3. Put in the data
new_node = Node(new_data)
# 3. Make next element of the new node to be the next element of the Head:
new_node.next = self.head.next
# 4. Make next element of the Head to be this new node
self.head.next = new_node
return self.head
# Function to print contents of a linked list
def print_list(self):
if self.head.next is None:
print("List is empty")
return False
temp = self.head.next
while temp.next is not None:
print(temp.data, "->", end="")
temp = temp.next
print(temp.data, "-> None")
return True
def delete_list(self, linked_list, value):
deleted = False
if self.head.next is None:
print("List is empty")
return deleted
# Traverse the linked list to find the value to be deleted
current_node = linked_list.head.next
previous_node = None
while current_node is not None:
# Node to be deleted is found
if current_node.data == value:
previous_node.next = current_node.next
deleted = True
break
previous_node = current_node
current_node = current_node.next
if deleted is False:
print("{} is not in the list".format(value))
else:
print("{} is deleted".format(value))
linked_list = LinkedList()
for i in range(1, 10, 1):
linked_list.insert_at_head(i)
linked_list.print_list()
linked_list.delete_list(linked_list, 8)
linked_list.delete_list(linked_list, 21)
linked_list.print_list() | true |
bb75c61df2d363b27703b8c02c6ebbfcf5eba4c1 | aartiaw/Solved_Puzzles | /mul_subarray.py | 903 | 4.15625 | 4 | """Max product subarray same as the Max sum subarray."""
def get_max_product(arr):
"""Function to get maximum product from subarray."""
if arr:
ans = arr[0]
cur_max_product = arr[0]
prev_max_product = arr[0]
prev_min_product = arr[0]
for i in range(1, len(arr)):
cur_max_product = max(arr[i], prev_max_product*arr[i],
prev_min_product*arr[i])
cur_min_product = min(arr[i], prev_max_product*arr[i],
prev_min_product*arr[i])
ans = max(ans, cur_max_product)
prev_max_product = cur_max_product
prev_min_product = cur_min_product
return ans
else:
return 0
if __name__ == "__main__":
arr = [6, -3, -10, 0, 2]
max_product = get_max_product(arr)
print "Maximum product of subarray: ", max_product
| false |
239a5babfec5b5fecb3e9a11f6a168d75fa779b6 | LadislavVasina1/PythonStudy | /ProgramFlow/trueFalse.py | 285 | 4.25 | 4 | day = "Monday"
temperature = 30
raining = True
if (day == "Saturday" and temperature > 27) or not raining:
print("Go swimming.")
else:
print("Learn Python")
name = input("Enter your name: ")
if name:
print(f"Hi, {name}")
else:
print("Are you the man with no name?")
| true |
2b53bc3f72d5ea1528666abe1d9a5e174b17d7c2 | federicociner/leetcode | /graphs/valid_tree.py | 1,690 | 4.15625 | 4 | """Given n nodes labeled from 0 to n-1 and a list of undirected edges (each
edge is a pair of nodes), write a function to check whether these edges make
up a valid tree.
Example 1:
Input: n = 5, and edges = [[0,1], [0,2], [0,3], [1,4]]
Output: true
Example 2:
Input: n = 5, and edges = [[0,1], [1,2], [2,3], [1,3], [1,4]]
Output: false
Note: you can assume that no duplicate edges will appear in edges. Since all
edges are undirected, [0,1] is the same as [1,0] and thus will not appear
together in edges.
"""
from typing import Dict, List
class Solution:
# Time complexity: O(V + E)
# Space complexity: O(V + E)
def validTree(self, n: int, edges: List[List[int]]) -> bool:
visited = [False] * n
count = 0
graph = {node: [] for node in range(n)}
for u, v in edges:
graph[u].append(v)
graph[v].append(u)
for node in range(n):
if not visited[node]:
self.dfs(graph, visited, node)
count += 1
if count == 1 and len(edges) < n:
return True
return False
def dfs(
self, graph: Dict[int, List[int]], visited: List[bool], node: int
) -> None:
if visited[node]:
return
visited[node] = True
for u in graph[node]:
self.dfs(graph, visited, u)
if __name__ == "__main__":
S = Solution()
# Example 1
n = 5
edges = [[0, 1], [0, 2], [0, 3], [1, 4]]
assert S.validTree(n, edges) is True
# Example 1
n = 5
edges = [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]]
assert S.validTree(n, edges) is False
print("All tests passed.")
| true |
cbcfea6a3d9052c030b2dd071269a3506bf1dd54 | federicociner/leetcode | /arrays/find_duplicate_number.py | 1,336 | 4.21875 | 4 | """Given an nums nums containing n + 1 integers where each integer is between
1 and n (inclusive), prove that at least one duplicate number must exist.
Assume that there is only one duplicate number, find the duplicate one.
Example 1:
Input: [1,3,4,2,2]
Output: 2
Example 2:
Input: [3,1,3,4,2]
Output: 3
Note:
- You must not modify the nums (assume the nums is read only).
- You must use only constant, O(1) extra space.
- Your runtime complexity should be less than O(n^2).
- There is only one duplicate number in the nums, but it could be repeated
more than once.
"""
from typing import List
class Solution:
# Time complexity: O(n)
# Space complexity: O(1)
def findDuplicate(self, nums: List[int]) -> int:
if not nums or len(nums) == 1:
return -1
slow = nums[0]
fast = nums[nums[0]]
while slow != fast:
slow = nums[slow]
fast = nums[nums[fast]]
slow = 0
while slow != fast:
slow = nums[slow]
fast = nums[fast]
return slow
if __name__ == "__main__":
s = Solution()
# # Example 1
x = [1, 3, 4, 2, 2]
assert s.findDuplicate(x) == 2
# Example 2
y = [3, 1, 3, 4, 2]
assert s.findDuplicate(y) == 3
print("All tests passed.")
| true |
4f6eb16985300e4634b3788f5493185c2654b606 | federicociner/leetcode | /design_problems/design_max_stack.py | 1,944 | 4.25 | 4 | """Design a max stack that supports push, pop, top, peekMax and popMax.
push(x) -- Push element x onto stack.
pop() -- Remove the element on top of the stack and return it.
top() -- Get the element on the top.
peekMax() -- Retrieve the maximum element in the stack.
popMax() -- Retrieve the maximum element in the stack, and remove it. If you f
ind more than one maximum elements, only remove the top-most one.
Example 1:
MaxStack stack = new MaxStack();
stack.push(5);
stack.push(1);
stack.push(5);
stack.top(); -> 5
stack.popMax(); -> 5
stack.top(); -> 1
stack.peekMax(); -> 5
stack.pop(); -> 1
stack.top(); -> 5
Note:
* -1e7 <= x <= 1e7
* Number of operations won't exceed 10000.
* The last four operations won't be called when stack is empty.
"""
class MaxStack:
# Time complexity: O(1), except popMax() which is O(n)
# Space complexity: O(n)
def __init__(self):
self.stack = []
def push(self, x: int) -> None:
m = max(x, self.stack[-1][1] if self.stack else float("-inf"))
self.stack.append([x, m])
def pop(self) -> int:
return self.stack.pop()[0]
def top(self) -> int:
return self.stack[-1][0]
def peekMax(self) -> int:
return self.stack[-1][1]
def popMax(self) -> int:
m = self.stack[-1][1]
b = []
while self.stack[-1][0] != m:
b.append(self.pop())
self.pop()
for item in reversed(b):
self.push(item)
return m
if __name__ == "__main__":
S = MaxStack()
# Example 1
S.push(5)
S.push(1)
S.push(5)
assert S.top() == 5
assert S.popMax() == 5
assert S.top() == 1
assert S.peekMax() == 5
assert S.pop() == 1
assert S.top() == 5
# Example 2
S = MaxStack()
S.push(5)
S.push(1)
assert S.popMax() == 5
assert S.peekMax() == 1
print("All tests passed.")
| true |
1e287847a48951f62d8fa99795bb792453396603 | federicociner/leetcode | /dynamic_programming/palindromic_substrings.py | 1,247 | 4.21875 | 4 | """Given a string, your task is to count how many palindromic substrings in
this string.
The substrings with different start indexes or end indexes are counted as
different substrings even they consist of same characters.
Example 1:
Input: "abc"
Output: 3
Explanation: Three palindromic strings: "a", "b", "c".
Example 2:
Input: "aaa"
Output: 6
Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
"""
class Solution:
# Time complexity: O(n ^ 2)
# Space complexity: O(n)
def countSubstrings(self, s: str) -> int:
if not s:
return 0
max_count = 0
for i in range(len(s)):
max_count += self.expand(s, i, i)
max_count += self.expand(s, i, i + 1)
return max_count
def expand(self, s: str, left: int, right: int) -> int:
count = 0
while left >= 0 and right < len(s) and s[left] == s[right]:
count += 1
left -= 1
right += 1
return count
if __name__ == "__main__":
S = Solution()
# Example 1
s = "abc"
assert S.countSubstrings(s) == 3
# Example 2
s = "aaa"
assert S.countSubstrings(s) == 6
print("All tests passed.")
| true |
d57d848792e49d6eb6c6667dc1ad1143ad402ceb | gvnn/csv_perimeter_calculator | /perimeter.py | 2,382 | 4.34375 | 4 | #!/usr/bin/env python
import csv
import glob
import os
import sys
def calculate_length(file_name):
"""
read a list of points from a CSV file and print out the length of the perimeter of the shape that is formed by
joining the points in their listed order
"""
fp = open(file_name)
reader = csv.reader(fp)
points = []
for row in reader:
x = try_parse(row[0])
y = try_parse(row[1])
if x is not None and y is not None:
points.append((x, y))
return perimeter(points)
def try_parse(string, fail=None):
try:
return float(string)
except Exception:
return fail
def perimeter(points):
""" returns the length of the perimeter of some shape defined by a list of points """
distances = get_distances(points)
length = 0
for distance in distances:
length = length + distance
return length
def get_distances(points):
""" convert a list of points into a list of distances """
i = 0
distances = []
if len(points) == 1: # single point, no distance
return distances
for i in range(len(points)):
point = points[i]
if len(points) > i + 1:
next_point = points[i + 1]
else:
if len(points) > 2:
next_point = points[0]
else:
next_point = None # 2 point it's a line, only one distance
if next_point is not None:
x0 = point[0]
y0 = point[1]
x1 = next_point[0]
y1 = next_point[1]
point_distance = get_distance(x0, y0, x1, y1)
distances.append(point_distance)
return distances
def get_distance(x1, y1, x2, y2):
""" use pythagorean theorem to find distance between 2 points """
a = x2 - x1
b = y2 - y1
c_2 = a * a + b * b
return c_2 ** .5
if __name__ == "__main__":
if len(sys.argv) > 1:
path = sys.argv[1]
if os.path.isdir(path):
csvfiles = glob.glob("{}/*.csv".format(sys.argv[1]))
for csvfile in csvfiles:
print "{} \t {}".format(csvfile, calculate_length(csvfile))
else:
if os.path.isfile(path):
print calculate_length(path)
else:
print "File not found"
else:
print "Please enter file or folder path" | true |
80f2643b925dded0e7a6723828ddf03887f4fad6 | devilroop/loops-programs | /loops task1.py | 1,714 | 4.21875 | 4 | '''#program1
#check whether a no is prime or not
n=33
for i in range(2,n):
if n%i==0:
print(n,"is not primre number")
break
else:
print(n,"is primre number")
#program2
#check list of prime numbers within a range
a=int(input("starting number:"))
b=int(input("ending number:"))
for num in range(a,b):
for i in range(2,num):
if num%i==0:
break
else:
print(num)'''
#program5
#sum of digits and sum is evev or odd
a=input("first number:")
b=input("second number:")
total=0
for i in (a,b):
total=total+int(i)
print(total)
if total%2==0:
print("even")
else:
print("odd")
'''# program no7
n=[2,3,4,5,6,7,10,4,10,3,5,6,7,7,8,9,1,2,3,4,5]
even=[]
odd=[]
for i in n:
if i%2==0:
even.append(i)
elif i%2!=0:
odd.append(i)
print(even)
print(odd)
if sum(even)==sum(odd):
print("even sum equal to odd sum")
else:
print("even sum not equal to odd sum ")
##program8
#add all positive numbers, negative numbers in a number separately, check whether both are equal or not
n=[2,3,-4,5,6,-7,10,4,-10,3,-5,6,-7,7,8,-9,1,2,3,4,-5]
pve=[]
nve=[]
for i in n:
if i>0:
pve.append(i)
elif i<0:
nve.append(i)
if pve==nve:
print("positive numbers sum equal to negitive sum")
else:
print("positive numbers sum not equal to negitive")
#program11
#factorial of a number
num=6
f=1
for i in range(1,num+1):
f=f*i
print(f)
# #program12
#fibonacci series
num=10
a=0
b=1
if num==1:
print(a)
else:
for i in range(2,num):
c=a+b
a=b
b=c
print(c)'''
| false |
a1e9fb6536c4221f5f58fa3b800550806f0163d9 | MohammadQu/Summer2348 | /Homework1/ZyLab2.19.py | 1,447 | 4.125 | 4 | # Mohammad Qureshi
# PSID 1789301
# LAB 2.19
# PART 1
# INPUT NUMBER OF LEMON, WATER, AND NECTAR CUPS AND SERVINGS
print('Enter amount of lemon juice (in cups):')
lemon = int(input())
print('Enter amount of water (in cups):')
water = int(input())
print('Enter amount of agave nectar (in cups):')
nectar = float(input())
print('How many servings does this make?')
serve = int(input())
print()
# OUTPUT USER INPUT
print('Lemonade ingredients - yields', ('{:.2f}'.format(serve)) , 'servings')
print(('{:.2f}'.format(lemon)), 'cup(s) lemon juice')
print(('{:.2f}'.format(water)), 'cup(s) water')
print(('{:.2f}'.format(nectar)), 'cup(s) agave nectar')
print()
# PART 2
# INPUT SERVING SIZE
print('How many servings would you like to make?')
servings = int(input())
print()
# OUTPUT INGREDIENTS BASED ON SERVING INPUT
print('Lemonade ingredients - yields', ('{:.2f}'.format(servings)) , 'servings')
print(('{:.2f}'.format(servings/3)), 'cup(s) lemon juice')
print(('{:.2f}'.format(servings*2.6666666)), 'cup(s) water')
print(('{:.2f}'.format(servings/2.4)), 'cup(s) agave nectar')
print()
# PART 3
# CONVERT CUPS TO GALLONS
print('Lemonade ingredients - yields', ('{:.2f}'.format(servings)) , 'servings')
print(('{:.2f}'.format((servings/3)/16)), 'gallon(s) lemon juice')
print(('{:.2f}'.format((servings*2.6666666)/16)), 'gallon(s) water')
print(('{:.2f}'.format((servings/2.4)/16)), 'gallon(s) agave nectar')
| true |
d977177bd14dbc7910f183544d23f1e1f4752ee4 | Kallikrates/adv_dsi_lab_2 | /src/features/dates.py | 477 | 4.34375 | 4 | def convert_to_date(df, cols:list):
"""Convert specified columns from a Pandas dataframe into datetime
Parameters
----------
df : pd.DataFrame
Input dataframe
cols : list
List of columns to be converted
Returns
-------
pd.DataFrame
Pandas dataframe with converted columns
"""
import pandas as pd
for col in cols:
if col in df.columns:
df[col] = pd.to_datetime(df[col])
return df | true |
4745c3664cdb74b4a67f3afb2ee126cbae225994 | m-samik/pythontutorial | /itterativeapproach.py | 255 | 4.15625 | 4 | # Itterative Approach for a Function
def factorial_itr(n):
fac=1
for i in range(n):
fac=fac*(i+1)
return fac
number=int(input("Enter the Nunber\n"))
print("factorial of the number using itterative method is :\n",factorial_itr(number))
| true |
9dbb209e95bdadd3f722101dc2915b5242f6e37c | m-samik/pythontutorial | /dictionary.py | 258 | 4.21875 | 4 | #creating a dictionary with words and meanings
d1 ={"Mutable":"Which Changes","Immutable" : "Which doesn't Change","Luminous":"Object with Light","Sonorous" : "Sound Producing Utencils"}
print("Enter the word to which you want meaning")
print(d1[input()]) | true |
4ba42df9e051ece562b5d6f9d4b537ad8da1bb28 | vineetpathak/Python-Project2 | /reverse_alternate_k_nodes.py | 965 | 4.21875 | 4 | # -*- coding: UTF-8 -*-
# Program to reverse alternate k nodes in a linked list
import initialize
def reverse_alternate_k_nodes(head, k):
count = 0
prev = None
curr = head
# reverse first k nodes in link list
while count < k and curr:
next = curr.nextnode
curr.nextnode = prev
prev = curr
curr = next
count += 1
# head will point to k node. So next of it will point to the k+1 node
if head:
head.nextnode = curr
# don't want to reverse next k nodes.
count = 0
while count < k-1 and curr:
curr = curr.nextnode
count += 1
# Recursively call the same method if there are more elements in the link list
if curr:
curr.nextnode = reverse_alternate_k_nodes(curr.nextnode, k)
return prev
head = initialize.initialize_linked_list()
head = reverse_alternate_k_nodes(head, 2)
print "After reversing the alternate k nodes in linked list"
while head:
print head.data
head = head.nextnode
| true |
3f86e2b16b0ef7f9fec2f6bac05bf8031dea71fc | vineetpathak/Python-Project2 | /convert_to_sumtree.py | 679 | 4.21875 | 4 | # -*- coding: UTF-8 -*-
# Program to convert tree to sumTree
import binary_tree
def convert_to_SumTree(root):
'''Convert a tree to its sum tree'''
if root is None:
return 0
old_value = root.data
root.data = convert_to_SumTree(root.left) + convert_to_SumTree(root.right)
return root.data + old_value
if __name__ == "__main__":
root = binary_tree.Node(10)
root.left = binary_tree.Node(-2)
root.right = binary_tree.Node(6)
root.left.left = binary_tree.Node(8)
root.left.right = binary_tree.Node(-4)
root.right.left = binary_tree.Node(7)
root.right.right = binary_tree.Node(5)
tree = binary_tree.Tree(root)
convert_to_SumTree(tree.root)
| true |
5438bd96360a3d93a74c37c8f1465864324ebb2a | Lckythr33/CodingDojo | /src/python_stack/python/fundamentals/insertion_sort.py | 571 | 4.15625 | 4 | # Python Insertion Sort
# Function to do insertion sort
def insertionSort(myList):
# Traverse through 1 to len(myList)
for i in range(1, len(myList)):
curr = myList[i]
# Move elements of myList[0..i-1], that are
# greater than curr, to one position ahead
# of their current position
j = i-1
while j >=0 and curr < myList[j] :
myList[j+1] = myList[j]
j -= 1
myList[j+1] = curr
return myList
test = insertionSort([12, 11, 13, 5, 6])
print(test) | true |
71ee0519bec09a2ebc810be3b97b46ef4c1c7263 | profnssorg/tcclucastanussantos | /exercicio 7-3.py | 439 | 4.125 | 4 | primeira = input("Digite a primeira string: ")
segunda = input("Digite a segunda string: ")
terceira = ""
for letra in primeira:
if letra not in segunda and letra not in terceira:
terceira+=letra
for letra in segunda:
if letra not in primeira and letra not in terceira:
terceira+=letra
if terceira == "":
print("Caracteres incomuns não encontrados.")
else:
print("Caracteres incomuns: %s" % terceira)
| false |
f53745c1d0b91273b69fa4c70ad77a53a8837fbf | dannielshalev/py-quiz | /quiz3.py | 1,129 | 4.46875 | 4 | # An anagram is a word obtained by rearranging the letters of another word. For example,
# "rats", "tars", and "star" are anagrams of one another, as are "dictionary" and
# "indicatory". We will call any list of single-word anagrams an anagram group. For
# instance, ["rats", "tars", "star"] is an anagram group, as is ["dictionary"].
# Write a method combine_anagrams(words) that, given a list of string words, groups the
# input words into anagram groups. Case doesn't matter in classifying strings as
# anagrams (but case should be preserved in the output), and the order of the anagrams
# in the groups doesn't matter. The output should be a list of anagram groups (i.e. a
# list of lists).
# Code skeleton:
def combine_anagrams(words):
pass
# Example test case:
input = ['cars', 'for', 'potatoes', 'racs', 'four', 'scar', 'creams', 'scream']
output = [ ["cars", "racs", "scar"],
["four"],
["for"],
["potatoes"],
["creams", "scream"] ]
# Hint: You can quickly tell if two words are anagrams by sorting their letters, keeping
# in mind that upper vs. lowercase doesn't matter.
| true |
c809124aaadfe3ca974ab4a6ce3bd0944fe9182c | Alcatrazee/robot_kinematic | /python code/ABB_Robot.py | 855 | 4.15625 | 4 | # -*- coding: utf-8 -*-
from forward_kinematic import *
from inverse_kinematic import *
import numpy as np
#Before running,you need to make sure you have installed numpy,scipy,matplotlib.
#All you need to do is to alternate the angle of each joint on below
#Set the theta vector to determine the angle of each joint
theta_vector = np.matrix([[np.radians(90),np.radians(50),np.radians(00),np.radians(30),np.radians(40),np.radians(0)]])
#forward result is the posture in SE(3)
forward_result = forward_kinematic(theta_vector)
print('forward result')
print(forward_result)
print('\n')
#use the result of forward kinematic as input to calculate the inverse kinematic
theta_vector_by_inverse = inverse_k(forward_result)
#result is the theta_vector as we input in line6
print('theta vector given:'+str(theta_vector))
forward_kinematic(theta_vector_by_inverse) | true |
2a18b4e470a4f6352cac822144f2a180bd372174 | SACHSTech/ics2o-livehack1-practice-GavinGe3 | /minutes_days.py | 829 | 4.3125 | 4 | """
-------------------------------------------------------------------------------
Name: minutes_days.py
Purpose: Converts given minutes into days, hours and minutes
Author: Ge.G
Created: 08/02.2021
------------------------------------------------------------------------------
"""
print("******Minutes to days, hours, and minutes converter******")
#get number of minutes
numberOfMinutes = float(input("Enter the number of minutes: "))
#convert into number of Days, Hours, and remaining minutes
numberOfDays = numberOfMinutes // 1440
numberOfHours = (numberOfMinutes - numberOfDays * 1440) // 60
numberOfRemainingMinutes = numberOfMinutes % 60
#output number of Days, Hours, and remaining minutes
print(f"\n{numberOfMinutes} minutes = {numberOfDays} days {numberOfHours} Hours and {numberOfRemainingMinutes} minutes") | true |
67393c0a1b38f784e6e035a01363a630622d2ac1 | c4collins/PyTHWay | /ex16.py | 996 | 4.4375 | 4 | from sys import argv
script, filename = argv
print "Opening %r for reading..." % filename
target = open(filename, 'r') # opens the file with the read attribute
print "It currently says:"
print target.read()
print "Closing the file."
target.close() # close the file after reading
print "We're going to erase %r." % filename
print "If you don't want that, hit CTRL-C (^C)."
print "If you do want that, hit Enter."
raw_input("?")
print "Opening %r..." % filename
target = open(filename, 'w') # opens the file with the write attribute, which truncates the file
# print "Truncating the file. Goodbye!"
# target.truncate() # truncate deletes the entire contents of the file.
print "Now I'm going to ask you for three lines."
line1 = raw_input("Line 1: ")
line2 = raw_input("Line 2: ")
line3 = raw_input("Line 3: ")
print "I'm going to write these to the file."
target.write("%s\n%s\n%s" % (line1, line2, line3)) # \n is the newline character
print "And finally we close it."
target.close() | true |
afe44c80b943e1b5f8704ff79f464173897161c3 | akm12k16/Python3-SortingAlgorithm | /insertion_algo1.py | 1,215 | 4.1875 | 4 | # sorting algorithm
# insertion sorting
def insertion_sort(a):
for i in range(1, len(a)):
print("In the i {%s} A : {%s}" % (i, a))
key = a[i]
j = i - 1
print('Before entering in the while j : {%s} , i : {%s} , key : {%s}' % (j, i, key))
while j >= 0 and a[j] > key:
print("In the j {%s} A : {%s}" % (j, a))
a[j + 1] = a[j]
j = j - 1
a[j + 1] = key
# for j in range(i-1, 0):
# print('j for loop', j)
# if a[j] > a[i]:
# print("In the j {%s} i {%s} A : {%s}" % (j, i, a))
# temp = a[j]
# a[j] = a[j+1]
# a[j+1] = temp
# print("In the j {%s} i {%s} A : {%s}" % (j, i, a))
return a
# A = [8.01203212, 7, 6.2, 4.123122, 3-3, 43, 432, -2, 43, 42, 224, 2432, -432.0102, -42.4, -242342, -242342, 24234232,
# 4, 0, 20, 0.0001, 00.2, 00.32, -0.41, 2, 432, 2, -224223423]
# A = [4, 3, 8, 7, 6, 5, 4, 3, 2]
A = [5, 4, 6, 8, 1]
# A = ['KA', 'CB', 'EC', 'EF', 'ALPHA', 'ZOOM', 'D', 'J']
print("UnSorted list : ", A)
insertion_sort(A)
print("Sorted list : ", A)
j = range(len(A), 0)
print(j)
j = range(len(A))
print(j)
| false |
5a0ee3949c55e7899a9fcd1a00bd70af162f108c | PanBohdan/ITEA_Python_Basics | /lesson4/recursive_bubble_sort.py | 616 | 4.40625 | 4 | # Напишите функцию, которая сортирует массив рекурсивно.
def recursive_bubble_sort(numbers):
for i in range(len(numbers) - 1):
if numbers[i] > numbers[i + 1]: # if next number is larger than swap
temp = numbers[i]
numbers[i] = numbers[i + 1]
numbers[i + 1] = temp
recursive_bubble_sort(numbers)
if __name__ == '__main__':
list1 = [1, 2, 25, 4, 3, 26, 100, -2, 55, 155, 10, 7, -1, 5,
2010, 0.5, 24, -3, 555, 67, 2003, 0.59, -1.5, -4, -5]
recursive_bubble_sort(list1)
print(list1)
| false |
063163e2aaa8391cebf5243113bc728354c3e559 | PanBohdan/ITEA_Python_Basics | /lesson2/homework_6(triangle).py | 282 | 4.1875 | 4 | # print triangle with the height of h
def build_triangle(h):
for i in range(h):
rows = [(h - i) * ' ' + i * 2 * '^' + '^']
for i1 in rows:
print(i1)
if __name__ == '__main__':
h1 = int(input('Input height of triangle '))
build_triangle(h1)
| false |
93f075fa8c8f9e7017e74be4e4ce2bceb329b13b | leoswaldo/pythonchallenge | /0.py | 411 | 4.3125 | 4 | #!/python/python3.4/bin/python3
## Function: pow, return a number to a power
# Parameters: base, power
# base: base number to pow
# power: number of pow
def pow(base, power):
result = 1
while(power > 0):
power-=1
result = result * base
return result
if __name__ == '__main__':
print("For next level, go to http://www.pythonchallenge.com/pc/def/%s.html" % pow(2, 38))
| true |
84102b0b9be5ceaafb61a4ba7fa04bdbbb4f455b | hbrown017/Projies | /Python/Turtle Graphics/bubbleSortAnimation.py | 2,928 | 4.25 | 4 | '''
Name: Harry Brown III
Program: Bubble Sort using Turtle
Date: 6/20/16
'''
import turtle
def drawHistogram(t, list):
t.speed(10) #0(fastest), 10(fast), 6(normal), 3 (slow)
t.hideturtle()
height = 100 #histogram height
width = 400 #histogram width
#draw bottom line for histogram
t.up()
t.goto(-width / 2, -height / 2)
t.down()
t.forward(width)
#set bar width
barWidth = width / len(list)
#draw bars
for i in range(len(list)):
h = list[i] * height / max(list)
x = -width/2 + i * barWidth
y = -height/2
drawBar(t, list, i, x, y, barWidth, h)
#t.hideturtle()
def drawBar(t, list, i, x, y, barWidth, h):
t.up()
t.goto(x, y)
t.setheading(90)
t.down()
t.forward(h)
t.write(' ' + str(list[i]), align='left', font=('Arial', 18))
t.right(90)
t.forward(barWidth)
t.right(90)
t.forward(h)
def BubbleSort(t, n):
count = 0
listIt = 0
t.hideturtle()
for x in range(0, len(n)-3):
for y in range(0, len(n)-1):
if n[y] > n[y+1]:
swap(t)
drawHistogram(t, [(n[y]), (n[y+1])]) #display values to be swapped
n[y], n[y+1] = n[y+1], n[y] #swap values
swapping(t)
drawHistogram(t, n)
count += 1
listIt += 1
#show list changes when swapped
swapProcess(t, n, listIt)
return count
def unsorted(t):
t.hideturtle()
t.up()
t.goto(0,200)
t.write('Original list: ', align = 'center', font=('Arial', 30))
def swap(t):
t.reset()
t.hideturtle()
t.color('red')
t.up()
t.goto(0,200)
t.write('Needs Swapping: ', align = 'center', font=('Arial', 30))
def swapping(t):
t.reset()
t.hideturtle()
t.color('red')
t.up()
t.goto(0,200)
t.write('Swapping: ', align = 'center', font=('Arial', 30))
def sortedList(t):
t.hideturtle()
t.color('green')
t.up()
t.goto(0,200)
t.write('Your list is now sorted: ', align = 'center', font=('Arial', 30))
def iterations(t, count):
t.hideturtle()
t.color('green')
t.up()
t.goto(0,-200)
t.write('Total swaps performed: ' + str(count), align = 'center', font=('Arial', 30))
def swapProcess(t, n, it):
t.reset()
t.hideturtle()
t.color('green')
t.up()
t.goto(0,-200)
t.write('Full list iteration: #' + str(it), align = 'center', font=('Arial', 30))
drawHistogram(t, n) #display swaped values
t.reset()
def main():
t = turtle.Turtle()
#list = [32, 23, 45, 34, 4, 90, 23, 25] #create a list of numbers
num = [1,8,-4,2,16,5,13,9,-2,12,6,17,7,19,4,10,3,2,11,14]
unsorted(t)
drawHistogram(t, num)
t.reset()
count = BubbleSort(t, num)
sortedList(t)
drawHistogram(t, num)
iterations(t, count)
main()
| false |
8ede9e26eb72585afb7424bf72cd9e28f5562e68 | haokai-li/ICS3U-Unit3-08-Python-Leap-Year | /leap_year.py | 911 | 4.21875 | 4 | #!/usr/bin/env python3
# Created by: Haokai Li
# Created on: Sept 2021
# This Program calculate leap year
def main():
# This function calculate leap year
# input
user_string = input("Please enter the year: ")
print("")
# process
try:
user_year = int(user_string)
if user_year % 400 != 0:
if user_year % 100 != 0:
if user_year % 4 != 0:
# output
print("It is a common year.")
else:
# output
print("It is a leap year.")
else:
# output
print("It is a common year.")
else:
# output
print("It is a leap year.")
except Exception:
# output
print("{} is not a valid input.".format(user_string))
print("\nDone.")
if __name__ == "__main__":
main()
| true |
16806de0e4ca649c6ed4dd2480ff7a1ea0aefc0b | thiagorangeldasilva/Exercicios-de-Python | /pythonBrasil/03.Estrutura de Repetição/30. panificadora 0.18.py | 791 | 4.15625 | 4 | #coding: utf-8
"""
O Sr. Manoel Joaquim acaba de adquirir uma panificadora e pretende
implantar a metodologia da tabelinha, que já é um sucesso na sua
loja de 1,99. Você foi contratado para desenvolver o programa que
monta a tabela de preços de pães, de 1 até 50 pães, a partir do
preço do pão informado pelo usuário, conforme o exemplo abaixo:
Preço do pão: R$ 0.18
Panificadora Pão de Ontem - Tabela de preços
1 - R$ 0.18
2 - R$ 0.36
...
50 - R$ 9.00
"""
x = 1
c = 1
pr = []
print(" Panificadora - Tabela de preços")
print()
while x <= 50:
p = x * 0.18
pr.append(p)
print(" ", str(x), f" - R$ {p:.2f}", end='')
if c == 5:
print()
c = 0
x += 1
c +=1
print()
i = int(input(" Informe de pães comprados: "))
print(f" Preço total: R$ {pr[i-1]:.2f}")
input() | false |
1d8ed81948c23dc4a2d610864a0f9989e96ac814 | thiagorangeldasilva/Exercicios-de-Python | /pythonBrasil/04. Listas/17. competição de salto.py | 2,327 | 4.1875 | 4 | #coding: utf-8
"""
Em uma competição de salto em distância cada atleta tem direito
a cinco saltos. O resultado do atleta será determinado pela média
dos cinco valores restantes. Você deve fazer um programa que receba
o nome e as cinco distâncias alcançadas pelo atleta em seus saltos
e depois informe o nome, os saltos e a média dos saltos. O programa
deve ser encerrado quando não for informado o nome do atleta. A saída
do programa deve ser conforme o exemplo abaixo:
Atleta: Rodrigo Curvêllo
Primeiro Salto: 6.5 m
Segundo Salto: 6.1 m
Terceiro Salto: 6.2 m
Quarto Salto: 5.4 m
Quinto Salto: 5.3 m
Resultado final:
Atleta: Rodrigo Curvêllo
Saltos: 6.5 - 6.1 - 6.2 - 5.4 - 5.3
Média dos saltos: 5.9 m
"""
def tratarErroNome(nome):
if nome != "":
nome = nome.replace(" ","")
if nome.isalpha() == True:
return 1
else:
return 2
else:
return 0
def tratarErroIntFloat(numero):
if numero != "":
if numero.isalpha() == False and numero.isalnum() == False:
return 1
elif numero.isdigit() == True:
return 2
else:
return 0
else:
return 0
def trasnformar(tratar, numero):
if tratar == 1:
return float(numero)
elif tratar == 2:
return int(numero)
cond = True
salto = ["Primeiro", "Segundo", "Terceiro", "Quarto", "Quinto"]
distancia = []
while cond:
x = 1
while cond:
nome = input("Informe o nome do atleta: ")
if tratarErroNome(nome) == 1:
break
elif tratarErroNome(nome) == 2:
print("Informar um nome válido")
elif tratarErroNome(nome) == 0:
x = 0
break
if x == 0:
break
print()
while x <= 5:
nota = input("Informe a " + str(x) + "ª nota: ")
if tratarErroIntFloat(nota) == 1 or tratarErroIntFloat(nota) == 2:
nota = trasnformar(tratarErroIntFloat(nota), nota)
if nota > 0:
distancia.append(nota)
x += 1
else:
print("Informe um valor válido.")
else:
print("Informe um valor válido.")
media = sum(distancia)/len(distancia)
print()
print("Atleta:", nome)
for i in range(len(distancia)):
print(salto[i], f"Salto: {distancia[i]:.1f} m")
print()
print("Resultado Final:")
print("Atleta:", nome)
print("Saltos: ", end="")
for i in range(len(distancia)):
if i == (len(distancia)-1):
print(f"{distancia[i]:.1f}")
else:
print(f"{distancia[i]:.1f} - ", end="")
print(f"Média dos Saltos: {media:.1f} m")
print()
input() | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.