blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
3f4bd06b351d2648897dace833ec3bc0d918ed78 | heitorchang/learn-code | /levelup/2018_jan/python/strings/capitalize.py | 1,065 | 4.40625 | 4 | """
You are asked to ensure that the first and last names of people begin with a capital letter in their passports. For example, alison heck should be capitalised correctly as Alison Heck.
Given a full name, your task is to capitalize the name appropriately.
Input Format
A single line of input containing the full name, .
Constraints
The string consists of alphanumeric characters and spaces.
Note: in a word only the first character is capitalized. Example 12abc when capitalized remains 12abc.
Output Format
Print the capitalized string, .
Sample Input
chris alan
Sample Output
Chris Alan
"""
def capitalize(string):
# must keep whitespace intact
# str.title() does not work because 12abc becomes 12Abc
result = ""
last_is_space = True
for c in string:
if last_is_space and c.isalpha():
result += c.upper()
last_is_space = False
else:
if c.isspace():
last_is_space = True
else:
last_is_space = False
result += c
return result
| true |
0bf652acd1c8b074907b103a7ba56b711c395629 | heitorchang/learn-code | /levelup/2018_jun/cracking_the_coding_interview/algorithms/sorting_comparator.py | 1,374 | 4.375 | 4 | description = """
Comparators are used to compare two objects. In this challenge, you'll create a comparator and use it to sort an array. The Player class is provided in the editor below. It has two fields:
name: a string.
string: an integer.
Given an array of Player objects, write a comparator that sorts them in order of decreasing score. If 2 or more players have the same score, sort those players alphabetically ascending by name. To do this, you must create a Checker class that implements the Comparator interface, then write an int compare(Player a, Player b) method implementing the Comparator.compare(T o1, T o2) method. In short, when sorting in ascending order, a comparator function returns -1 if a < b, 0 if a == b, and 1 if a > b.
"""
from functools import cmp_to_key
class Player:
def __init__(self, name, score):
self.name = name
self.score = score
def __repr__(self):
return self.name
def comparator(a, b):
if a.score == b.score:
return -1 if a.name < b.name else 1
return -1 if a.score > b.score else 1
n = int(input())
data = []
for i in range(n):
name, score = input().split()
score = int(score)
player = Player(name, score)
data.append(player)
data = sorted(data, key=cmp_to_key(Player.comparator))
for i in data:
print(i.name, i.score)
| true |
b64effbc38c63c220de4452f6e989317c8c77a46 | heitorchang/learn-code | /levelup/2018_jan/python/basic_data_types/nested_lists.py | 1,277 | 4.1875 | 4 | """
Given the names and grades for each student in a Physics class of N 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, N, the number of students.
The 2N subsequent lines describe each student over 2 lines; the first line contains a student's name, and the second line contains their grade.
Constraints
2 <= N <= 5
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.
"""
from operator import itemgetter
if __name__ == '__main__':
students = []
scores = set()
for _ in range(int(input())):
name = input()
score = float(input())
scores.add(score)
students.append([name, score])
students.sort(key=itemgetter(1, 0))
# get second lowest score
second_lowest = sorted(scores)[1]
for st in students:
if st[1] == second_lowest:
print(st[0])
| true |
2fa2c182f8624667b86cbd19b6d96d6289580e30 | heitorchang/learn-code | /levelup/2018_jan/python/print_without_methods.py | 352 | 4.3125 | 4 | """
Read an integer .
Without using any string methods, try to print the following:
Note that "" represents the values in between.
Input Format
The first line contains an integer .
Output Format
Output the answer as explained in the task.
"""
if __name__ == "__main__":
N = int(input())
for i in range(1, N+1):
print(i, end="")
| true |
4d06c9f7e33f901e6babc191ff8e888596931ff0 | heitorchang/learn-code | /levelup/2018_jun/cracking_the_coding_interview/data_structures/heaps_find_running_median.py | 1,251 | 4.28125 | 4 | description = """
The median of a dataset of integers is the midpoint value of the dataset for which an equal number of integers are less than and greater than the value. To find the median, you must first sort your dataset of integers in non-decreasing order, then:
If your dataset contains an odd number of elements, the median is the middle element of the sorted sample. In the sorted dataset [1,2,3], 2 is the median.
If your dataset contains an even number of elements, the median is the average of the two middle elements of the sorted sample. In the sorted dataset [1,2,3,4], 2.5 is the median.
Given an input stream of integers, you must perform the following task for each integer:
Add the integer to a running list of integers.
Find the median of the updated list (i.e., for the first element through the element).
Print the list's updated median on a new line. The printed value must be a double-precision number scaled to 1 decimal place (i.e., 12.3 format).
"""
from bisect import insort
def runningMedian(lst, val):
insort(lst, val)
len_lst = len(lst)
if len_lst % 2 == 1:
median = lst[len_lst // 2]
else:
median = (lst[len_lst // 2] + lst[len_lst // 2 - 1]) / 2
return format(median, ".1f")
| true |
3f7f9d3b06c08daf3d976be7d8c81d278baef899 | heitorchang/learn-code | /battles/filomenafirmeza/digits/digitDegree.py | 682 | 4.4375 | 4 | description = """
Let's define digit degree of some positive integer as the number of times we need to replace this number with the sum of its digits until we get to a one digit number.
Given an integer, find its digit degree.
Example
For n = 5, the output should be
digitDegree(n) = 0;
For n = 100, the output should be
digitDegree(n) = 1.
1 + 0 + 0 = 1.
For n = 91, the output should be
digitDegree(n) = 2.
9 + 1 = 10 -> 1 + 0 = 1.
"""
def digitDegree(n):
times = 0
while len(str(n)) > 1:
n = sum(map(int, str(n)))
times += 1
return times
def test():
testeql(digitDegree(6), 0)
testeql(digitDegree(100), 1)
testeql(digitDegree(99), 2)
| true |
ecb7f05fe7a102ec0cdaa7fd7c33981af99a5229 | heitorchang/learn-code | /levelup/2018_jun/cracking_the_coding_interview/techniques_concepts/time_complexity_primality.py | 826 | 4.25 | 4 | description = """
A prime is a natural number greater than 1 that has no positive divisors other than and itself. Given integers, determine the primality of each integer and print whether it is Prime or Not prime on a new line.
Note: If possible, try to come up with an O(sqrt(n)) primality algorithm, or see what sort of optimizations you can come up with for an O(n) algorithm. Be sure to check out the Editorial after submitting your code!
"""
import math
def isprime(n):
if n < 2:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3, math.floor(math.sqrt(n)) + 1, 2):
if n % i == 0:
return False
return True
def test():
testeql(isprime(22), False)
testeql(isprime(29), True)
testeql(isprime(2), True)
| true |
4b445c22c4dc23bd3c55c66fbc377a3fe32894e3 | heitorchang/learn-code | /levelup/2018_jan/python/loops.py | 392 | 4.15625 | 4 | """
Task
Read an integer N. For all non-negative integers i < N, print i^2. See the sample for details.
Input Format
The first and only line contains the integer, N
Output Format
Print N lines, one corresponding to each i.
"""
def main(N):
for i in range(N):
print(i ** 2)
if __name__ == "__main__":
N = int(input())
main(N)
def test():
testeql(main(4), None)
| true |
bb60b2b78bd351588a1d2031790527f73d126ef9 | heitorchang/learn-code | /battles/challenges/created/turtlePolygon.py | 1,301 | 4.6875 | 5 | description = """
[Turtle graphics in Python is a popular way for introducing programming to kids.](https://docs.python.org/3.7/library/turtle.html)
Your granddaughter wants to show you how cool her latest drawing is, and to drive the point home of how powerful programs can be, you will tell her how many sides her polygon has, *without even looking at her screen*.
Of course, this will have to be done with a program that interprets the given Python Turtle script.
Assume that the following import is done at startup prior to running your granddaughter's script:
```
from turtle import fd, lt, rt
```
The turtle starts at the center of the graphics window, pointing to the right.
`fd` is `forward`, moving the given number of pixels in its current direction. `lt` turns the turtle left (counterclockwise) the given number of degrees, and `rt` turns it to the right (clockwise).
"""
import sys
from turtle import fd, lt, rt
if __name__ == "__main__":
filename = sys.argv[1]
print("[", end="")
cmds = []
with open(filename) as f:
for line in f:
line = line.strip()
eval(line)
cmds.append('"' + line + '"')
print(",".join(cmds), end="")
print("]")
dummy = input("Press Enter to quit.")
| true |
4940f9edcbd1dbb565378631d0729614e5df231c | heitorchang/learn-code | /battles/skilltest/composeExpression.py | 1,072 | 4.125 | 4 | description = """
Given a string that contains only digits 0-9 and a target value, return all expressions that are created by adding some binary operators (+, -, or *) between the digits so they evaluate to the target value. In some cases there may not be any binary operators that will create valid expressions, in which case the function should return an empty array. The numbers in the new expressions should not contain leading zeros.
The function should return all valid expressions that evaluate to target, sorted lexicographically.
Example
For digits = "123" and target = 6, the output should be
composeExpression(digits, target) = ["1*2*3", "1+2+3"].
Input/Output
[time limit] 4000ms (py3)
[input] string digits
Guaranteed constraints:
2 ≤ digits.length ≤ 10.
[input] integer target
Guaranteed constraints:
-104 ≤ target ≤ 104.
[output] array.string
"""
def composeExpression(digits, target):
pass
def test():
testeql(composeExpression("5000060000", -10000), ["50000-60000"])
testeql(composeExpression("123", 6), ["1*2*3", "1+2+3"])
| true |
6e0ebc3c099d60a95e5dea9565eae8bd4788032f | manuaatitya/computer_graphics | /basic_programs/point_inside_triangle.py | 2,617 | 4.3125 | 4 | # Point class to store the x and y values of the coordinates
class Point:
def __init__(self,x,y):
self.x = x
self.y = y
# Man class to check if the point intersects the triangle
class point_within_triangle:
# Initiaization function
def __init__(self):
self.triangle = []
self.intersecting_edge = 0
print('Python program to test if a Point is within a triangle')
# Get the Point data as input data from the user
def get_input_point(self):
x,y = map(float,input('Enter the x and y cordinates of the Point P to be tested ').split())
self.point = Point(x,y)
# Get the triangle coordinates as input data from the user
def get_input_triangle(self):
for i in range(3):
x,y = map(float,input('Enter the x and y cordinates of the Point {} of the triangle '.format(i+1)).split())
self.triangle.append(Point(x,y))
# Compute a vector from the given points
def compute_vector(self, point1, point2):
return Point(point2.x - point1.x, point2.y - point1.y)
# Function to compute the cross product between 2 vectors in 2D
def cross_product(self, point1, point2):
return point1.x * point2.y - point1.y * point2.x
# Function to check if point exists within or intersects the triangle
def compute_cross_product(self):
positive = 0
negative = 0
zeros = 0
for i in range(3):
temp = self.cross_product(self.compute_vector(self.point, self.triangle[i]), self.compute_vector(self.point, self.triangle[(i+1) % 3]))
if(temp > 0):
positive = positive + 1
elif(temp < 0):
negative = negative + 1
else:
zeros = zeros + 1
self.intersecting_edge = i
if(positive == 3 or negative == 3 or zeros == 3):
self.point_within_triangle = True
self.point_intersects_triangle = False
elif((positive + zeros) == 3 or (negative + zeros) == 3):
self.point_within_triangle = False
self.point_intersects_triangle = True
else:
self.point_intersects_triangle = False
self.point_within_triangle = False
def debug(self):
# Printing the given point
print('The given point is {} {}'.format(self.point.x, self.point.y))
# Printing the given triangle points
for i in range(3):
print('The entered cordinates of the point {} in the triangle is {} {}'.format(i+1, self.triangle[i].x, self.triangle[i].y))
| true |
8abb924021478855a6be358ee4c365a526f2de99 | suyeon-yang/CP1404practicals | /prac_05/word_occurences.py | 391 | 4.15625 | 4 |
words_to_counts = {}
input_text = input("Enter a string: ")
words = input_text.split()
for word in words:
word_count = (words_to_counts.get(word, 0))
words_to_counts[word] = word_count + 1
words = list(words_to_counts.keys())
words.sort()
max_length = max((len(word) for word in words))
for word in words:
print("{:{}} : {}".format(word, max_length, words_to_counts[word]))
| true |
4bcbf7cdaa169e10bef34c3fb387012b0e3075ca | somaliren/dhambaal | /Resources/classes_1.py | 2,262 | 4.21875 | 4 | # Attributes : are normal variables defined inside a class
# Method: a function in a class
# Property and attributes are same sometimes
from datetime import datetime
class Foo:
pass
class Employee:
raise_up = 1.05
def __init__(self,first_name,last_name,company,pay):
self.first_name = first_name
self.last_name = last_name
self.company = company
self.pay = pay
def __repr__(self):
return f'{self.first_name} {self.last_name} {self.company} {self.pay}'
# def email(self):
# return f'{self.first_name}.{self.last_name}@{self.company}.com'
@property
def email(self):
return f'{self.first_name}.{self.last_name}@{self.company}.com'
def yearly_raise(self):
self.pay = int(self.pay*self.raise_up)
@staticmethod
def is_work_day(day):
if day.lower() == 'thursday' or day.lower() == 'friday':
print("Enjoy your weekend")
else:
print("Keep working")
@staticmethod
def is_work_day(day):
if day.lower() == 'thursday' or day.lower() == 'friday':
return ("Enjoy your weekend")
return ("Keep working")
@classmethod
def class_method_example(cls):
print( "This is a class method")
# Employee.class_method_example()
employee1 = Employee('Ali','Abdi','SomaliREN',500)
employee2 = Employee('Ahmed','Abdi','SomaliREN',500)
# print(employee1)
# print(employee2)
# # print(employee2.email())
# print(employee2.email)
# employee2.is_work_day('Friday')
class Developer(Employee):
def __init__(self,first_name,last_name,company,pay,pl):
super().__init__(first_name,last_name,company,pay)
self.pl = pl
# Method overflow
# def call():
# pass
# def call(var):
# pass
# def call(var1,var2):
# pass
def __repr__(self):
return f"{self.first_name} {self.last_name} {self.company} {self.pay} {self.pl}"
class Manager(Employee):
raise_up = 3.5
dev1 = Developer("Ali","Hassan",'Somaliren',600,'Python')
dev1.yearly_raise()
m1 = Manager("Ali","Hassan",'Somaliren',600)
m1.yearly_raise()
print(dev1)
print(m1)
# today = datetime.today()
# print(today)
| true |
ff1db10550bd2665a852146f61608ec1a947effb | pwollinger/simple-codes-py | /fibonacci.py | 1,046 | 4.15625 | 4 | #Fibonacci - Code solution to the fibonacci sequence. Here we have two ways to solve this problem, using recursion and using memoization.
#Fibonacci with recurtion is a elegant way to solve fibonacci because the compact code, but the code cost a lot. Because in this solution we create a binary tree for every recursion we use. Because of that, the Big O notation for this code is O(2^number)
def fibo(number):
if number < 3:
return 1
return fibo(number-1) + fibo(number-2)
#Fibonacci with memoization is a better solution than the normal recursive code because we store the result of a node in the binary tree create for the recursive function so that we can check the already processed result inside the dictionary we create to save those numbers we will use in another node. THe Big O notation for this code is O(n)
def fibo_memo(number, memo = {}):
if number in memo:
return memo[number]
if number < 3:
return 1
memo[number] = fibo(number-1, memo) + fibo(number-2, memo)
return memo[number] | true |
64de6b52503271943145b9ced58a13bc01020b40 | Anirudhk94/Algorithms-Python | /PeakFinder2D.py | 587 | 4.125 | 4 | #!/usr/bin/python
def peak2d(array):
'''This function finds the peak in a 2D array by the
recursive method.
Complexity: O(n log m)'''
n = len(array)
m = len(array[0])
j = m // 2
row = [i[j] for i in array]
i = row.index(max(row))
print(i, j)
if j > 0 and array[i][j] < array[i][j - 1]:
return peak2d([row[:j] for row in array])
elif j < m - 1 and array[i][j] < array[i][j + 1]:
return peak2d([row[j:] for row in array])
else:
return array[i][j]
print(peak2d([[1, -1, 3], [1, 5, 6], [-8, 3, 9]]))
| true |
283c245b925be54f4e23866029890e2135185415 | Jhayes007/Python-code | /program8-17.py | 2,094 | 4.5 | 4 | # Filename: Program8-17.py
# Author: J.Hayes
# Date: Nov. 18, 2019
# Purpose: To demonstrate the use of two-dimensional arrays.
# On pages 396-397, this is an example of referencing 2D arrays.
# we will read sales data for three divisions and 4 quarters
# for a company. As in the text we will find the overall total
# for the sales of the company. In addition, we will find the
# overall sales for each division (totaling rows)
# and also for each quarter (totaling columns). We will use
# rows for divisions and columns for quarters.
DIVS = 3
QTRS = 4
# A 2D array with all elements intialized to zero.
sales = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
# Accumulator for overall total
total = 0
# Display instructions
print("This program calculates the company's total sales.")
print('Enter the quarterly sales amounts for each division')
print('when prompted.')
# Nested loops to fill the array with quarterly sales amount
# for each division.
for row in range(DIVS):
for col in range(QTRS):
print('Division ', row+1, ' quarter ', col+1, ': ', end='')
sales[row][col] = float(input())
print() # A blank line
# The loop to compute the totals for each division
# This will be done by calculating row totals
rtotals = [0] * DIVS # 1D array to hold row totals
for row in range(DIVS):
for col in range(QTRS):
rtotals[row] += sales[row][col]
print('Totals for the Divisions: ', rtotals)
# The loop to compute totals for each quarter
# This will be done by calculating column totals
ctotals = [0] * QTRS # 1D array to hold column totals
for row in range(DIVS):
for col in range(QTRS):
ctotals[col] += sales[row][col]
print('Totals for the quarters: ', ctotals)
# Nested loops to add all the elements of the 2D array.
for row in range (DIVS):
for col in range(QTRS):
total += sales[row][col]
# Display the total sales for the organization
print('The total company sales are: ${:,.2f}'.format(total))
| true |
32ea610271d9a87f003c4999fe737d2c6a67dab5 | Jhayes007/Python-code | /Program8-3.py | 728 | 4.25 | 4 | # Filename: Program8-3.py
# Author: J.Hayes
# Date: Nov. 6, 2019
# Purpose: To demonstrate the use of arrays. In python there
# are no true arrays as in traditional languages.
# We will use lists to simulate arrays.
# This script is based on Program 8-3 on page 356.
# Constant for array size
SIZE = 3
# Declare the array
hours = [0] * SIZE
# Read values into the array
for index in range(SIZE):
print('Enter the hours worked by ', end='')
print('Employee number ', index+1, ': ', end='')
hours[index] = int(input())
# Display the elements of the array
print('The hours you entered are: ')
for index in range(SIZE):
print(hours[index], ' ', end='')
| true |
c4bc5a831884329cd06a93901961e96ffef3c5ae | Jhayes007/Python-code | /program6-4.py | 553 | 4.21875 | 4 | # Filename: program6-4.py
# Author: J.Hayes
# Date: Oct. 21, 2019
# Purpose: To demonstrate the use and functioning
# of random functions.
# This script is based on figure 6-5. Rolling dice
import random
# The loop control variable
again = 'y'
# Simulate the die roll
while (again == 'y' or again == 'y'):
print('Rolling the dice...')
print('Their values are: ')
print(random.randint(1, 6))
print(random.randint(1, 6))
# Do another roll of dice?
again = input('Roll them again? (y = yes): ')
| true |
e990f8464f227a6e6b8c7e580b8550185c7bca3c | Jhayes007/Python-code | /program8-16.py | 749 | 4.53125 | 5 | # Filename: Program8-16.py
# Author: J.Hayes
# Date: Nov. 18, 2019
# Purpose: To demonstrate the use of two-dimensional arrays.
# On page 392, this is an example of referencing 2D arrays.
# Constants for rows and columns
ROWS = 3
COLS = 4
# Creating a 2D array with 3 rows and 4 columns in Python
Values = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
# Read values into the array
for row in range(ROWS):
for col in range(COLS):
Values[row][col] = int(input('Enter an integer: '))
# End of the nested for loops
# Display the values in the array
print('Here are the values held in the array: ')
for row in range(ROWS):
for col in range(COLS):
print(Values[row][col])
# end of nested loops
| true |
6e5de3527e8bd76c970f5db7b8d75b41772e8df9 | Jhayes007/Python-code | /SpeedViolation.py | 1,849 | 4.75 | 5 | # Filename: SpeedingViolation.py
# Author: J.Hayes
# Date: November, 4 2019
# Purpose: To demonstrate the use and functioning
# of a validation loop
# This script is the solution to exercise 4 @ the end of chap 7.
# In this exercise the user inputs the speed limit on a
# a road and the driving speed of a driver and check if the
# driving speed is greater than the limit. If so, display
# how much over the limit the speed is.
# The getLimit() function
def getLimit(minSpeed, maxSpeed):
# Enter the speed limit
inputAmount = int(input("Enter the speed limit: "))
# Validate the limit
while (inputAmount < minSpeed or inputAmount > maxSpeed):
print('Limit must be between ', minSpeed, ' and ', \
maxSpeed)
inputAmount = int(input('Enter a valid quanity: '))
return inputAmount
# The getDrive() function
def getDrive(limitSpeed):
# Enter the drive's speed
inputAmount = int(input('Enter the speed of the driver: '))
# Validation loop
while (inputAmount <= limitSpeed):
print('Speeding must be over ', limitSpeed, '!')
inputAmount = int(input('Enter a valid quanity: '))
return inputAmount
# The overSpeed() function
def overSpeed(limitSpeed, driveSpeed):
overLimit = driveSpeed - limitSpeed
print('The driver is going ',overLimit, 'MPH over the speed limit!')
return
# The main() module
def main():
# The range for the limit speeds
minSpeed = 20
maxSpeed = 70
# Get the speed limit
limitSpeed = getLimit(minSpeed, maxSpeed)
# Get the driver's speed
driveSpeed = getDrive(limitSpeed)
# Show if speeding
if (driveSpeed > limitSpeed):
overSpeed(limitSpeed, driveSpeed)
return
main()
| true |
50af955328fa14c07ffedfb7b6699e48305ce7e8 | rimkin/lesson1 | /Python_start/Negatives__Zeros_and_Positives.py | 761 | 4.15625 | 4 | #На вход программе подается натуральное число n, а затем n целых чисел. Напишите программу,
#которая сначала выводит все отрицательные числа, затем нули, а затем все положительные числа,
#каждое на отдельной строке. Числа должны быть выведены в том же порядке, в котором они были введены.
less_0 = []
is_0 = []
more_0 =[]
for _ in range(int(input())):
a = int(input())
if a < 0:
less_0.append(a)
elif a == 0:
is_0.append(a)
else:
more_0.append(a)
print(*less_0, *is_0, *more_0, sep='\n') | false |
b584a95267eab66f72168c58ba6147cf876f2130 | ajayravindra/puzzles | /matrix_search.py | 1,057 | 4.3125 | 4 | ##
# description: searches for an element in a matrix
# complexity : worst case of m + n, where m: #rows, n: #cols
##
import sys
M = [
[ 1, 3, 6, 9, 13],
[ 3, 7, 10, 11, 15],
[ 7, 8, 12, 19, 25],
[14, 19, 21, 32, 46],
[51, 53, 64, 76, 81]
]
def print_matrix(matrix):
for row in matrix:
print row
def search_matrix(matrix, num):
row = 0
col = len(matrix[0]) - 1
steps = []
while row < len(matrix) and col >= 0:
steps.append(matrix[row][col])
if num == matrix[row][col]:
return True, row, col, steps
if num < matrix[row][col]: col = col - 1
if num > matrix[row][col]: row = row + 1 # note: col might have changed
return False, row, col, steps
if __name__ == '__main__':
print_matrix(M)
num = int(raw_input("Enter num to search for: "))
(found, row, col, steps) = search_matrix(M, num)
if found:
print "%d found at (%d, %d) after %d steps: %s" \
%(num, row, col, len(steps), steps)
else:
print "%d not found after %d steps: %s" %(num, len(steps), steps)
| true |
aed8e460c17633b11c108267b6fe500a0aa2071a | SATHYASAGAR/Rosalind-Problems-Computational-Genomics | /counting-point-mutations/rosalind_hamm.py | 752 | 4.28125 | 4 | #Counting Point Mutations
def hamming_distance(s,t):
"""Return the hamming distance between two DNA strings
Keyword Argument:
s -- first dna string
t -- second dna string
Return Value:
Hamming distance between s and t
"""
hamming_distance=0
for i in range(len(t)):
if s[i]<>t[i]:
hamming_distance+=1
return hamming_distance
def main():
"""Main function to calculate the hamming distance
The function reads two dna string from the file.
Computes and prints the hamming distance.
"""
foo=open('rosalind_hamm.txt','r')
lst = foo.read().strip().split()
print hamming_distance(lst[0],lst[1])
foo.close()
if __name__ =='__main__':
main() | true |
7df4a3f92768d9997cfd927647c58d8afdaccc0d | giupo/adventofcode2020 | /findSum2020.py | 664 | 4.21875 | 4 | #!/usr/bin/env python
import fileinput
def get_numbers():
"""
get the numbers from advent of code
"""
return [int(line) for line in fileinput.input()]
numbers = get_numbers()
def find_pair(numbers = get_numbers()):
for x in numbers:
for y in numbers:
if x + y == 2020:
return (x, y)
return None
def find_triple(numbers = get_numbers()):
for x in numbers:
for y in numbers:
for z in numbers:
if x + y + z == 2020:
return (x, y, z)
return None
x, y = find_pair(numbers)
print(x * y)
x, y, z = find_triple(numbers)
print(x * y * z)
| true |
6a2c81348d9739911a5fd1f00c430a3383f585c4 | HossamKhir/1MAC_FullStack | /python/functions1/11b_stairs_mine.py | 390 | 4.21875 | 4 | #! /usr/bin/python3
# Write code to draw the staircase
# pattern above. The modulo operation
# might be useful!
import turtle
def stairs():
direction = -1
challange = turtle.Turtle()
challange.color("yellow")
challange.width(5)
for steps in range(7):
challange.forward(50)
challange.right(direction * 90)
direction *= -1
stairs()
| true |
8f51077e3a27e656b0a6768adb128ce80af1290a | TumuRenusri/DSA | /Learning/Recursion/power.py | 247 | 4.125 | 4 | def power(x, n):
if n == 0:
return 1
else:
return x*power(x,n-1)
base = int(input("Enter the base number : \n"))
exponential = int(input("Enter the power for the base : \n"))
print(power(base, exponential)) | true |
506d2a4f3fa5a63cc7b983302704f467de4ac3c7 | marblef2/web-335 | /week-8/marble_calculator.py | 280 | 4.125 | 4 | first_name = 'Fred'
last_name = 'Marble'
print(first_name+' '+last_name)
def divide(num1, num2):
return(num1 / num2)
def subtract(num1, num2):
return(num1 - num2)
def add(num1, num2):
return(num1+num2)
print(add(10, 2))
print(subtract(6, 3))
print(divide(8, 4)) | false |
e007af3011f44dd96da3e385d54a8066c6b9afca | JeremyT313/RockPaperScissors | /rps.py | 2,485 | 4.3125 | 4 | from random import choice
print('...Rock... \n...Paper... \n...Scissors...')
p1_score = 0
p2_score = 0
winning_score = 3
while p1_score < winning_score and p2_score < winning_score:
print(f'Player 1 Score: {p1_score}\nPlayer 2 Score: {p2_score}')
computer = choice(['rock', 'paper', 'scissors'])
player1 = input('What is your choice? ').lower()
player2 = computer
if player1 == 'quit' or player1 == 'q':
break
if player1 == 'rock' or player1 == 'paper' or player1 == 'scissors':
print(f'Player 1 Chose: {player1} \nPlayer 2 Chose: {player2}')
if (player1 == 'rock' and player2 == 'paper') or (player1 == 'scissors' and player2 == 'rock') or (player1 == 'paper' and player2 == 'scissors'):
print('Player 2 Wins!!! \n')
p2_score += 1
elif (player1 == 'rock' and player2 == 'scissors') or (player1 == 'paper' and player2 == 'rock') or (player1 == 'scissors' and player2 == 'paper'):
print('Player 1 Wins!!! \n')
p1_score += 1
else:
print('It\'s a Draw!!!\n')
else:
print('Please choose between rock, paper, or scissors\n')
if p1_score > p2_score:
print('Congrats You Win!!')
elif p1_score == p2_score:
print('You tied!')
else:
print('Oh no You lost!')
print(f'Final Score\nPlayer 1 Score: {p1_score}\nPlayer 2 Score: {p2_score}')
############################################
# if player1 == 'rock' or player1 == 'paper' or player1 == 'scissors':
# if player1 == 'rock':
# if player2 == 'scissors':
# print('Player 1 Wins!!!')
# elif player2 == 'paper':
# print('player 2 Wins')
# elif player1 == 'paper':
# if player2 == 'scissors':
# print('Player 2 Wins!!!')
# elif player2 == 'rock':
# print('Player 1 Wins!!!')
# elif player1 == 'scissors':
# if player2 == 'rock':
# print('Player 2 Wins!!!')
# elif player2 == 'paper':
# print('Player 1 Wins!!!')
# else:
# print('It\'s a Draw!!!')
# else:
# print('Please choose between rock, paper, or scissors')
#######################################
# p1 = input("Player 1: rock, paper, or scissors ")
# p2 = input("Player 2: rock, paper, or scissors ")
# if p1 == p2:
# print("Draw")
# elif p1 == "rock" and p2 == "scissors":
# print("p1 wins")
# elif p1 == "paper" and p2 == "rock":
# print("p1 wins")
# elif p1 == "scissors" and p2 == "paper":
# print("p1 wins")
# else:
# print("p2 wins")
| false |
ff1d702453b4370e08f23a8169c70ea7c7ab08e9 | VladislavZhukovsky/python-scripts | /source/Apps/PythonApp1/oop.py | 1,231 | 4.1875 | 4 | class Animal():
def __init__(self):
print('Animal created')
def who_am_i(self):
print('I am an animal!')
def eat(self):
print('I am eating')
#example for abstract class
def speak(self):
raise NotImplementedError('abstract class')
class Dog(Animal):
#class object attribute
species = 'mammal'
def __init__(self, breed, name, spots):
#attributes
Animal.__init__(self)
self.breed = breed
self.name = name
self.spots = spots
print('Dog created!')
def who_am_i(self):
print('I am a dog!')
#methods
def speak(self):
print('WOOF! My name is {0}!'.format(self.bark))
#mydog = Dog('Shih Tzu', 'Jasya', True)
#mydog.who_am_i()
#print(f'My {my_dog.name} is {my_dog.breed}!')
#print(Dog.species)
class Book():
def __init__(self, title, author, pages):
self.title = title
self.author = author
self.pages = pages
def __str__(self):
return f'{self.title} - {self.author}'
def __len__(self):
return self.pages
def __del__(self):
print('object deleted from memory')
b = Book('Python rocks', 'Vlad', 777)
print(b)
print(len(b))
del b | false |
a26f6c1a805d489d7d7f36422113e2b2d278bb3e | kayush96/bookish-invention | /Day - 2/tip_generator.py | 621 | 4.125 | 4 | # If the bill was $150.00, split between 5 people, with 12% tip.
# Each person should pay (150.00 / 5) * 1.12 = 33.6
# Format the result to 2 decimal places = 33.60
print("Welcome to Tip Calculator App\n")
total_amount = float(input("Enter your Total Bill Amount: "))
tip_percent = int(
input("What percentange tip would you like to give? 10, 12 or 15? "))
total_people = int(input("How many people to split the bill? "))
split_amount = (total_amount/total_people) * (1 + (tip_percent/100))
total_tip = round(split_amount, 2)
total_tip = "{:.2f}".format(split_amount)
print(f"Each person should pay: ${total_tip}")
| true |
ef56c1c286bc63a814c32efa49b5e9f78b39f339 | rakeshcarpediem/Python | /P17_PrimeNumber.py | 479 | 4.3125 | 4 | # Python program to check if given number is prime or not
no = 11
# If given number is greater than 1
if no > 1:
# check from 2 to n / 2
for i in range(2, no//2):
# If no. is divisible by any number between
# 2 and n / 2, it is not prime
if (no % i) == 0:
print(no, "is not a prime number.")
break
else:
print(no, "is a prime number.")
else:
print(no, "is not a prime number.")
| true |
0722a5d6837fe95339153aab5002bb65a7626614 | Pig-Rabbit/python_algorithm | /1.01 maximum.py | 250 | 4.25 | 4 | # maximum value of 3 integers
print('find maximum with 3 integers')
a = int(input('a: '))
b = int(input('b: '))
c = int(input('c: '))
maximum = a
if b > maximum: maximum = b
if c > maximum: maximum = c
print(f'maximum value is {maximum}') | false |
b244dddf19ebf4e5aa837997fa302e84825ab4bf | Pig-Rabbit/python_algorithm | /2.04 max_of_test_randint.py | 469 | 4.21875 | 4 | # print the maximum of sequence elements (elements are entered)
import random
from max import max_of
print('calculate the maximum of array')
num = int(input('enter the number of random: '))
lo = int(input('enter the minimum of random: '))
hi = int(input('enter the maximum of random: '))
x = [None]*num
for i in range(num):
x[i] = random.randint(lo, hi) # give random number between lo and hi
print(f'{(x)}')
print(f'the maximum is {max_of(x)}.') | true |
054f43f1838437196feb9290b9e77dffa40c17a3 | Pig-Rabbit/python_algorithm | /1.09 sum.py | 297 | 4.21875 | 4 | # the sum of integer from a to b (for)
print('solve the sum of integer from a to b')
a = int(input('enter a: '))
b = int(input('enter b: '))
if a > b:
a, b = b, a # ascending sort
sum = 0
for i in range(a, b+1):
sum += i
print(f'the sum of integer from {a} to {b} is {sum}') | true |
d9ff6a7621f1bfc946467972ca18b77f7e1376a9 | Pig-Rabbit/python_algorithm | /2.03 max_of_test_input.py | 404 | 4.1875 | 4 | # print the maximum of sequence elements (elements are entered)
from max import max_of
print('calculate the maximum of array')
print('warning: exit with "End"')
number = 0
x = []
while True:
s = input(f'enter the value of x[{number}]')
if s == 'End':
break
x.append(int(s))
number += 1
print(f'enter {number} elements')
print(f'the maximum is {max_of(x)}.') | true |
84c78d0635a213a99fdcb225c730ba3bca66e977 | Robiul-1304009/Learn-Numpy- | /numpy_3.py | 784 | 4.125 | 4 | # Slicing Arrays
import numpy as np
# Slicing one dimensional array
arr1 = np.array([1, 2, 3, 4, 5])
print(arr1[0:3]) # Index = 0, 1, 2 = 1, 2, 3
print(arr1[2:5]) # Index = 2, 3, 4 = 3, 4, 5
print(arr1[:]) # Index = whole array(0:5) = 1-5
print(arr1[1:]) # Index = 1-Last = array(1:5) = 2-5
print(arr1[:4]) # Index = 0-3 = whole array(0:4) = 1, 2, 3
print(arr1[:4:2]) # Index = 0-3 with steps 2 = 0, 2 = 1, 3
# Slicing Two dimensional array
arr2 = np.array([[1, 2, 3], [3, 4, 5], [6, 7, 8]])
print(arr2[1, 0:2]) # index = rows(1st dimension) = [3, 4, 5]
# slice(0:2) = 0, 1 = 3, 4
print(arr2[0:2, 0]) # Index = rows 0, 1 = [1, 2, 3] [3, 4, 5]
# find first element of arrays(0) = 1, 3
print(arr2[0:2, 0:2]) # slicing the arrays = 0, 1 = 1 2 3 4
| false |
5a6f5bc1e7f410bfece03fb4ada88e2651462d2e | woniuge/basicCode_Python | /liaoxuefeng/OOP/序列化/JSON.py | 507 | 4.21875 | 4 |
#Python内置的json模块提供了非常完善的Python对象
# 到JSON格式的转换。我们先看看如何把Python对象变成一个JSON:
import json
d = dict(name = 'Bob',age = 20,score = 88)
print(json.dumps(d))
#要把JSON反序列化为Python对象,用loads()或者对应的load()方法,
# 前者把JSON的字符串反序列化,后者从file-like Object中读取字
# 符串并反序列化:
json_str = '{"age":20,"score":87,"name":"Bob"}'
print(json.loads(json_str))
| false |
e0bdd68e5ab75fe40eabb1992b792a583f74657e | Marvel123456/nuthing | /fraction_calculator.py | 672 | 4.15625 | 4 | #fraction calculator
import time
whole = int(input("enter the whole number >> "))
div = int(input("enter the divident >> "))
num = int(input("enter the numerator >> "))
deev = str(div) #div
op = input() #operation
def convert():
print(whole*div+num)
print("--\n"+deev)
def add():
print(whole*div+num)
print("--\n"+deev)
if op == "convert":
i()
convert()
elif op == "add":
whole2 = int(input("enter the whole number for the 2nd number >> "))
div2 = int(input("enter the divident for the 2nd number >> "))
num2 = int(input("enter the numerator for the 2nd number >> "))
time.sleep(1)
add()
| false |
b71a759cea3ece8ec5ae2cf713ea06c4cde67873 | saggit01/CS576-Fall-2019 | /Day 03 - DNA Fragmentation/Solution/fasta.py | 2,133 | 4.53125 | 5 | def read_sequences_from_fasta_file(filename):
"""Reads all sequence records from a FASTA-formatted file.
Args:
filename: the name of the FASTA-formatted file
Returns:
A list of records, where each record is represented by a tuple (name, sequence)
"""
sequences = []
current_lines = None
with open(filename) as f:
for line in f:
if line.startswith(">"):
if current_lines is not None:
sequences.append(sequence_from_fasta_lines(current_lines))
current_lines = []
current_lines.append(line.rstrip())
# Handle the last record in the file
if current_lines is not None:
sequences.append(sequence_from_fasta_lines(current_lines))
return sequences
def write_sequences_to_fasta_file(sequences, filename, wrap_width=70):
"""Writes a list of sequence records to a file in FASTA format.
Args:
sequences: A list of records, where each record represented by a tuple (name, sequence)
filename: the name of the file to which to write the sequences.
"""
with open(filename, 'w') as f:
for name, sequence in sequences:
print(">" + name, file=f)
print(wrap_sequence(sequence, wrap_width), file=f)
def sequence_from_fasta_lines(lines):
"""Constructs a sequence record from a list of FASTA-formatted lines
Args:
lines: a list of FASTA-formatted lines representing one sequence record
Returns:
A sequence record, which is represented by a tuple (name, sequence)
"""
# Strip the beginning '>'
name = lines[0][1:]
# Concatenate the sequence lines
sequence = ''.join(lines[1:])
return (name, sequence)
def wrap_sequence(s, width):
"""Wraps a string to multiple lines with a given maximum line length.
Args:
s: a string
width: the maximum line length
Returns:
A string equivalent to s but wrapped such that lines are no longer than width
"""
return "\n".join(s[start: start + width] for start in range(0, len(s), width))
| true |
e885ee38464cac46398f7adc9ac92a74be99ad8c | Jessica-Thomas/PythonPractice | /check_pls.py | 1,119 | 4.1875 | 4 | # import math
# def split_check(total,people):
# cost_per_person = math.ceil(total / people)
# return cost_per_person
# #math.ceil rounds up to a whole number so we don't get 5 decimal places
# #calling split_check and storing in amount_due
# total_due = float(input("What is the check total? "))
# people = int(input("How many people are splitting the check? "))
# amount_due = split_check(total_due, people)
# print("Each person owes ${}".format(amount_due))
# EXCEPTIONS-- try code
import math
def split_check(total,people):
if people <= 1:
raise ValueError("More than 1 person required to split check.")
cost_per_person = math.ceil(total / people)
return cost_per_person
try:
total_due = float(input("What is the check total? "))
people = int(input("How many people are splitting the check? "))
amount_due = split_check(total_due, people)
except ValueError as err:
print("That is not a valid value. Please enter a number.")
print("({})".format(err))
else:
print("Each person owes ${}".format(amount_due)) | true |
e58f51132facce0543742f651fa065a4238054ad | Jessica-Thomas/PythonPractice | /in_not_in.py | 889 | 4.46875 | 4 | docs = 'Tuples are immutable sequences, typically used to store collections of heterogeneous data (such as the 2-tuples produced by the enumerate() built-in). Tuples are also used for cases where an immutable sequence of homogeneous data is needed (such as allowing storage in a set or dict instance).'
if 'tuple' in docs:
print("I seen't the tuple.")
else:
print("Nah, bruh. No tuple here.")
marbles = 'Marbles are immutable glass balls, typically used to store collections of heterogeneous data (such as the 2-Marbles produced by the enumerate() built-in). Marbles are also used for cases where an immutable sequence of homogeneous data is needed (such as allowing storage in a set or dict instance).'
if 'marble' in marbles:
print("I seen't the marble.")
else:
print("Nah, bruh. No marbles here.")
print(docs.count('Tuple'))
print(docs.index('Tuple')) | true |
21ada74a5964a93c024f7890f3c03eaf6942d9ff | saurabhgrewal718/automation-using-python | /my_strings.py | 630 | 4.15625 | 4 | var = "yes thjis is a string"
var2 = 'this is a greedy\'s gouse'
# use of three quotes to represent the mulitline input
var = """
whatever i write here
will appeear as it is
and it is
co
soo
cool"""
print(var)
#using raw string
var = r"this is a \' raw string"
print(var)
var = "String slicing"
for i in range(0,len(var)):
print(var[i],end=" ")
print("-1 ",var[-1])
print("4 ",var[4])
print("-1 -1 ",var[:-1])
print("all ",var[:])
a ='cats' not in 'cats and dogs'
print(a)
#strign methods
var = var.upper()
print(var)
var = var.lower()
print(var)
var = var.isupper()
print(var)
a = '12345'.islower()
print(a) | true |
85dbc4f3d31f6d4464db5d008fa27b45a4a8d97e | SJeliazkova/SoftUni | /Programming-Basic-Python/Exams/Exam_6_7_July_2019/06. The Most Powerful Word.py | 913 | 4.21875 | 4 | word = input()
powerful_word = ""
powerful_word_points = 0
while word != "End of words":
word_len = len(word)
symbol_sum = 0
first_letter = word[0]
for i in range(0, word_len):
letter = word[i]
letter_value = ord(word[i])
symbol_sum += letter_value
if first_letter == "a" or first_letter == "e" or first_letter == "i" or \
first_letter == "o" or first_letter == 'y' or first_letter == "u" or \
first_letter == "A" or first_letter == "E" or first_letter == "I" or \
first_letter == "O" or first_letter == "Y" or first_letter == "U":
result = symbol_sum * word_len
else:
result = round(symbol_sum / word_len)
if result > powerful_word_points:
powerful_word_points = result
powerful_word = word
word = input()
else:
print(f"The most powerful word is {powerful_word} - {powerful_word_points}") | false |
280f0c72ebc385046d372af3d271cb3733e346dd | SJeliazkova/SoftUni | /Programming-Basic-Python/Exams/Exam_6_7_July_2019/03. Coffee Machine.py | 1,300 | 4.21875 | 4 | drink_type = input()
sugar = input()
number_of_drinks = int(input())
drink_price = 0
if drink_type == "Espresso":
if sugar == "Without":
drink_price = number_of_drinks * 0.90 * 0.65
elif sugar == "Normal":
drink_price = number_of_drinks * 1
elif sugar == "Extra":
drink_price = number_of_drinks * 1.20
elif drink_type == "Cappuccino":
if sugar == "Without":
drink_price = number_of_drinks * 1 * 0.65
elif sugar == "Normal":
drink_price = number_of_drinks * 1.20
elif sugar == "Extra":
drink_price = number_of_drinks * 1.60
elif drink_type == "Tea":
if sugar == "Without":
drink_price = number_of_drinks * 0.50 * 0.65
elif sugar == "Normal":
drink_price = number_of_drinks * 0.60
elif sugar == "Extra":
drink_price = number_of_drinks * 0.70
if drink_type == "Espresso" and number_of_drinks >= 5:
if sugar == "Without":
drink_price = number_of_drinks * 0.90 * 0.65 * 0.75
elif sugar == "Normal":
drink_price = number_of_drinks * 1 * 0.75
elif sugar == "Extra":
drink_price = number_of_drinks * 1.20 * 0.75
if drink_price > 15:
drink_price = drink_price * 0.80
print(f"You bought {number_of_drinks} cups of {drink_type} for {drink_price:.2f} lv.")
| true |
1f5cb483324e1b165ee6071a17e52d0ddcc089ee | 123kanhaiya/Python-programming | /divisiblity_checker_for_anyno.py | 218 | 4.21875 | 4 | num=int(input('enter your number for check:- '))
y=int(input('by which number u have to divide:- '))
if num%y==0:
print(num,' it is divisible by ', y)
else:
print(num,' (´•`_´•`) srry it is not divisible by',y) | false |
4e8de312406798989c2857b2375dcaa21ba24ff3 | Cooops/Coding-Challenges | /CodeWars/make_negative.py | 690 | 4.21875 | 4 | # http://www.codewars.com/kata/return-negative/train/python
"""
We need a function that can transform a number into a string.
In this simple assignment you are given a number and have to make it negative. But maybe the number is already negative?
Example:
make_negative(1); # return -1
make_negative(-5); # return -5
make_negative(0); # return 0
Notes:
The number can be negative already, in which case no change is required.
Zero (0) is not checked for any specific sign. Negative zeros make no mathematical sense.
"""
# MY SOLUTION
def make_negative(number):
return int(f'-{number}') if number >=0 else number
# TOP SOLUTION
def make_negative(number):
return -abs(number)
| true |
bcca4ef6b304b67d7cdaa522fb8b8169c9bee41b | Cooops/Coding-Challenges | /CodeWars/unique_number.py | 733 | 4.25 | 4 | # http://www.codewars.com/kata/find-the-unique-number-1/train/python
"""
There is an array with some numbers. All numbers are equal except for one. Try to find it!
findUniq([ 1, 1, 1, 2, 1, 1 ]) === 2
findUniq([ 0, 0, 0.55, 0, 0 ]) === 0.55
It’s guaranteed that array contains more than 3 numbers.
The tests contain some very huge arrays, so think about performance.
This is the first kata in series:
Find the unique number (this kata)
Find the unique string
Find The Unique
"""
# MY SOLUTION
from collections import Counter
def find_uniq(arr):
x = Counter(arr)
for x in x.most_common(2)[::-1]:
return x[0]
# TOP SOLUTION
def find_uniq(arr):
a, b = set(arr)
return a if arr.count(a) == 1 else b
| true |
7235c61939c23805ac0ebb9f67bf32abe6c62ad2 | Cooops/Coding-Challenges | /HackerRank/rotate_array_left.py | 1,227 | 4.5625 | 5 | """
Complete the function rotLeft in the editor below. It should return the resulting array of integers.
rotLeft has the following parameter(s):
An array of integers .
An integer , the number of rotations.
Input Format
The first line contains two space-separated integers and , the size of and the number of left rotations you must perform.
The second line contains space-separated integers .
"""
def rotLeft(a, d):
"""
The below algorithm takes advantage of python's powerful slicing functionality to easily
re-order our array.
In Python, index slicing works like so => indices[start:stop:step].
First, we begin with the index specified at start (k:) and traverse to the next index by our step amount
(i.e. if step = 2, then we jump over every other element, if step = 3, we jump over 2 elements at a time).
If step is not specified it is defaulted to 1.
We continue steping from our start point until we come to or exceed our stop point.
We do NOT get the stop point, it simply represents the point at which we stop.
"""
print(a[d:]) # [5]
print(a[:d]) # [1, 2, 3, 4]
aR = a[d:] + a[:d] # [5, 1, 2, 3, 4]
return aR
print(rotLeft([1, 2, 3, 4, 5], 4))
| true |
c8c3beb4f2e8852d9050bb6bd7c28f8ffa5acdb1 | Cooops/Coding-Challenges | /CodeWars/find_odd_int.py | 573 | 4.1875 | 4 | # http://www.codewars.com/kata/find-the-odd-int/python
# MY SOLUTION
def find_it(n):
""" (array) -> int
Takes in an array of integers and returns the int that appears an odd number of times.
There will always be _only one_ integer that appears an odd number of times.
We use .pop to pop the last value out of the set. We can also use `next(iter(set(list)))` to extract the value.
"""
return set([i for i in n if n.count(i) % 2]).pop()
# TOP SOLUTION
def find_it(seq):
for i in seq:
if seq.count(i)%2!=0:
return i
| true |
49bdf9142fe78d3f09189d383636e45e784c0a4a | acerinop/Programmability-Black-Belt | /Apprentice_Level1/Camp1_Day2_assign3.py | 2,838 | 4.40625 | 4 | '''
Loops in a program go over a particular set of actions repeatedly until a condition is met/not met. Below is a list with a set of numbers as given below.
Print out all the even numbers in the sequence. Write the solution (in Python 3) into a function and have it called in your main block for the requested answer.
numbers = [{'sequence': '951, 402, 984, 651, 360, 69, 408, 319, 601, 485, 980, 507, 725, 547, 544, 615, 83, 165, 141, 501, 263, 617, 865, 575, 219, 390, 984, 592, 236, 105, 942, 941, 386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345, 399, 162, 758, 219, 918, 237, 412, 566, 826, 248, 866, 950, 626, 949, 687, 217, 815, 67, 104, 58, 512, 24, 892, 894, 767, 553, 81, 379, 843, 831, 445, 742, 717, 958, 609, 842, 451, 688, 753, 854, 685, 93, 857, 440, 380, 126, 721, 328, 753, 470, 743, 527'}]
eg:
find_even()
output : The even numbers are : 2,4,6,8
'''
numbers = [{'sequence': '951, 402, 984, 651, 360, 69, 408, 319, 601, 485, 980, 507, 725, 547, 544, 615, 83, 165, 141, 501, 263, 617, 865, 575, 219, 390, 984, 592, 236, 105, 942, 941, 386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345, 399, 162, 758, 219, 918, 237, 412, 566, 826, 248, 866, 950, 626, 949, 687, 217, 815, 67, 104, 58, 512, 24, 892, 894, 767, 553, 81, 379, 843, 831, 445, 742, 717, 958, 609, 842, 451, 688, 753, 854, 685, 93, 857, 440, 380, 126, 721, 328, 753, 470, 743, 527'}]
def splitValue(varName, key, separator):
varSplit = varName[key].split(separator)
return varSplit
def removeUneven(unevenList):
evenOutput = [i for i in unevenList if int(i)%2 == 0]
return evenOutput
def removeDuplicate(duplicateList):
uniqueList = list(set(duplicateList))
return uniqueList
def sequencialValue(seqListName):
seqListName.sort(key=int)
return seqListName
def joinValue(joinListName, separator):
joinList = separator.join(joinListName)
return joinList
def find_even(numbersList, keyName, separatorValue):
#split the value with ',' separator by using function defined earlier
evenNumber = splitValue(numbersList[0], keyName, separatorValue)
#remove "un-even" number in the list by using function defined earlier
evenNumber = removeUneven(evenNumber)
#remove duplicate entries in the list by using function defined earlier
evenNumber = removeDuplicate(evenNumber)
# sort the list in ascending order by using function defined earlier
evenNumber = sequencialValue(evenNumber)
# join list values using "," separator and rely on the function defined earlier
evenNumber = joinValue(evenNumber, separatorValue)
print("output : The even numbers are : " + evenNumber)
# Entry point for program
if __name__ == '__main__':
# execute the find_even function and print out the result
find_even(numbers, "sequence", ",") | true |
f41515e6620378f31362127c9420f1daa4a54421 | Stridma/SSYX02-17-82 | /main.py | 2,672 | 4.21875 | 4 | #!/usr/bin/env python
"""
This file contains the main program that the user is supposed to run. The program can handle both simulations and real
life robots. This file only contains one function, and the purpose is to delegate work to other functions in regard to
the users intentions.
Maybe it would be a nice touch if it had a GUI, but it is of no importance for its functioning.
"""
import rospy
import simulation
import run
# Start program, ask whether it is a simulation
# or not and take action accordingly.
def main():
sim = raw_input("Simulation (y/n)?: ")
sim.lower()
nbr_of_nodes = input("Input number of robots in system: ")
if sim == "y":
sim_object = simulation.Simulation(nbr_of_nodes)
else:
run_object = run.Run(nbr_of_nodes)
while True:
user = raw_input("What do you want to do (h for help)? ")
user.lower()
if user == "h" or user == "help":
print "Possible commands are: "
print "Go to formation (gtf)"
print "Move formation (mf)"
print "Rotate robots (rr)"
print "Exit"
elif user == "go to formation" or user == "gtf":
if sim == "y":
sim_object.set_formation()
sim_object.go_to_formation()
else:
run_object.set_formation()
run_object.go_to_formation()
elif user == "move formation" or user == "mf":
print "Where do you want the robot to go? "
goal = [0, 0]
goal[0] = input("x: ")
goal[1] = input("y: ")
print "What should the distances in between them be?"
distance = input("Distance: ")
# Distances are given from robot a to b as distances[a][b]
distances = [[0, distance, distance],
[distance, 0, distance],
[distance, distance, 0]]
if sim == "y":
sim_object.move_formation(goal, distances)
else:
run_object.move_formation(goal, distances)
elif user == "rotate robots" or user == "rr":
orientation = input("Input orientation in radians: ")
if sim == "y":
sim_object.rotate(orientation)
else:
run_object.rotate(orientation)
elif user == "exit" or user == "quit":
break
# Needed for the program to know that it is supposed to run when called on.
# Catches exception from rospy but takes no action if caught.
if __name__ == '__main__':
try:
main()
except rospy.ROSInterruptException:
pass | true |
5c5e7d0717bb05502e33eb145a18d395f2420d26 | nicalitz/Programiz-Tutorials | /function arguments.py | 740 | 4.15625 | 4 | from __future__ import print_function
# DEFAULT ARGUMENTS
def greet(name, msg = "good morning!"):
"""This function greets to
the person with the provided message.
If message is not provided, it defaults
to "Good morning!" """
print("Hello",name + ', ' + msg)
greet('Kate')
greet('Bruce','how do you do?')
# non-default arguments cannot follow default arguments. that is to say, the following would not be allowed:
# def greet(msg = "good morning", name):
# ARBITRARY ARGUMENTS: defined using asterisk (*)
def greet(*names):
"""This function greets all
the person in the names tuple."""
# names is a tuple with arguments
for name in names:
print("Hello",name)
greet("Monica","Luke","Steve","John") | true |
caa751b7b83175d619d1563abbe88d2fbe99c527 | bhavnavarshney/Algorithms-and-Data-Structures | /Python/Binary-Insertion-Sort.py | 228 | 4.25 | 4 | print('****** Binary Insertion Sort **********')
# Used to reduced the number of comparison in Insertion Sort O(log n) but shifting the elements after insertion takes O(n)
# Complexity : O(nlogn)-> Comparisons and O(n*n) swaps
| true |
3c1a7b5cfece173f0190a06d1eb60fd235f5454b | MartinYangSH/Liu-s-Word | /chapter14/exer3.py | 580 | 4.3125 | 4 | string = "123asbs43abads02982"
digit = []
alphabet = []
def select(string):
try:
for item in string:
if ord(item)>=48 and ord(item)<=57:
digit.append(item)
elif ord(item)>=97 and ord(item)<=122 or ord(item)>=65 and ord(item)<=90:
alphabet.append(item)
else:
raise TypeError
except TypeError:
print 'The string must be consisted of integer or alphabet'
select(string)
print "All digit in string are :"+str(digit)
print "All alphabet in string are :"+str(alphabet) | true |
bca9834384a7322f9c0f53ebb8c705cceaf59926 | KenMwanza/bc-9-oop | /student.py | 1,570 | 4.125 | 4 | from datetime import date
map_ = {
'KE' : "Kenya",
"UG" : 'Uganda'
}
class Student(object): # This object here is a class object
count = 0
class_attendance = [] # Takes dates as keys and list of attendance as values
def __init__(self, fname = '', lname = '', cc = "KE"): # Here you can provide the default parameters
# Generate sequential unique id
Student.count += 1
self.id = Student.count #Using two underscore makes it private
self.fname = fname
self.lname = lname
self.country = map_[cc]
def attend_class(self, **kwargs):
'''
default values:
location = 'Hogwarts'
date = current_date
teacher = 'Alex'
'''
location = 'Hogwarts'
m_date = date.today().strftime("%B %d %Y")
teacher = 'Alex'
# Take the data and append it the attendance list
data = [m_date, self.fname, teacher, location]
Student.class_attendance.append(data)
# Print all data in the attendance list
def get_class_attendance(self):
my_test_date = date.today().strftime("%B %d %Y")
no_of_attendees = 0
attendance = Student.class_attendance
print attendance
for item in attendance:
print item
for details in range(len(item)):
if item[details] == my_test_date:
no_of_attendees += 1
print "%s STUDENTS ATTENDED ON %s" % (no_of_attendees, my_test_date)
| true |
6b41930bca27d7cc2e9adc5f13028382b9a97bc1 | IraSym/SoftServePython | /HW3_Will there be enough space.py | 1,184 | 4.53125 | 5 | # Bob is working as a bus driver. However, he has become extremely popular amongst the city's residents.
# With so many passengers wanting to get aboard his bus, he sometimes has to face the problem of not enough space left
# on the bus! He wants you to write a simple program telling him if he will be able to fit all the passengers.
# Task Overview:
# You have to write a function that accepts three parameters:
# cap is the amount of people the bus can hold excluding the driver.
# on is the number of people on the bus.
# wait is the number of people waiting to get on to the bus.
# If there is enough space, return 0, and if there isn't, return the number of passengers he can't take.
cap=int(input("Input the amount of people the bus can hold excluding the driver: "))
on=int(input("Input the number of people on the bus: "))
wait=int(input("Input the number of people waiting to get on to the bus: "))
if on + wait <= cap:
waiting_people = 0
print("There is enough space!!!")
else:
waiting_people = on + wait - cap
print("There is not enough space!!!")
print("There are {} people waiting for the next bus".format(waiting_people)) | true |
d5e38a58332f2c513b51f30f91df24c79ad0a3c7 | tlherr/NETS1035-Lab1 | /Question1.py | 648 | 4.4375 | 4 | # Thomas Herr
# 200325519
# NETS1035 Applied Cryptography
# 1. Create a python program that takes a string and prints out the first,middle and last characters.
# a. The program should take an input,value = input(), or use argv
# b. Example input is hello, output is “hlo”
while True:
try:
name = input("Please enter a string: ")
if not name:
raise ValueError('Empty String Given')
except ValueError as e:
print("Sorry, I didn't understand that.")
print(e)
continue
else:
break
length = len(name)
half = int(length/2)
print(name[0],name[half],name[length - 1], sep='')
| true |
0ab873ce51b1dd8c0983bd410185ec98c83114dc | a6232283/University_Practice-code_python | /Python初級/Set-Dictionary .py | 712 | 4.125 | 4 | #集合
#s1={3,4,5}
#print (10 not in s1)
#s1={3,4,5}
#s2={4,5,6,7}
#s3=s1&s2 #交集:取兩集合中,相同資料 4,5
#s3=s1|s2 #聯集:取兩集合中,但不重複 3,4,5,6,7
#s3=s1-s2 #差集:S1減去S2有重疊部分 3
#s3=s1^s2 #反交集:取兩集合中,不重複部分
#print(s3)
#s=set("hello") #set(字串) 差解匯出隨機
#print("h" in s)
#字典運算:key-value配對
#dic={"apple":"蘋果","bug":"蟲蟲"};
#dic["apple"]="小蘋果";
#print(dic["apple"])
#dic={"apple":"蘋果","bug":"蟲蟲"};
#print("apple" in dic)#判斷key是否存在
#del dic["apple"];#刪除字典中的鍵值對
#print(dic)
dic={x:x*2 for x in [3,4,5]}#從列表的資料產生字典
print(dic) | false |
610c3f0966fff4c4d2b56cf9fc6048b12bf3062b | joyrexus/CS212 | /exam/2_logic/main.py | 2,639 | 4.21875 | 4 | """
UNIT 2: Logic Puzzle
You will write code to solve the following logic puzzle:
1. The person who arrived on Wednesday bought the laptop.
2. The programmer is not Wilkes.
3. Of the programmer and the person who bought the droid,
one is Wilkes and the other is Hamming.
4. The writer is not Minsky.
5. Neither Knuth nor the person who bought the tablet is the manager.
6. Knuth arrived the day after Simon.
7. The person who arrived on Thursday is not the designer.
8. The person who arrived on Friday didn't buy the tablet.
9. The designer didn't buy the droid.
10. Knuth arrived the day after the manager.
11. Of the person who bought the laptop and Wilkes,
one arrived on Monday and the other is the writer.
12. Either the person who bought the iphone or the person who bought the tablet
arrived on Tuesday.
You will write the function logic_puzzle(), which should return a list of the
names of the people in the order in which they arrive. For example, if they
happen to arrive in alphabetical order, Hamming on Monday, Knuth on Tuesday, etc.,
then you would return:
['Hamming', 'Knuth', 'Minsky', 'Simon', 'Wilkes']
(You can assume that the days mentioned are all in the same week.)
"""
import itertools
_ = None
people = ['Hamming', 'Knuth', 'Minsky', 'Simon', 'Wilkes']
(H, K, M, S, W) = people
def logic_puzzle():
"Return a list of the names of the people, in the order they arrive."
orders = list(itertools.permutations(people))
result = next((mon, tue, wed, thu, fri)
for (mon, tue, wed, thu, fri) in orders
for (programmer, writer, manager, designer, _) in orders
if manager is S
and s_then_k(mon, tue, wed, thu, fri)
and programmer is not W # and programmer is H
and writer is not M
and thu is not designer
and (mon is W or writer is W)
for (laptop, tablet, droid, iphone, _) in orders
if droid in (W, H)
and programmer in (W, H)
and droid is not programmer
and tue in (iphone, tablet)
and wed is laptop
and fri is not tablet
and designer is not droid
and manager not in (tablet, K)
and mon in (laptop, W)
and writer in (laptop, W)
and mon is not writer)
return list(result)
def s_then_k(*days):
'''Knuth should immediately follow Simon.'''
s = days.index(S)
k = days.index(K)
return k - s == 1
print logic_puzzle()
# ('Wilkes', 'Hamming', 'Minsky', 'Simon', 'Knuth')
#
# simon is manager since ...
# if follows(S, K)
# if follows(manager, K)
| true |
1b72ae0a954da4aef2c2b3e67ffd01adf39f9356 | yuancf1024/learn-python-exercise | /2020-01-lxf-python/hannoi.py | 592 | 4.21875 | 4 | # -*- coding: utf-8 -*-
# 汉诺塔函数 7行代码搞定
''' n = 1 -> 1
n = 2 -> 3
n = 3 -> 7
n = 4 -> 15
n = 5 -> 31
'''
def move(n, a, b, c):
if n == 1:
print(a,'-->',c)
else:
move(n-1,a,c,b)
print(a,'-->',c)
move(n-1,b,a,c)
# print(b,'-->',a)
#move(n-1,b,c,a)
#print(a,'-->',c)
#move(n-1,a,b,c)
move(1,'A', 'B', 'C')
print('间隔')
move(2,'A', 'B', 'C')
print('间隔')
move(3, 'A', 'B', 'C')
print('间隔')
move(4, 'A', 'B', 'C')
print('间隔')
move(5,'A','B','C') | false |
5d2db2f416e7d5bb25c1b9d2b40f828725e57134 | CodeForContribute/Algos-DataStructures | /LinkedListCodes/linkedlistinsertion.py | 1,092 | 4.25 | 4 | class Node:
def __init__(self,data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def push(self,new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
def append(self,data):
new_node = Node(data)
last = self.head
if self.head is None:
self.head = new_node
while last and last.next is not None:
last = last.next
last.next = new_node
@staticmethod
def insert_after(prev_node, new_data):
if prev_node is None:
print("The given previous node does not exist")
return
new_node = Node(new_data)
new_node.next = prev_node.next
prev_node.next = new_node
def print_list(self):
node = self.head
while node:
print(node.data, end="\n")
node = node.next
if __name__ == '__main__':
ll = LinkedList()
ll.push(90)
ll.append(8)
ll.push(80)
ll.append(7)
ll.print_list()
| true |
e0167b1bd771b562b0ab53ee0244a911ef6a57d3 | CodeForContribute/Algos-DataStructures | /LinkedListCodes/check_wheather_ll_is_even_or_odd.py | 975 | 4.1875 | 4 | class Node:
def __init__(self, new_data):
self.data = new_data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
def print_list(self):
temp = self.head
while temp:
print(temp.data, end=" ")
temp = temp.next
def check_whether_linked_list_is_even_odd(self):
temp = self.head
length = 0
while temp:
length += 1
temp = temp.next
if length % 2 == 0:
print("Linked List is even")
else:
print("Linked List is odd")
if __name__ == '__main__':
ll = LinkedList()
ll.push(3)
ll.push(4)
ll.push(5)
ll.push(6)
ll.push(7)
print("Created Linked List is:")
ll.print_list()
print("\n")
ll.check_whether_linked_list_is_even_odd() | false |
6aded8830b25e8ed6b6b0de17d605d1b52e47f80 | CodeForContribute/Algos-DataStructures | /TreeCodes/TreeTraversal/Morris_traversal_without_stack_recursion.py | 2,135 | 4.1875 | 4 | class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
########################################################################################################################
# Morris Traversal : Time Complexity : O(n) Space Complexity :O(1)
def in_order_traversal_without_recursion_and_stack(root):
if root is None:
return
current = root
while current is not None:
if current.left is None:
print(current.data, end=" ")
current = current.right
else:
pred = current.left
while pred.right is not None and pred.right is not current:
pred = pred.right
if pred.right is None:
pred.right = current
current = current.left
else:
pred.right = None
print(current.data, end=" ")
current = current.right
########################################################################################################################
def pre_order_traversal(root):
if root is None:
return
current = root
while current is not None:
if current.left is None:
print(current.data, end=" ")
current = current.right
else:
pred = current.left
while pred.right is not None and pred.right is not current:
pred = pred.right
if pred.right is None:
pred.right = current
print(current.data, end=" ")
current = current.left
else:
pred.right = None
current = current.right
########################################################################################################################
if __name__ == '__main__':
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
in_order_traversal_without_recursion_and_stack(root)
print("\n")
print("Pre-Order Traversal of tree is:")
pre_order_traversal(root)
| true |
e03af66ee64166fa7e0cc621617f6ff0a5f86d19 | CodeForContribute/Algos-DataStructures | /TreeCodes/checking&Printing/2trees_identical_recursive.py | 833 | 4.15625 | 4 | class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right= None
def isSymmetric(root1, root2):
if not root1 and not root2:
return True
# if root1 or root2:
# return False
if root1 and root2:
return root1.data == root2.data and isSymmetric(root1.left, root2.left) and isSymmetric(root1.right, root2.right)
return False
if __name__ == '__main__':
root1 = Node(1)
root2 = Node(1)
root1.left = Node(2)
root1.right = Node(3)
root1.left.left = Node(4)
root1.left.right = Node(5)
root2.left = Node(2)
root2.right = Node(3)
root2.left.left = Node(4)
root2.left.right = Node(5)
if isSymmetric(root1, root2):
print("Both trees are identical")
else:
print("Trees are not identical") | true |
566c2d27517941be2636c6fd99c45a8a420cd909 | CodeForContribute/Algos-DataStructures | /LinkedListCodes/delete_nodes_greater_right_value.py | 1,825 | 4.21875 | 4 | class Node:
def __init__(self, new_data):
self.data = new_data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
def print_list(self):
temp = self.head
while temp:
print(temp.data, end=" ")
temp = temp.next
# Algorithms:
# 1. First reverse the given list
# 2. keep track of max node till then:
# if max node is greater than next node delete the next node
# else max node will be next node
# 3.Reverse the given list back
def reverse_linked_list(self):
prev = None
current = self.head
while current is not None:
next_node = current.next
current.next = prev
prev = current
current = next_node
self.head = prev
def delete_nodes_greater_right_value(self, head):
max_node = head
current = head
while current is not None and current.next is not None:
if current.next.data >= current.data:
current = current.next
max_node = current
else:
temp = current.next
current.next = temp.next
temp = None
if __name__ == '__main__':
ll = LinkedList()
ll.push(3)
ll.push(2)
ll.push(6)
ll.push(5)
ll.push(11)
ll.push(10)
ll.push(15)
ll.push(12)
print("Created Linked List is:")
ll.print_list()
print("\n")
print("Linked List after deleting grater right value")
ll.reverse_linked_list()
ll.delete_nodes_greater_right_value(ll.head)
ll.reverse_linked_list()
ll.print_list()
| true |
bb4319b1690afac7745fc128b98d5a3e4327a1dd | CodeForContribute/Algos-DataStructures | /LinkedListCodes/delete_alternate_nodes.py | 1,430 | 4.1875 | 4 | class Node:
def __init__(self, new_data):
self.data = new_data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
def print_list(self):
temp = self.head
while temp:
print(temp.data, end=" ")
temp = temp.next
def delete_alternate_nodes(self, head):
if head is None:
return
prev = head
node = head.next
while prev is not None and node is not None:
prev.next = node.next
node = None
prev = prev.next
if prev is not None:
node = prev.next
def delete_alternate_nodes_recursive(self, head):
if head is None:
return
node = head.next
if node is None:
return
head.next = node.next
node = None
self.delete_alternate_nodes_recursive(head.next)
if __name__ == '__main__':
ll = LinkedList()
ll.push(90)
ll.push(89)
ll.push(78)
ll.push(67)
ll.push(56)
ll.push(45)
ll.push(34)
print("\n")
print("Created Linked List is :")
ll.print_list()
ll.delete_alternate_nodes_recursive(ll.head)
print("\n")
print("Linked List after deleting alternate nodes:")
ll.print_list()
| true |
b4b70c5af7ed34368c3ec1df6cc875c0c784a325 | thiagovongrapp/Languages_Skills | /Python/1_Variables_and_Data_Types/Exercise_1.py | 1,518 | 4.15625 | 4 | """
Exercise 1:
- Objective: Create a system which receives three integer values and print their sum.
# Reference: Course "Programação em Python do Básico ao Avançado" - Geek University, Udemy. #
"""
print("Choisissez une option de langue, s'il vous plaît!\n"
"Please, choose a language option!\n\n"
"[1] - Français\n"
"[2] - English\n")
try:
option = int(input("Option: "))
if option == 1:
print("\nBienvenue! Saisissez trois valeurs ci-dessous pour voir leur somme.\n")
first_value = int(input("Premier Valeur: "))
second_value = int(input("Deuxième Valeur: "))
third_value = int(input("Troisième Valeur: "))
print(f"\nTotal = {first_value + second_value + third_value}")
elif option == 2:
print("\nWelcome! Please, enter three values below to see their sum.\n")
first_value = int(input("First Value: "))
second_value = int(input("Second Value: "))
third_value = int(input("Third Value: "))
print(f"\nTotal = {first_value, + second_value + third_value}")
else:
print("\nOption invalide! Redémarrez le système et choisissez une option valable, s'il vous plaît!"
"\nInvalid option! Please, restart the system and choose a valid option!")
except ValueError:
print("\nOption invalide! Redémarrez le système et choisissez une option valable, s'il vous plaît!"
"\nInvalid option! Please, restart the system and choose a valid option!")
| false |
f50478605914fe1f8010a3f6f83560db6365df4f | natedo18/cop1000 | /do4/program4_1.py | 2,561 | 4.28125 | 4 | #Minh-Nhat Do 2418180
#Pseudocode
#start by assigning constants to REDUCTION (.25), TAX (0.07)
#start accumulator assigning total to 0
#start while expression ticket price!=0
#prompt the user to input the ticket price item and assign to variable, price
#prompt the user to input whether item is on sale or not
#if the item is on sale, multiply by .25 to get amount reduced,
#assign to discount
#calculate sale price by subtracting discount from price,
#assign to variable, sale_price
#if the item is not reduced, assign price as sale_price
#prompt the user to input whether item is taxable or not
#if the item is taxable, multiply sale_price by 0.07 to calculate sales tax,
#assign to variable sales_tax
#if the item is not taxable, assign sales_tax as 0.00
#to calculate the total amount due, assign sale_price+sales_tax to total
#print all required information
def main():
#assign constants for sale reduction and tax
REDUCTION=0.25
TAX=0.07
#set accumulator value
total=0.0
#prompt input of ticket price from the user,
#use float in case an item is not a whole dollar
price=float(input('Enter the ticket price of the item or 0 to quit: '))
while price!=0:
#determine if the item is reduced and calculate sale price as needed
reduced=input('Is this item reduced y/n? ')
if reduced=='y':
discount=(price*REDUCTION)
sale_price=(price-discount)
else:
discount=0 #if item is not on sale,
sale_price=price #assign price to sale_price
#determine if the item is taxable and calculate tax as needed
taxable=input('Is this item taxable y/n? ')
if taxable=='y':
sales_tax=sale_price*TAX
else:
sales_tax=0 #sales_tax set to 0 if item is not
#assign final price of the item to total #taxable
subtotal=(sale_price+sales_tax)
#printing all required information
print('Here is your bill:')
print('Original price: $',format(price,'.2f'),sep='')
print('Reduction during event: $',format(discount,'.2f'),sep='')
print('Final price: $',format(sale_price,'.2f'),sep='')
print('7% Sales tax: $',format(sales_tax,'.2f'),sep='')
print('Item subtotal: $',format(subtotal,'.2f'),sep='')
price=float(input('Enter the ticket price of item or 0 to quit: '))
total+=subtotal
print('Total amount due: $',format(total,'.2f'),sep='')
main()
#collaborators: none
| true |
ab977ff1983770e88377066e34a0b83698ecc0f8 | mrkresker/codewars | /leastcoinchange.py | 1,871 | 4.125 | 4 | def coin_change(cash):
"""
Given cash, return least number of coins necessary
Using coin denominations of 1,4,5,9
"""
final_count = [0,0,0,0]
amt_left = cash
while amt_left > 0:
if int(amt_left/9) > 0:
final_count[3] += int(amt_left/9)
amt_left -= 9 * int(amt_left/9)
elif int(amt_left/5) > 0:
final_count[2] += int(amt_left/5)
amt_left -= 5 * int(amt_left/5)
elif int(amt_left/4) > 0:
final_count[1] += int(amt_left/4)
amt_left -= 4 * int(amt_left/4)
else:
final_count[0] += 1
amt_left -= 1
return final_count, sum(final_count)
def joes_solution(coins, value):
"""
This takes in a list of coin denominations as coins i.e. [1, 4, 5, 9]
and a value which is the change you want to give
"""
table = [None for x in range(value + 1)] # creates a list with None as big as the change is i.e. if value = 4, table = [None, None, None, None, None] (0, 1, 2, 3, 4)
table[0] = [] # initializes the first element in table to be an empty list
for i in range(1, value + 1): # if value = 4 => [1, 2, 3, 4]
for coin in coins: # for each of the coin values i.e. if coins =[1, 4, 5, 9], coin 1 then 4 then 5 then 9
if coin > i: continue #if the coin denomination is bigger than i, just continue. 4 > 1, 2, 3 so it just continues.
elif not table[i] or len(table[i - coin]) + 1 < len(table[i]): #table[i] => None usually. so if you do not None => True or len(table[4-3]) + 1 = len(None) + 1 = 2< len(table[i]) = 2<1
if table[i - coin] != None: # table[4 - 3] = table[0] = [] != None ==> true
table[i] = table[i - coin][:] # table [1] = table [1 - 1][:]
table[i].append(coin) # table[1].append(1)
if table[-1] != None:
print '%d coins: %s' % (len(table[-1]), table[-1])
else:
print 'No solution possible'
| true |
b1ea1b4ae68aa83f2b2ad655d9208d8d3e752761 | yaoyu2001/LeetCode_Practice_Python | /DataStructure/dijkstra.py | 1,503 | 4.21875 | 4 | # From BFS to dijkstra calculate the nearest path in a graph (with weight)
# https://www.youtube.com/watch?v=9wV1VxlfBlI
import heapq
import math
graph = {
'A':{'B':5, 'C':1},
'B':{'A':5, 'C':2,'D':1},
'C':{'A':1, 'B':2,'D':4,'E':8},
'D':{'B':1, 'C':4,'E':3,'F':6},
'E':{'C':8, 'D':3},
'F':{'D':6}
}
def init_distance(graph, s):
distance = {s:0}
for vertex in graph:
if vertex !=s:
distance[vertex] = math.inf
return distance
def dijkstra(graph,s):
pqueue = list()
heapq.heappush(pqueue, (0, s))
seen = set()
parent = {s:None} # Find nearest path
distance = init_distance(graph,s)
while (len(pqueue) > 0):
pair = heapq.heappop(pqueue)
dist = pair[0]
vertex = pair[1]
seen.add(vertex) # Once a vertex be taken from a priority queue, mark it as "seen"
nodes = graph[vertex].keys() # All nodes connected with current vertex
for w in nodes:
if w not in seen:
if dist + graph[vertex][w] < distance[w]: # If a vertex which connected with current "vertex" hasn't seen, calculate the distance
heapq.heappush(pqueue, (dist + graph[vertex][w], w)) # Calculate distance, if it less then current distance, replace it.
parent[w] = vertex
distance[w] = dist + graph[vertex][w]
return parent, distance
# print(graph["A"])
parent,distance = dijkstra(graph, "A")
print(parent)
print(distance) | false |
eace2b0b2f54cd2207266c90bc8167af14b4801b | z0li627/Sprint-Challenge--Algorithms | /recursive_count_th/count_th.py | 549 | 4.15625 | 4 | '''
Your function should take in a single parameter (a string `word`)
Your function should return a count of how many occurences of ***"th"*** occur within `word`. Case matters.
Your function must utilize recursion. It cannot contain any loops.
'''
word = "ojndcthlhtwkencthth"
def count_th(word, i = 0, counter = 0):
if len(word) < 2:
return 0
if (word[i] + word[i+1]) == "th":
counter += 1
i += 1
else:
counter = counter
i += 1
return counter + count_th(word[i:])
print(count_th(word))
| true |
e8faf1d5181d77d3a77811571245ca68ef81f388 | SteveMinhDo/violentpython | /unixPassWord/hackPassword.py | 1,233 | 4.34375 | 4 | # 1. we have hash password, need to find the real password.
# 2. we need to create the dictionary
# 3. Dictionary need to be input to same crypto function
# 4. Compare output of our hash function to the hash password.
# 5. how is the design for user
# 6. user need to input the dictionary file and password file
# 7. Password file is in some format
import crypt
def testpass(cryptPass):
try:
dictFile = open("dic.txt")
salt = cryptPass[0:2]
for line in dictFile.readlines():
line = line.strip('\n')
password = crypt.crypt(line,salt)
if password == cryptPass:
print "[+] The password is " + password
return
except:
print "There is wrong dictionary file"
print "[-] Hmm, No password found."
return
def main():
try:
passFile = open("passwd.txt")
for line in passFile.readlines():
if ":" in line:
user = line.split(':')[0]
print "Cracking Password for user: " + user
cryptPass = line.split(':')[1].strip(' ')
testpass(cryptPass)
except:
print "No passwd file"
if __name__ == "__main__":
main()
| true |
ac925a669d64af1ff28119283814fba337a2cf56 | ITInfra-101/Python_practice_public_repo | /exercise_7_List_comprehension_pub.py | 771 | 4.34375 | 4 | #Let’s say I give you a list saved in a variable: a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100].
# Write one line of Python that takes this list a and
# makes a new list that has only the even elements of this list in it.
#Logic 2 list comprehension
a1 = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# User_input_number=int(input("Enter a number till which the list should be displayed : "))
# a12=a1[0:User_input_number]
# length_of_a1=len(a1)
b1 = [each_element for each_element in a1 if (each_element%2)==0]
c1 =[each_element for each_element in a1 if (each_element%2)!=0]
print("The whole big list is {} ".format(a1))
print("The list is made of even numbers of big list {} ".format(b1))
print("The list is made of odd numbers of big list {} ".format(c1))
| true |
2af86e21232d7584fdbb5f20a448da003ee5e58e | edagotti689/PYTHON-9-OOP-S | /9_super_use.py | 340 | 4.28125 | 4 | ## Using super we can call parent class methods
class One:
def __init__(self):
print('__init__ of One')
def add(self):
print(' One add is ')
class Two(One):
def add(self):
print(' Two add is ')
# super().add()
# ins2 = One()
# ins2.add()
ins = Two()
ins.add() | false |
ee559640dc2f9cf2ad59e31b66be1e994253e0aa | cy/llc-python | /morning_recap2.py | 445 | 4.125 | 4 | parsed = False
user_input = 0
while not parsed:
try:
user_input = int(raw_input("gimme a number:\n"))
parsed = True
except ValueError:
print "not a number, try again."
if user_input < 10 or user_input > 20:
print "your input is less than 10 or greater than 20"
elif user_input > 10 and user_input < 20:
print "your input is greater than 10 and less than 20"
else:
print "your input doesn't matter"
| true |
f030b84e56a5e0a8235da7bed62d6fa0fcf2afc9 | santanafelipe98/blastoff | /src/teste7.py | 605 | 4.15625 | 4 | """
### BlastOff - Teste de Lógica 7 ###
Descrição: Dada uma lista de números A[1,2,3,...] retorna somente os números pares
Autor: Felipe Santana
Data: 22/10/2021
"""
# filtra somente os números pares
def pares(lista_numeros):
somente_pares = []
for num in lista_numeros:
if num % 2 == 0:
somente_pares.append(num)
return somente_pares
# função main
def main():
numeros = [ 14, 5, 6, 7, 11, 20 ]
somente_pares = pares(numeros)
print(f'Lista de números: {numeros}')
print(f'Números pares: {somente_pares}')
if __name__ == '__main__':
main() | false |
2dea547c71139435f5e8e4935d4ead43683bb4d3 | Kushg02/CTSBoat | /AutonPreset.py | 1,199 | 4.28125 | 4 | # Import the modules.
import turtle
# Set the shape of the boat
turtle.shape('square')
# Set the color of the turtle.
turtle.color('red', 'black')
turtle.pencolor('red')
#Set Turtle Speed (Higher for sake of demo)
turtle.speed('25')
# 2) Mosquito Sweep of squarish body
for i in range(4):
turtle.forward(100)
turtle.left(90)
# 3) Mosquito Sweep of Odd shaped water body
turtle.clear()
turtle.speed('30')
numberOfSides = 5
degrees = 360 / numberOfSides
for x in range(numberOfSides):
turtle.forward(100)
turtle.left(degrees)
# 4) Spot Clean Mode 1 (Slower dissolving)
turtle.clear()
turtle.speed('20')
side = 10
for x in range(20):
turtle.forward(side)
turtle.left(90)
side += 20
# 4) Spot Clean Mode 2 (Fast dissolving)
turtle.clear()
turtle.penup()
turtle.speed('20')
turtle.home()
turtle.pendown()
angle = 20
for x in range(20):
turtle.circle(angle, 180)
angle += 20
print("yes")
# Sample of a more complicated shape
turtle.clear()
turtle.penup()
turtle.speed('10')
turtle.home()
turtle.pendown()
angle = 0
for x in range(6):
for x in range(3):
turtle.forward(100)
turtle.right(120)
turtle.left(120)
turtle.forward(100)
turtle.left(180)
angle += 30
| true |
7c59932796ac4e2deffa2fc694924d80dd25b265 | PriscillaRoy/Data-Structures | /PalindromeLinkedList.py | 1,299 | 4.15625 | 4 | class Node:
def __init__(self, val = None):
self.val = val
self.next = None
def print_data(self):
node = self
while node != None:
print(node.val)
node = node.next
def reverse_list(self):
node = self
head = Node(node.val)
node = node.next
while(node != None):
n = Node(node.val)
n.next = head
head = n
node = node.next
return head
def palindrome_check(self, nodeA):
nodeB = self
while(nodeA != None and nodeB != None):
if(nodeA.val != nodeB.val):
return False
nodeA = nodeA.next
nodeB = nodeB.next
return True
n0 = Node(5)
n1 = Node(6)
n2 = Node(7)
n3 = Node(8)
n0.next = n1
n1.next = n2
n2.next = n3
n0.print_data()
n4 = n0.reverse_list()
n4.print_data()
print("Checking for Palindrome")
if(n4.palindrome_check(n0)):
print("Yes Palindrome")
else:
print("Not Palindrome")
n0 = Node(1)
n1 = Node(4)
n2 = Node(4)
n3 = Node(1)
n0.next = n1
n1.next = n2
n2.next = n3
n0.print_data()
n4 = n0.reverse_list()
n4.print_data()
print("Checking for Palindrome")
if(n4.palindrome_check(n0)):
print("Yes Palindrome")
else:
print("Not Palindrome") | false |
094a482b64af5fd1fd28ded5ebb1a9731efe0f92 | francososuan/2-PracticePythonOrg | /15-ReverseWordOrder.py | 417 | 4.125 | 4 | def reverser(sentence):
sentence_list = sentence.split(" ")
reverse_list = []
for i in range(len(sentence_list)-1,-1,-1):
reverse_list.append(sentence_list[i])
return " ".join(reverse_list)
input_sentence = str(input("Please enter a sentence: "))
print(reverser(input_sentence))
def reverse_word(sentence):
return " ".join(sentence.split()[::-1])
print(reverse_word(input_sentence)) | true |
f5da9dae606bb8934b3e124c0eefa5681331b563 | sindetisarah/Python-conditionals | /condition.py | 540 | 4.1875 | 4 | number=int(input("Number:"))
if (number > 0):
print("number is positive","\n")
elif (number < 0):
print("number is negative","\n")
else:
print("number is zero","\n")
# Finding whether an year is a leap year
year=int(input("Enter year:"))
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
print(f"{year} is a leap year")
else:
print(f"{year} is not a leap year")
else:
print(f"{year}is not a leap year")
else:
print(f"{year}is not a leap year")
| false |
0d093de90b7a43d95d7a849cd07be834b3a79f26 | mohnoor94/ProblemsSolving | /src/main/python/string/is_unique.py | 484 | 4.1875 | 4 | """
Implement an algorithm to determine if a string has all unique characters.
- Cracking the coding interview, a book by Gayle Mcdowell (6th ed., q 1.1)
"""
def is_unique(string):
shown = set()
for c in string:
if c in shown:
return False
else:
shown.add(c)
return True
if __name__ == '__main__':
print(is_unique('hello'))
print(is_unique('world'))
print(is_unique('hello world'))
print(is_unique('hi world'))
| true |
507405c3be976888e01b0309b6a3b2aeb4a0c168 | mohnoor94/ProblemsSolving | /src/main/python/string/group_angarams.py | 883 | 4.15625 | 4 | """
Given an array of strings, group anagrams together.
Example:
- Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
- Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
Notes:
- All inputs will be in lowercase.
- The order of your output does not matter.
Problem Statement: https://leetcode.com/problems/group-anagrams/
"""
import collections
from typing import List
def group_anagrams(strings: List[str]):
"""
:type strings: List[str]
:rtype: List[List[str]]
"""
answer = collections.defaultdict(list)
a = ord('a')
for s in strings:
count = [0] * 26
for c in s:
count[ord(c) - a] += 1
answer[tuple(count)].append(s)
return answer.values()
if __name__ == '__main__':
print(group_anagrams(["eat", "tea", "tan", "ate", "nat", "bat"]))
| true |
7bd876b27f7e7c7c87e20a136b7291e9f1e733c4 | watson2017/usage-class | /car.py | 2,681 | 4.1875 | 4 | # ================================1.car 的父类================================
class Car():
def __init__(self, make, model, years):
"""make:生产商,model:型号,years:生产年限"""
self.make = make
self.model = model
self.years = years
self.odometer_reading = 0 # 设置一个参数,汽车跑的总里程数,初始值为0,无需外界传入
def get_descriptive_name(self):
long_name = str(self.years) + ',' + self.model + ',' + self.make
return long_name.title()
def read_odometer(self):
# self.odometer_reading = 23
print("this car has " + str(self.odometer_reading) + " miles on it.")
def update_odometer(self, newmiles):
"""
将里程表读数设定为指定的值
禁止将里程表的读数往回拨
"""
# self.odometer_reading = newmiles
if self.odometer_reading <= newmiles:
self.odometer_reading = newmiles
else:
print("you can not rollback an old meter !")
# ======================2.子类的创建======================================
# 创建子类时,父类必须包含在当前文件中,且位于子类前面
# 创建子类的实例时,Python首先需要完成的任务是给父类的所有属性赋值
# super()是一个特殊函数,帮助Python将父类和子类关联起来
# =========================================================================
class ElectricCar(Car): # 括号中object表示从哪里继承父类
def __init__(self, make, model, years):
super().__init__(make, model,
years) # 继承父类的属性(其中的方法),与Python2 版本中写法不一样
self.battery = Battery(66) # 调用Battery类
def read_odometer(self):
"""重写父类的方法:在子类中定义一个与要重写的父类方法同名。这样,Python就不会继承这个父类方法"""
print("elc car not need read miles.")
# ============================3.将实例用作属性==================================
# 将类的一部分作为一个独立的类提取出来,可以将大型类拆分成多个协同工作的小类
# 如下方的Battery实例可以用作ElectricCar类的一个属性
# ==============================================================================
class Battery():
def __init__(self, battery_size=100):
"""初始化电池的容量"""
self.battery_size = battery_size
def describe_battery(self):
"""描述电池剩余量"""
print("this electriccar has a " + str(self.battery_size) +
" -kWh battery.")
| false |
33b8f62680b0d84a5ff4bfa0266cccedb29c7e51 | PrakalpTiwari137/Python | /Using Python to Access Web Data/w6a1.py | 1,667 | 4.34375 | 4 | # QUESTION
'''
Extracting Data from JSON
In this assignment you will write a Python program somewhat similar to http://www.py4e.com/code3/json2.py. The program will prompt for a URL, read the JSON data from that URL using urllib and then parse and extract the comment counts from the JSON data, compute the sum of the numbers in the file and enter the sum below:
We provide two files for this assignment. One is a sample file where we give you the sum for your testing and the other is the actual data you need to process for the assignment.
Sample data: http://py4e-data.dr-chuck.net/comments_42.json (Sum=2553)
Actual data: http://py4e-data.dr-chuck.net/comments_481552.json (Sum ends with 87)
You do not need to save these files to your folder since your program will read the data directly from the URL. Note: Each student will have a distinct data url for the assignment - so only use your own data url for analysis.
Data Format
The data consists of a number of names and comment counts in JSON as follows:
{
comments: [
{
name: "Matthias"
count: 97
},
{
name: "Geomer"
count: 97
}
...
]
}
The closest sample code that shows how to parse JSON and extract a list is json2.py. You might also want to look at geoxml.py to see how to prompt for a URL and retrieve data from a URL.
'''
# ANSWER
import urllib.request, urllib.parse, urllib.error
import json
url = input('Enter url: ')
# url = 'http://py4e-data.dr-chuck.net/comments_481552.json'
uh = urllib.request.urlopen(url)
data = uh.read()
info = json.loads(data)
lst = info['comments']
val = 0
for ele in lst:
val = val + int(ele['count'])
print(val)
| true |
079c14f54de8442237c8d041d50c28f7699985da | alef123vinicius/PythonDevelopment | /exercicios/exercicio_01.py | 612 | 4.375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 11 15:28:46 2021
@author: alef
"""
""" Exercicio 01
1. Implementar duas funções:
- Uma que converta temperatura em graus Celsius para Fahrenheit
- Outra que covnerta temperatura em graus Fahrenheit para Celsius
Formula:
F = 9/2 . C + 32
C = (f-32)/1.8
"""
def celsius_for_fahrenheit(C):
return (9/5) * C + 32
def fahrenheit_for_celsius(F):
return (F - 32) / 1.8
print(celsius_for_fahrenheit(0))
print(fahrenheit_for_celsius(32))
print(celsius_for_fahrenheit(55))
print(fahrenheit_for_celsius(131)) | false |
e2438cd253be7b42dfeb85f93311289beb6de523 | ksreddy1980/test | /General/Nthlargest_from_list.py | 523 | 4.125 | 4 | l = list(input("enter the list of elements:"))
n = int(input("enter the which largest element:"))
def largest(l):
n = len(l)
max = 0
for i in range(n):
if (max < int(l[i])) :
max = int(l[i])
return max
def nthlargest(l, n,max):
n1 = len(l)
nmax = 0
for i in range(n1):
if(int(l[i]) > nmax and int(l[i]) < max):
nmax = int(l[i])
if (n <= 2):
return nmax
else:
return nthlargest(l, n-1, nmax)
print(nthlargest(l, n+1,max))
| false |
14e83dcaf65c3049c754f0160e75f7e4e85fc7e1 | ksreddy1980/test | /General/Class_method.py | 1,435 | 4.21875 | 4 | class employee:
num_of_emp=0
pay_raise= 1.05
def __init__(self,fname,sname,pay):
self.first= fname
self.second= sname
self.salary= pay
self.email=fname +"."+sname +"@"'company.com'
employee.num_of_emp +=1
def hike(self):
self.salary= int(self.salary) * self.pay_raise
#self.salary= self.salary* employee.pay_raise
return self.salary
@classmethod
def set_raise_amount(cls, amount):
cls.pay_raise= amount
@classmethod
def from_string(cls,str):
fname,sname,pay= str.split('-')
return cls(fname,sname,pay)
employee.set_raise_amount(6)
print('Number of employees:' ,employee.num_of_emp)
str1="Rajesh-K-100000"
str2="Sagar-koteru-90000"
str3="John-Taylor-130000"
emp1=employee.from_string(str1)
emp2=employee.from_string(str2)
emp3=employee.from_string(str3)
print('Number of employees:' ,employee.num_of_emp)
emp2.pay_raise= 3
print('employee1 :')
print(emp1.first)
print(emp1.second)
print(emp1.salary)
print('salary after hike:', emp1.hike())
print(emp1.email,"\n")
print('employee2 :')
print(emp2.first)
print(emp2.second)
print(emp2.salary)
print( 'salary after hike:',emp2.hike())
print(emp2.email,"\n")
print('employee3 :')
print(emp3.first)
print(emp3.second)
print(emp3.salary)
print('salary after hike:',emp3.hike())
print(emp3.email,"\n") | false |
54e8a8b3101b365b1a9b8ba81eda1b1652581324 | smithp0022/CTI110 | /P3HW2_MealTipTax_Smith.py | 1,882 | 4.3125 | 4 |
# Meal Tip Tax Calculator
# 12 FEB 2019
# CTI-110 P3HW2 - Meal Tip Tax Calculator
# Patrick Smith
print("")
# input the total meal amount in $.
meal_amount = float(input("Enter the meal amount: $"))
# Ask the user to provide tip amount in 15, 18 , or 20.
tip_amount = input("What amount of tip do you wish to consider?: ")
# Define tip variables.
tip_1 = "15"
tip_2 = "18"
tip_3 = "20"
# Calculate the sales tax .07
tax = meal_amount * .07
# Calculate the tip using meal_amount* 0.15, 0.18, & 0.20.
tip_amount1 = meal_amount * .15
tip_amount2 = meal_amount * .18
tip_amount3 = meal_amount * .20
# Calculate the total cost of the meal_amount plus the tip_amount
total_cost1 = meal_amount + tax + tip_amount1
total_cost2 = meal_amount + tax + tip_amount2
total_cost3 = meal_amount + tax + tip_amount3
# Display all totals for a meal.
if tip_amount == tip_1:
print("\nMeal amount is: $",format(meal_amount,",.2f"),sep="")
print("15% is $",format(tip_amount1,",.2f"),sep="")
print("tax is $",format(tax,".2f"),sep="")
print("total meal cost is $", format(total_cost1, ",.2f"),sep="")
elif tip_amount == tip_2:
print("\nMeal amount is: $",format(meal_amount,",.2f"),sep="")
print("18% is $", format(tip_amount2,",.2f"),sep="")
print("tax is $",format(tax,".2f"),sep="")
print("total meal cost is $", format(total_cost2, ",.2f"),sep="")
elif tip_amount == tip_3:
print("\nMeal amount is: $",format(meal_amount,",.2f"),sep="")
print("20% is $", format(tip_amount3,",.2f"),sep="")
print("tax is $",format(tax,".2f"),sep="")
print("total meal cost is $", format(total_cost3, ",.2f"),sep="")
# Error message if other than 15%, 18%, or 20% is entered.
else:
print( "\nError! You must choose 15%, 18%, or 20% only!" )
input("\nPress the 'Enter Key' to exit.")
| true |
4d112d6c1b913b9669e2a4fc064d473d4194dfd7 | eogiesoba/Python_Practice | /DataScience/Python_Beginner/4_NumToFloat.py | 1,225 | 4.40625 | 4 | #You now have a list of lists assigned to nested_list, where each inner list contains string elements.
#The second element (the estimated number of people with that name) in each list is a decimal value that you should convert to a float.
#By converting these values to floats, you'll be able to perform computations on them and analyze the data.
print(nested_list[0:5])
numerical_list = []
for x in nested_list:
name = x[0] #this will assign the value of the element at index 0 of in x to the variable name
value = float(x[1]) #This will convert the string into a float and assign that value the variable value
numerical_list.append([name,value]) # This will append the list into the list numerical_list. Hence list of lists.
print(numerical_list[0:4])
#---------------------------------------------------------------------------------------------------->
#The data set contains first names shared by at least 100 people.
#Let's limit it those shared by at least 1,000 people.
# The last value is ~100 people
numerical_list[len(numerical_list)-1]
thousand_or_greater = []
for x in numerical_list:
if x[1] >= 1000:
thousand_or_greater.append(x[0])
print(thousand_or_greater)
| true |
905933ec3c097c5b786f3687a50e04de266b9c0a | subbiahs84/LearnPython | /functions_Factorial.py | 439 | 4.25 | 4 | def fact(n):
result = 1
for i in range(1,n+1):
result = result*i
return result
n = int(input("Enter the number to get factorial-"))
factValue = fact(n)
print("Using FOR loop, Factorial value for the {} is {}".format(n, factValue))
#Factorial using recursion
def factRecursion(n):
if(n==0):
return 1
return n*factRecursion(n-1)
result = factRecursion(n)
print("Factorial using recursion - ", result)
| true |
7d88d5146671baa800abc2abc0b0c355dae9757a | subbiahs84/LearnPython | /MultiThread.py | 401 | 4.125 | 4 | from threading import Thread
from time import sleep
class Hello(Thread):
def run(self):
for i in range(5):
print("Hello")
sleep(1)
class Hi(Thread):
def run(self):
for i in range(5):
print("Hi")
t1 = Hello();
t2 = Hi();
t1.start()
t2.start()
#To make main thread to wait until to complete the T1 and T2
t1.join()
t2.join()
print("Bye") | true |
6aa0260325895f2b257e80bf7f6f037b0b99e6da | subbiahs84/LearnPython | /functions_ListToFunction.py | 456 | 4.15625 | 4 | from array import array
numArray = array("i", [])
n = int(input("Enter the number of elements "))
for i in range(n):
value = int(input("Enter the array value "))
numArray.append(value)
def countEvenOdd(numList):
odd = 0
even = 0
for n in numList:
if n%2==0:
odd+=1
else:
even+=1
return odd, even
odd, even = countEvenOdd(numArray)
print("Number of odd - {}, even - {}".format(odd,even)) | true |
ef9f96bcbbaf8f2f35dace7170fd3f29d9d32541 | Arlyxs/PythonOnline | /Lessons/MyWrks/Aliens_OOP/PolyMorphism/Operator_Overloading.py | 1,163 | 4.125 | 4 | class Student:
def __init__(self, m1, m2):
self.m1 = m1
self.m2 = m2
# *1
def __add__(self, other):
m1 = self.m1 + other.m1
m2 = self.m2 + other.m2
s3 = Student(m1,m2)
return s3
# *3
def __gt__(self, other):
r1 = self.m1 + self.m2
r2 = other.m1 + other.m2
if r1 > r2:
return True
else:
return False
'''
# *4
def __str__(self):
return self.m1, self.m2
'''
# *5
def __str__(self):
return '{} {} '.format(self.m1, self.m2)
s1 = Student(58, 69)
s2 = Student(60, 65)
# *2
s3 = s1 + s2
print(s3.m2)
if s1 > s2:
print('s1 wins')
else:
print('s2 wins')
print(s1.__str__())
''' *1 to overload the built in method of add so that s1 and s2 may be added we must create our own method for __add__
*2 when it is added our method overloads the built in method
*3 this is our comparator overload function
*4 overides the default string method and returns values that we define if we use the __str__() method in the print statement
*5 uses a format to print the output of the object
''' | false |
2d5a44a99e853b2669f7c1744629fff230b80d80 | anujmshrestha/Python_Basics | /Objects and Classes/Docstring.py | 975 | 4.34375 | 4 | class Account:
"""Class to represent Account
Attributes: It keeps record of all the attributes.
name(char):the name of the client
balance(float): the balance of the client
Methods:
withdraw()
deposit()
"""
def __init__(self, name, balance):
"""initmethod of Account class
This is the initialie method of the Account class which is automated"
Args:
name(char): initialises the name attributes
balance(float): it initialisee the balance attributes.
"""
self.name = name
self.balance = balance
#help(Account)
print(Account.__doc__)
#following line gives the doc of the init method.
print(Account.__init__.__doc__)
Account.__init__.__doc__= """
This is the another method of giving the documentation.
"""
help(Account) | true |
ec33f29f87eac2604b9438dc9feeb0116a4994ee | anujmshrestha/Python_Basics | /Database/checkdb.py | 536 | 4.125 | 4 | import sqlite3
con = sqlite3.connect("contacts.sqlite")
#We can check the schema. and attack by followin
name=input("Enter the name")
#con=sqlite3.connect("contacts.sqlite3")
#for row in con.execute("select * from contacts where name=?",(name,)):
for row in con.execute("select * from contacts where name like ?", (name,)): #(name,) Parameter sustitution.and ? is place holder
print(row)
#for row in con.execute("select *from sqlite_master"):
"""for row in con.execute("select * from contacts"):
print(row)
"""
con.close()
| true |
06363e0d57a596f49feac0a64829bccc9f58804a | jdst103/python-basic | /Exercises/exercise_101_input_basic.py | 643 | 4.15625 | 4 | #create a litle program that ask a user for the following details:
#- namne
#- hieght
#-fav colour
#- a secret number
#capture these inputs
#print a tailored welcome message to the user
#print other details it gathered, except the secret of course
# hitn, think about casting your datatype.
print("hello, what is your name?")
name = input()
print(f"hello {name}, what is your hieght?")
height = input()
print(f"wow !! Very tall {name}, what is your favourite colour?")
colour = input()
print(f"{colour}? interesting colour!")
print(f"{name}, what is your secret number?")
number = input()
print(f"{name}, i''ll keep it a secret for you!")
| true |
21cfe7db5d2e86622608f7f5ce8144835f54d830 | jdst103/python-basic | /for_loops_108.py | 1,142 | 4.15625 | 4 | import time
# for loops
# iterations!
# syntax
# for <placeholders> in <iterable>:
#block of code
# indented lines are part of this block
cars = ['skoda felecia fun', 'Mustang Boss 429', 'Fiat 500', 'Jaguar 420g', 'Aston Martin Vanquish']
#for x in cars:
# print(x)
# time.sleep(1)
# print('still in the block')
#for x in cars:
# print(x)
# time.sleep(1)
#for car in cars:
# print(car)
# time.sleep(1)
#iterating over a dictionary
student1 = {
'name': 'Arya Stark',
'stream': 'Many faces',
'grade': '10'
}
#gives key
#for x in student1:
# print(x)
#print(student1['name'])
#for key in student1:
# print(key)
#for key in student1:
# print(key) # this is each individual key of the dictionnary
# print(student1)# this is the dictionary
# print(student1[key]) # we can use the dictionary + keys to get the values
# iterate over the student1
# i want the output to be
# -> 'name is Arya Stark'
# -> 'stream is Many Faces'
for key in student1:
print(key.capitalize(), 'is ' + student1[key])
for key in student1:
print(f"{key} is {student1[key]}")
# -> 'stream is Many Faces'
| true |
59e08738cb9c717467a93cae8362e3d1021ee222 | jdst103/python-basic | /controlflow_107.py | 1,148 | 4.125 | 4 | # Control flow
# if statements
# Control where the code will execute. Depending on the assertions.
# An assertion/condition is something that returns True or False
# notes:
# block of code - refers to a consecutive lines of code, that are indented and
#will run together. Block exist inside if statments and while loops and other functions.
# in simple words: its a specific piece of code that will run in a specific time.
# # # Syntax
# if <condtion>:
# # block of code
# elif <conditionL:
# # block of code
#else:
# # block of code
#weather = 'rainy and stormy'
#if weather == 'rainy':
# print('take umbrella!')
# print("I'm still in the block of code aswell")
#elif weather == 'stormy':
# print('take rain coat')
#elif 'stormy' in weather and 'rainy' in weather:
# print('stay ay home')
#else:
# print('Take sunglasses')###
weather = 'rainy and stormy'
if 'stormy' in weather and 'rainy' in weather:
print('stay ay home')
elif weather == 'rainy':
print('take umbrella!')
elif weather == 'stormy':
print('take rain coat')
else:
print('Take sunglasses')
#print("I'm outside and always run :D")
| true |
09d45f573a6357ce35688c9904444e5ebb41b7eb | hgreen-akl/ProjectEuler | /Python/Problem 7.py | 888 | 4.1875 | 4 | # By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
# What is the 10 001st prime number?
number = 7
def is_prime(n) :
if (n < 2):
return False
elif (n==2):
return True
elif (n==3):
return True
else:
for x in range(2,n//2):
if(n % x==0):
return False
return True
def get_nth_prime(x):
"""[Obtains the nth prime number based on a function that is prime]
Arguments:
x {[int]} -- [the nth prime number wanted]
"""
number = 0
prime_list = []
while len(prime_list) <= x:
if is_prime(number):
prime_list.append(number)
number += 1
else:
number +=1
return prime_list[-1]
get_nth_prime(5) # this should be 11
get_nth_prime(6) # this should be 13
get_nth_prime(10001) | true |
3333e1bb2ed7dfff9c70bb2f6d3332209e41dc96 | Mary-Rudyk/new | /12_task.py | 1,438 | 4.34375 | 4 | #Напишите программу-калькулятор, которая поддерживает следующие операции: сложение, вычитание,
#умножение, деление и возведение в степень. Программа должна выдавать сообщения об ошибке и
#продолжать работу при вводе некорректных данных, делении на ноль и возведении нуля в
#отрицательную степень.
def summ(x, y):
return x+y
def dif(x, y):
return x-y
def mult(x, y):
return x * y
def div(x, y):
return x / y
def degr(x, y):
return x ** y
def calc():
while True:
try:
x = int(input("Write some X "))
y = int(input("Write some Y "))
except ValueError:
print("Wrong type x or y")
act = input("Write some action (+ - * / ^) ")
if act == "+":
print(summ(x, y))
elif act == "-":
print(dif(x, y))
elif act == "*":
print(mult(x, y))
elif act == "/":
try:
print(div(x, y))
except ZeroDivisionError as er:
print(er)
elif act == "^":
try:
print(degr(x, y))
except ZeroDivisionError as er:
print(er)
calc()
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.