blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
dbf214cb3a1ce05dca825676975b49051c1bf149 | Abhilas-007/python-practice | /codes/recursion_factorial.py | 363 | 4.21875 | 4 | def fact(num,res):
result =res*num
if num>1:
fact(num-1,result)
else:
print(result)
def fact2(num):
if(num==0):
return 1
return num*fact2(num-1)
fact(int(input("Enter a number"
" to find its factorial")),1)
res=fact2(int(input("Enter a number"
" to find its factorial")))
print(res) | true |
15dcb43e2f1bd960d3684c2f5cd218a9eb026556 | lamtharnhantrakul/coding-interview-bootcamp | /sortAlmostSortedArray.py | 1,115 | 4.1875 | 4 | import heapq
import itertools
array = [3,-1,2,6,4,5,8]
def merge_almost_sorted_array(sequence, k):
result = []
min_heap = []
for x in itertools.islice(sequence, k):
heapq.heappush(min_heap, x)
for x in sequence[k:]:
min_element = heapq.heappushpop(min_heap, x)
result.append(min_element)
while min_heap:
result.append(heapq.heappop(min_heap))
return result
def merge_almost_sorted_array2(sequence, k):
'''
Time complexity is nlog(k). For every n items, we do logk operations (heap characteristic)
'''
result = []
min_heap = []
# add first k=3 elements to heap
for x in sequence[:k]:
heapq.heappush(min_heap, x)
# progress through the sequence after the first k items
for x in sequence[k:]:
min_element = heapq.heappushpop(min_heap, x)
result.append(min_element)
# sequentially pop the remaining items in the heap
while min_heap:
result.append(heapq.heappop(min_heap))
return result
print(merge_almost_sorted_array(array,3))
print(merge_almost_sorted_array2(array,3))
| false |
91bfc8a4056239c0b810ecd8289546067348456a | yashsharma15/tathastu_week_of_code | /day4/program2.py | 439 | 4.34375 | 4 | n = int(input("Enter size of list:"))
m = int(input("Enter size of each Tuple :"))
l = []
for i in range (0,n):
print("Enter elements in Tuple :",i+1)
T = []
for j in range (0,m):
a = int(input("Enter the element"+str(j+1)+":"))
T.append(a)
l.append(tuple(T))
p = int(input("Enter the Nth index about which you want to sort the list:"))
l.sort(key = lambda x : x[p])
print ("After sorting tuple list by Nth index sort:",l)
| false |
a53dd96980dcbdc587f9706281f5083a08366505 | darpan45/100DaysofCode | /Day2/day2.py | 1,919 | 4.21875 | 4 | ##String
# print("Hello"[0])
# print("Hello"[4])
# print("123"+"456")
# #Integer
# print(123)
# print(123+456)
##Float
# print(12.3+45.6)
##Boolean
# value1=True
# value2=False
##Type Conversion and Types
# name=len(input("What is your name ?"))
# new_name=str(name)
# print("My name has " + new_name + " characters .")
##Task 1
##Adding the sum of two digit number
# a=input("Enter a two digit number :\n")
# b=int(a[0])+int(a[1])
# print(b)
##Arithmetic Operation
# print(3+1)
# print(4-2)
# print(4*6)
# print(10/2)
# print(10**2)
# #It follow PEMDAS Rule
# ()
# **
# * / #for both these ,the leftmost will take place first
# + - #for both these ,the leftmost will take place first
##BMI Calculator
##BMI =weight/(height*height)
# weight=float(input("Enter your weight in kgs : "))
# height=float(input("Enter your height in m : "))
# bmi=weight/height**2
# print(round(bmi,2))
##F string
# name="Darpan"
# height=1.71
# print(f"my name is {name} and my height is {height}.")
##Tim Urban Life in Weeks
# age=int(input("What is your current age ?"))
# total_days=90*365
# total_weeks=90*52
# total_months=90*12
# days_remaining=total_days-(age*365)
# weeks_remaining=total_weeks-(age*52)
# months_remaining=total_months-(age*12)
# print(f"You have {days_remaining} days, {weeks_remaining} weeks and {months_remaining} months remaining .")
# #Tip Calculator
print("Welcome to the tip Calculator .")
tot_bill=float(input("What was the total Bill ? $ "))
#print(tot_bill)
perc_tip=int(input("What percentage tip would you like to give ? 10 12 or 15 ? "))
#print(perc_tip)
no_of_people=int(input("How many people to split the bill ?"))
#print(no_of_people)
result=round(float((tot_bill + (tot_bill*perc_tip/100))/no_of_people),2)
print(f"Each person should pay : $ {result}")
print("CONGRATULATIONS DAY2 COMPLETE!!!!!!!!!!!") | true |
675bb3891c7ea8decfb65838657b1d773d69821f | darpan45/100DaysofCode | /Day12/day12.py | 1,430 | 4.125 | 4 | #Global and Local scope
#Global Variable
# apples=12
# def add_apple():
# #local variable
# apples=13
# print(apples)
# add_apple()
# print(apples)
# There is no Block scope in Python (while,for,if)
#Modifying Global Scope
# apples=12
# def add_apple():
# global apples
# apples+=1
# print(apples)
# add_apple()
# print(apples)
# apples=12
# def add_apple():
# # print(apples)
# return apples+1
# apples=add_apple()
# print(apples)
#GUESS THE NUMBER GAME
import random
print("Welcome to the Number guessing game!")
print("I'm thinking of a number between 1 to 100 ")
def guess_the_number(attempts):
print(f"You have {attempts} attempts remaining to guess the number ")
for i in range(attempts):
guess=int(input("Make a guess : "))
if guess == number:
print("Congrats!! You have guessed the number correctly 🏆🏆")
elif guess > number:
print("Choose a smaller number")
elif guess< number:
print("Choose a greater number")
if guess !=number:
print("You Lose .You have run out of your lives .")
print(f"The number was {number}.")
difficulty=input("Choose a difficulty. Type 'easy' or 'hard' : ")
number=random.randint(1,101)
attempts=0
if difficulty == "easy":
guess_the_number(8)
elif difficulty == "hard":
guess_the_number(5)
| true |
6ac914c01922208058570ac4678956208eaab4a0 | trantrikien239/exercise | /odd_or_even_2.py | 537 | 4.15625 | 4 | def getInt(text):
try:
intInput = input(text)
intInput = int(intInput)
if intInput <= 0:
raise
return intInput
except Exception:
print("Input must be a positive integer, please try again")
return getInt(text)
# Ask for input
check = getInt("Give me another positive integer to check: ")
num = getInt("Give me a positive integer to divide it by: ")
if check % num == 0:
print("check divide evenly into num")
else:
print("check does not devide evenly into num")
| true |
e3672e4a920bb34200b7e2806cc34c196538930b | WoodyAllen2000/MIT6.0001-pset | /ps1/ps1b.py | 569 | 4.1875 | 4 | annual_salary = float(input('Enter your annual salary: '))
portion_saved = float(input('Enter the percentage of your salary to save, as a decimal: '))
total_cost = float(input('Enter the cost of your dream house: '))
portion_down_payment = 0.25
current_savings = 0
r = 0.04
monthly_salary = annual_salary/12
number_months = 0
mr = r/12
payment = portion_down_payment*total_cost
while current_savings < payment:
current_savings = current_savings*(1 + mr) + monthly_salary*portion_saved
number_months += 1
print('number of months', number_months)
| true |
aaa607872f3a02a0660e9bbb9784c619bdaee10a | SACHSTech/ics2o-livehack1-practice-daniellen23 | /minutes_days.py | 508 | 4.125 | 4 | """
Name: minutes_days.py
Purpose: This program will convert user inputted amount of minutes into days, hours and minutes.
Author: Nguyen.D
Created: 2021-02-11
"""
minutes = int(input("Enter amount of minutes: "))
days = minutes / 1440
#days = 1440 minutes
#hours = 60 minutes
remaining_hours = minutes % 1440
new_hours = remaining_hours / 60
new_minutes = minutes % 60
print("Number of days: ", (int(days)))
print("Number of hours: ", (int(new_hours)))
print("Number of minutes: ", (int(new_minutes)))
| true |
ed0094eb38897962f690202ef4134ce94756ba77 | rjoshmatthews/cs1400 | /Homework/Exercises/Exercise 6/Exercise 6.5.py | 555 | 4.125 | 4 | import math
"""
Robert Matthews
CS 1400
Section 002
Exercise 6
5. Chapter 6, Programming Exercises #3, pg 206. Write the indicated functions, solve the problem and submit your source
code as your answer.
"""
# surface area of a sphere is 4pir^2
radius = 10
def sphere_area(a_radius):
area = 4 * math.pi * a_radius**2
return area
print("{0:.2f}".format(sphere_area(radius)))
# volume of a sphere is 4/3πr^3
def sphere_volume(a_radius):
volume = 4 / 3 * (math.pi * a_radius**3)
return volume
print("{0:.2f}".format(sphere_volume(radius)))
| true |
fa7623140c84073f2329dba0e03e352d77c6a644 | qiyangjie/Udacity-Data-Structures-Algorithm-Projects | /project2/problem_2.py | 1,306 | 4.34375 | 4 | import os
def find_files(suffix, path):
"""
Find all files beneath path with file name suffix.
Note that a path may contain further subdirectories
and those subdirectories may also contain further subdirectories.
There are no limit to the depth of the subdirectories can be.
Args:
suffix(str): suffix if the file name to be found
path(str): path of the file system
Returns:
a list of paths
"""
b_list = []
dir_list = os.listdir(path)
for direction in dir_list:
full_direction = os.path.join(path, direction)
if os.path.isfile(full_direction):
if full_direction.endswith(suffix):
b_list.append(full_direction)
else:
b_list = b_list + find_files(suffix, full_direction)
return b_list
if __name__ == '__main__':
# test 1
print(find_files('.c', 'testdir')) # ['testdir\\subdir1\\a.c', 'testdir\\subdir3\\subsubdir1\\b.c', 'testdir\\subdir5\\a.c', 'testdir\\t1.c']
print(find_files('.h', 'testdir')) # ['testdir\\subdir1\\a.h', 'testdir\\subdir3\\subsubdir1\\b.h', 'testdir\\subdir5\\a.h', 'testdir\\t1.h']
# test 2, no python files
print(find_files('.py', 'testdir')) # []
# test 3
print(find_files('.py', 'testdir2')) # FileNotFoundError
| true |
2e24ee541a4a12facc6504d9563f3c4fd3587d47 | reshinto/useless_apps | /rename_files.py | 2,865 | 4.4375 | 4 | """
A simple script for renaming file or folder name(s).
Features:
1) replace character(s) with new character(s)
2) add new character(s) before or after the filename
3) delete character(s) in the filename
4) all file or folder name(s) within the same location will be renamed
5) set path location to rename file or folder name(s) remotely
Tested on: OSX(mojave)
TODO: add select option for renaming single or multiple filename(s)
"""
import argparse
import os
def get_arguments():
"""
Options:
-o must include -n or -d
-n must include -o
-d does not require argument to delete character (must also have -o)
-ap add new prefix character (stand-alone)
-as add new suffix character (stand-alone)
-p change and set path (optional)
e.g.: python rename.py -o old_char -n new_char -p /usr/local
If replace space character, use a single \ followed by a space character
e.g.: python rename.py -o \ -n new_char
"""
parser = argparse.ArgumentParser()
parser.add_argument("-o", "--old", dest="old_character",
help="old character(s) of file/folder names to remove")
parser.add_argument("-n", "--new", dest="new_character",
help="new character(s) of file/folder names to add")
# Need to set action="store_true" to work without arguments
parser.add_argument("-d", "--del", dest="delete", action="store_true",
help="delete old character(s) from file/folder names")
parser.add_argument("-ap", "--prefix", dest="prefix",
help="add new prefix character to file/folder names")
parser.add_argument("-as", "--suffix", dest="suffix",
help="add new suffix character to file/folder names")
parser.add_argument("-p", "--path", dest="path",
help="set path for app to rename files/folders")
_args = parser.parse_args()
return _args
class Rename:
def __init__(self):
self.args = get_arguments()
if self.args.path:
os.chdir(f"{self.args.path}")
self.file_list = os.listdir()
def rename(self):
for file in self.file_list:
if self.args.delete:
new_filename = file.replace(self.args.old_character, "")
elif self.args.prefix:
new_filename = self.args.prefix + file
elif self.args.suffix:
new_filename = file + self.args.suffix
elif self.args.old_character and self.args.new_character:
new_filename = file.replace(self.args.old_character,
self.args.new_character)
os.rename(file, new_filename)
def main():
run = Rename()
run.rename()
print("Renaming of file/folder names completed!")
if __name__ == "__main__":
main()
| true |
b97032c77bdf02ae3c59c8193a589d1211c346ee | isha-03/python-course | /Programs/005_Calculator.py | 1,226 | 4.15625 | 4 | def calculator(num1, num2, operation):
result = 0
if operation == "+" or operation.lower() == "a":
result = sumCal(num1, num2)
elif operation == "-" or operation.lower() == "s":
result = subCal(num1, num2)
elif operation == "*" or operation.lower() == "m":
result = mulCal(num1, num2)
elif operation == "/" or operation.lower() == "d":
result = divCal(num1, num2)
elif operation == "**" or operation.lower() == "p":
result = powerCal(num1, num2)
print(result)
print("\n--------------------------------------------\n")
def sumCal(a, b):
return "Sum = " + str(a + b)
def subCal(a, b):
return "Subtraction = " + str(a - b)
def mulCal(a, b):
return "Multiplication = " + str(a * b)
def divCal(a, b):
return "Quotient = " + str(a / b) + "\nRemainder = " + str(a % b)
def powerCal(a, b):
return "Power = " + str(a ** b)
if __name__ == '__main__':
allowedOperations = ["a", "s", "m", "d", "p", "A", "S", "M", "D", "P", "+", "-", "*", "/", "**"]
while True:
operation = input("Enter operation: ")
if operation not in allowedOperations:
break
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
calculator(num1, num2, operation)
print("\nBYE")
| false |
a1d6bb634d81488f12621a032844298e83e4e84b | mohamedabdelbary/algo-exercises | /python/queue_using_stacks.py | 2,206 | 4.34375 | 4 | from stack import Stack
class Queue(object):
"""
Implement a queue using two stacks. Recall that a queue is a FIFO (first-in, first-out) data structure
with the following methods: enqueue(element), which inserts an element into the queue, and dequeue(),
which removes it.
"""
def __init__(self):
self._tmp_stack = Stack()
self._queue_stack = Stack()
self._count = 0
def enqueue(self, element):
"""
- If the queue stack is empty, then empty the tmp stack
into it.
- Otherwise push the new element onto the tmp stack
"""
self._tmp_stack.push(element)
if self._queue_stack.is_empty():
self._move_stack(self._tmp_stack, self._queue_stack)
self._count += 1
def dequeue(self):
"""
Always dequeue from the queue stack
"""
if self._queue_stack.is_empty():
if not self._tmp_stack.is_empty():
self._move_stack(self._tmp_stack, self._queue_stack)
self._count -= 1
return self._queue_stack.pop()
else:
return None
else:
self._count -= 1
return self._queue_stack.pop()
@property
def head(self):
if not self._queue_stack.is_empty():
return self._queue_stack.peek()
elif not self._tmp_stack.is_empty():
self._move_stack(self._tmp_stack, self._queue_stack)
return self._tmp_stack.peek()
else:
return None
@property
def count(self):
return self._count
@staticmethod
def _move_stack(from_, to):
while not from_.is_empty():
to.push(from_.pop())
if __name__ == '__main__':
q = Queue()
q.enqueue(10)
q.enqueue(4)
assert q.head == 10
q.enqueue(7)
assert q.dequeue() == 10
assert q.count == 2
q.enqueue(-1)
assert q.head == 4
assert q.dequeue() == 4
assert q.count == 2
assert q.head == 7
q.dequeue()
assert q.count == 1
assert q.dequeue() == -1
assert q.count == 0
assert q.dequeue() is None
assert q.head is None
assert q.count == 0
| true |
5809da86fd0a9a81c79a3973c171155047908579 | talesbear/Analytics_with_python | /firt_script.py | 889 | 4.3125 | 4 | #!/usr/bin/env python3
from math import exp, log, sqrt
print("Output #1: I'm excited to learn Python.")
# 두 수를 더한다.
x = 4
y = 5
z = x + y
print("Output #2: Four plus five equals {0:d}.".format(z))
# 두 리스트를 더한다.
a = [1, 2, 3, 4]
b = ["first", "second", "third", "fourth"]
c = a + b
print("Output #3: {0}, {1}, {2}".format(a, b, c))
x = 9
print("Output #4: {0}".format(x))
print("Output #5: {0}".format(3**4))
print("Output #6: {0}".format(int(8.3)/int(2.7)))
print("Output #7: {0:.3f}".format(8.3/2.7))
y = 2.5 * 4.8
print("Output #8: {0:.1f}".format(y))
r = 8/float(3)
print("Output #9: {0:.2f}".format(r))
print("Output #10: {0:.2f}".format(8.0/3))
print("Output #11: {0:.4f}".format(exp(3)))
print("Output #12: {0:.2f}".format(log(4)))
print("Output #13: {0:.1f}".format(sqrt(81)))
print("Output #14: {0:s}".format('I\'m enjoying learing Python.'))
| false |
9c5a7345045e705863d567c75e6894ca7b8d0e35 | aymanalqadhi/ezdict | /ezdict/ezdict/utils/string.py | 228 | 4.21875 | 4 | #!/usr/bin/env python3
def reverse_str(name: str) -> str:
""" Reverses a string """
name_lst = list(name)
name_lst.reverse()
ret = ''
for i in range(len(name_lst)):
ret += name_lst[i]
return ret
| false |
d457d8db5ada5a34c1d38e4b6a480c8f060c12f8 | ramkarthikn/DataStructures | /Trie.py | 932 | 4.21875 | 4 | class TrieNode:
def __init__(self,letter):
self.letter = letter
self.children= {}
self.is_end_of_word= False
class Trie:
def __init__(self):
self.root = TrieNode('*')
def add_word(self,word):
cur_node = self.root
for letter in word:
if letter not in cur_node.children:
cur_node.children[letter]= TrieNode(letter)
cur_node = cur_node.children[letter]
cur_node.is_end_of_word = True
def does_word_exist(self,word):
if word =="":
return True
curr_node= self.root
for letter in word:
if letter not in curr_node.children:
return False
curr_node= curr_node.children[letter]
return curr_node.is_end_of_word
trie = Trie()
trie.add_word("karthik")
trie.add_word("karthi")
print(trie.does_word_exist("karthi")) | false |
b5716cb8d3e85000afe07e6b19b6b677f6ddb965 | iancovert/CodeIHS | /day4/exercise_solutions.py | 2,624 | 4.375 | 4 | '''
Exercise 1: iterating through lists
Write three different functions, each of which print out every element of a
list on its own line. Hint: use for loops for two of them, and a while loop
for one. The outputs should look exactly the same!
'''
def printList1(my_list):
for item in my_list:
print(item)
def printList2(my_list):
for i in range(len(my_list)):
print(my_list[i])
def printList3(my_list):
i = 0
while (i < len(my_list)):
print(my_list[i])
i = i + 1
list1 = [1, 3, 5, 7, 9]
list2 = ['Print', 'me', 'out', 'one', 'line', 'at', 'a', 'time']
printList1(list1)
printList1(list2)
printList2(list1)
printList2(list2)
printList3(list1)
printList3(list2)
'''
Exercise 2: counting positive numbers
Write a function that takes a list of numbers, and counts how many of the
numbers are positive (greater than zero)
'''
def numPositive(my_list):
count = 0
for item in my_list:
if item > 0:
count = count + 1
return count
list1 = [1, -1, 6, -6, -9, 9, 0, 2]
list2 = list(range(-5, 5, 1))
print(numPositive(list1))
print(numPositive(list2))
'''
Exercise 3: how far into a list is the first negative number?
Write a function that takes a list of numbers, and counts how far into the
list the first negative number appears. For example, in the list
[3, 2, 1, 0, -1], the first negative number appears at index 4. Return the
index at which the first negative number appears. Hint: consider using a
while loop
'''
def firstNegative(my_list):
i = 0
while (i < len(my_list)):
if my_list[i] < 0:
return i
else:
i = i + 1
# If the list contains no negative numbers, return the length of the list
return i
list1 = [1, 1, 1, -1, 1, -1, -1]
list2 = list(range(5, -5, -1))
print(firstNegative(list1))
print(firstNegative(list2))
'''
Exercise 4: simulating coin flips
The function random() simulates a number between 0 and 1. round(random())
results in a random number that is 0 half the time, and 1 half the time -
like flipping a coin.
Let's say that 0 is tails and 1 is heads.
Use this tool to simulate flipping a coin, and write a function that counts
the number of flips until you get a head. Each time you call the function,
a new set of coin flips should be simulated. Hint: use a while loop
'''
from random import random
# Notice how each time you call the function, you get a different result
print(round(random()))
print(round(random()))
print(round(random()))
def countFlips():
flip = 0
count = 0
while (flip == 0):
flip = round(random())
count = count + 1
return count
print(countFlips())
print(countFlips())
print(countFlips()) | true |
fc0b56977bf90d1e811853b04fa0637c24a3c78d | iancovert/CodeIHS | /day1/lists.py | 1,212 | 4.5 | 4 | # CONCEPT: a list is a container that holds multiple variables
x = [1, 2, 3, 9, 8, 7]
# We access elements of the list using the [] operator
# NOTE: lists are zero-indexed (the first element has index 0)
print(x[0])
print(x[1])
print(x[5])
print(x[4])
# We can access a sequence of elements (similarly to how we obtained
# substrings). Look closely at which elements are returned
print(x[1:4])
print(x[:4])
print(x[1:])
# We can change values in an array
print(x[0])
x[0] = 10
print(x[0])
# We can find the number of elements in an array
x_length = len(x)
print(x_length)
# Instead of viewing one element at a time, we can print the whole list
print(x)
# We can also make lists containing strings
y = ['The', 'weather', 'is', 'nice']
print(y[0] + y[1] + y[2] + y[3])
# It's okay to mix data types in a list
z = [1, 2.0, '3']
print(z[0])
print(z[1])
print(z[2])
# Lists have other operations associated with them
a = []
# Appending
a.append(1)
a.append(2)
a.append(3)
print(a)
# Inserting at a specified index
a.insert(0, 0)
print(a)
# Remove element at an index
a.pop(1)
print(a)
# Counting the number of appearances of an element in the list
b = [1, 1, 1, 2, 1, 1, 1, 3, 4, 1, 5, 1]
print(b.count(1))
| true |
3a9694b4f69e07bd736244f96583d732f077e55b | iancovert/CodeIHS | /day2/functions.py | 1,244 | 4.125 | 4 | # A simple function that prints something, and returns nothing
def hello():
print('Hello world')
hello()
# A function that always returns the value 5
def five():
return 5
# When calling it, assign the return value to a variable
x = five()
print(x)
# A function that takes an argument, and simply returns the argument
def useless(n):
return n
y = useless('This function just returns the argument you pass to it')
print(y)
# A function that takes the argument, does something with it, and returns
# a value
def square(n):
val = n * n
return(val)
z = square(5)
print(z)
# A function that takes a list of numbers (floats or ints) and calculates and
# returns the average
def average(num_list):
total = 0
for num in num_list:
total += num
return total / len(num_list)
a = average([1, 2, 3, 4, 5, 11, 23, 56, 78])
print(a)
# A function that reverses the order of elements in a list. Note that the list
# is not returned. Nothing is returned. What does that tell us about how lists
# work in Python?
def reverse_list(my_list):
n = len(my_list)
for i in range(n // 2):
temp = my_list[i]
my_list[i] = my_list[n - i - 1]
my_list[n - i - 1] = temp
# Don't return a value
b = [1, 2, 3, 4, 5]
print(b)
reverse_list(b)
print(b) | true |
5d0cccad5fc6b7f9e74996470d7c138a12649de7 | JohnYehyo/Pylearning | /17字符串API练习.py | 1,282 | 4.40625 | 4 | s = 'hello python!'
# 计算长度
print(len(s))
# 字符串首字母大写的副本
print(s.capitalize())
# 字符串中每个单词首字母与都大写的副本
print(s.title())
# 字符串全部大写的副本
print(s.upper())
# 查找子字符串在字符串中的位置
print(s.find('o'))
print(s.find('x'))
print(s.rfind('o'))
print(s.index('o'))
# 找不到时会产生异常
# print(s.index('x'))
# 判断字符串是否已指定的字符串开头和结尾
print(s.startswith('he'))
print(s.endswith('on!'))
# 以指定宽度居中字符串并在两侧填充指定的字符
print(s.center(20, '$'))
# 字符串靠右并在左侧填充指定的字符
print(s.rjust(20, '$'))
# 字符串靠左并在右侧填充指定的字符
print(s.ljust(20, '$'))
# 检查字符串是否由数字构成
print(s.isdigit())
# 检查字符串是否由字母构成
print(s.isalpha())
# 检查字符串是否由数字或字母构成
print(s.isalnum())
# 去除字符串两端的空格
print(s.strip())
# 去除字符串中的空格
print(s.replace(' ', ''))
# 替换
print(s.replace('o', 'j'))
print(s.replace('o', 'j', 1))
# 获取字符串中的字符
print(s[0])
print(s[0:])
print(s[:])
print(s[0:1])
print(s[:1])
# 类似于redis list结构的取值
print(s[0:-1])
# 反转
print(s[::-1]) | false |
7647e7fba086b9ba1ce86a63f0e7a086fe148cf3 | SantiagoD123/projprogramacion | /Taller/Tallerfunciones.py | 1,719 | 4.15625 | 4 | #Dada una lista muéstrela en pantalla elemento a elemento
def elemlista(lista):
for i in lista:
print(i)
numeros = [24, 40, 80, 10, 20, 35, 77, 80, 105]
elemlista(numeros)
#Dada una lista de números enteros muestre en pantalla el número más grande, el más pequeño y el promedio
#de la lista
def proLista(lista):
menor = min(lista)
mayor = max(lista)
prom = 0
prom =sum(lista)
div = len(lista)
promedio = prom/div
print('El mayor es:', mayor, 'Menor es:', menor, 'promedio es:', promedio)
numeros = [24, 40, 80, 10, 20, 35, 77, 80, 105]
proLista(numeros)
#Saludar n veces
def saludo(n = 0):
print("Buenas tardes " * n)
n = int(input ("¿Cuantas veces quieres saludar?: "))
saludo(n)
#Que devuelva todos los números pares de una lista de números enteros
def numpar(lista):
par = []
for i in lista:
if i % 2 == 0:
par.append(i)
return par
numeros = [24, 40, 80, 10, 20, 35, 77, 80, 105]
print (numpar(numeros))
#Que devuelva únicamente los elementos mayores a 24
def nummay(lista):
may = []
for i in lista:
if i > 24:
may.append(i)
return may
numeros = [24, 40, 80, 10, 20, 35, 77, 80, 105]
print (nummay(numeros))
#Se sabe que el IMC se calcula dividiendo el peso por la
#altura al cuadrado, realice una función que lo calcule.
def imc(peso, alt):
IMC = peso/(alt**2)
print (IMC)
peso = float(input("Por favor escriba su peso: "))
alt = float(input("Escriba su estatura: "))
IMC = imc(peso, alt)
#Crea un función que sirva para despedirte del que esta ejecutando el código
def desp():
print(Mensaje_despedida)
Mensaje_despedida = "Hasta luego, que tenga un buen dia"
desp() | false |
95da004f8bfe4b2e8979de6a6ab4078a1ccef9d0 | rongoodbin/secret_messages | /keyword_cipher.py | 1,836 | 4.21875 | 4 | import string
from ciphers import Cipher
class Keyword(Cipher):
def __init__(self, keyword):
self.keyword = keyword.upper()
self.FORWARD = string.ascii_uppercase
self.setup_mono()
def setup_mono(self):
"""
setup alphabet with keyword added in the beginning of the alphabet.
This is done by removing letters that are in the keyword and then appending
the keyword to the letter list
"""
self.monoalphabet = [char for char in string.ascii_uppercase]
for letter in self.keyword:
try:
self.monoalphabet.remove(letter)
except:
pass
self.monoalphabet = self.keyword.upper() + "".join(self.monoalphabet)
def encrypt(self, text):
"""Encryption logic for the keyword cipher.
Arguments:
text -- string message to encrypt.
Returns:
An encrypted string.
"""
output = []
text = text.upper()
for char in text:
if char not in string.ascii_uppercase:
output.append(char)
continue
index_of_letter = self.FORWARD.find(char)
output.append(self.monoalphabet[index_of_letter])
return ''.join(output)
def decrypt(self, text):
"""decryption logic for the keyword cipher
Arguments:
text -- string message to decrypt.
Returns:
Decrypted string.
"""
output = []
text = text.upper()
for char in text:
if char not in string.ascii_uppercase:
output.append(char)
continue
index_of_letter = self.monoalphabet.find(char)
output.append(self.FORWARD[index_of_letter])
return ''.join(output)
| true |
32785f1b2b01b831c8de995cab0dc3a18df1b601 | jitendragangwar123/cp | /note/script.py | 999 | 4.1875 | 4 | # polynomial evaluation
eq = "x**3 + x**2 + x + 1"
x = 1
ans = eval(eq)
print (ans)
# lambda function
x = lambda x,y:x+y
print(x(10,20))
# reduce function
# The reduce() function applies a function of two arguments cumulatively on a list of objects in succession from left to right to reduce it to one value. Say you have a list, say [1,2,3] and you have to find its sum.
from functools import reduce
reduce(lambda x, y : x + y,[1,2,3])
# define an initial value https://stackoverflow.com/questions/409370/sorting-and-grouping-nested-lists-in-python?answertab=votes#tab-top
reduce(lambda x, y : x + y, [1,2,3], -3)
# Sorting and Grouping Nested Lists in Python
x = [
['4', '21', '1', '14', '2008-10-24 15:42:58'],
['3', '22', '4', '2somename', '2008-10-24 15:22:03'],
['5', '21', '3', '19', '2008-10-24 15:45:45'],
['6', '21', '1', '1somename', '2008-10-24 15:45:49'],
['7', '22', '3', '2somename', '2008-10-24 15:45:51']
]
from operator import itemgetter
x.sort(key=itemgetter(1))
| true |
4252778b56bc85e0cbc74205f041a5605bd896cc | teixeirah/Calculator | /calculator.py | 1,922 | 4.3125 | 4 | import sys
while True:
operador = None
num1 = None
num2 = None
res = None
final = None
print("\nTHIS-IS-A-CALCULATOR")
print("-> Type '+' to add '2' numbers")
print("-> Type '-' to subtract '2' numbers")
print("-> Type '*' to multiply '2' numbers")
print("-> Type '/' to divide '2' numbers")
print("-> Type 'off' to turn-off the calculator")
operador = input("-> ")
if operador == "+":
print("Operator -> Adding")
print("-> Type the first number you want to add")
num1 = float(input("-> "))
print("Type the number you want to add " + str(num1) + " with")
num2 = float(input("-> "))
res = float(num1) + num2
final = str(num1) + " plus " + str(num2) + " is equal to: " + str(res)
print(final)
if operador == "-":
print("Operator -> Subtracting")
print("-> Type the first number you want to subtract")
num1 = float(input("-> "))
print("Type the number you want to subtract " + str(num1) + " with")
num2 = float(input("-> "))
res = float(num1) - num2
final = str(num1) + " minus " + str(num2) + " is equal to: " + str(res)
print(final)
if operador == "*":
print("Operator -> Multiplying")
print("-> Type the first number you want to multiply")
num1 = float(input("-> "))
print("Type the number you want to multiply " + str(num1) + " with")
num2 = float(input("-> "))
res = float(num1) * num2
final = str(num1) + " times " + str(num2) + " is equal to: " + str(res)
print(final)
if operador == "/":
print("Operator -> Dividing")
print("-> Type the first number you want to divide")
num1 = float(input("-> "))
print("Type the number you want to divide " + str(num1) + " with")
num2 = float(input("-> "))
res = float(num1) / num2
final = str(num1) + " divided by " + str(num2) + " is equal to: " + str(res)
print(final)
if operador == "off":
break
sys.exit()
| true |
8f899091e5f9ac887087a9e14f5d294176939929 | Sravani663/Practice | /insertion_sort.py | 589 | 4.25 | 4 | from __future__ import print_function
def insertion_sort(array):
for index in range(1, len(array)):
while 0 < index and array[index] < array[index - 1]:
array[index], array[
index - 1] = array[index - 1], array[index]
index -= 1
return array
if __name__ == '__main__':
try:
raw_input
except NameError:
raw_input = input
user_input = raw_input('Enter numbers separated by a comma:\n').strip()
unsorted = [int(item) for item in user_input.split(',')]
print(insertion_sort(unsorted))
| true |
0f6275aed5b3af311ac0c6f9649d8e688dff5a49 | Szczypiorstwo/Udemy_Python_text_battle | /tutorials_up_to_section4/tutorials.py | 472 | 4.1875 | 4 | print("Hello, " + "Nicki")
print("this costs " + str(6) +" dolars." )
print("this costs " + str(6+5) +" dolars." )
text = " hello:Nick:works"
text2 = text.split(":")
text3 = text.split(":")[1]
print("my name is" + text3)
print ("this" is "this")
print ("True" is True) #gives False
print ("True" is str(True)) #gives true
list = ["python", "16", "games"]
print("I like " + list[0])
dictionary = {"name": "Nick", "age": 27, "hobby": "code"}
print(dictionary["hobby"]) | false |
6f88e5eb899270cd1b1be5f235e2c25aff4d4e33 | Zebfred/Intro-Python-I | /guided_practice/05_string_formatting.py | 905 | 4.6875 | 5 | """
String Formatting
"""
# 1. The "%" operator is used to format a set of variables
# enclosed in a "tuple", together with a format string,
# which contains normal text together with "argument specifiers",
# special symbols like "%s" and "%d".
# This prints out "Hello, John!"
name = "John"
print("Hello, %s!" % name)
# # 2. To use two or more argument specifiers, use a tuple (parentheses)
# This prints out "John is 23 years old."
name = "John"
age = 23
print("%s is %d years old." % (name, age))
# 3. Any object which is not a string can be formatted
# using the %s operator as well
# %s - String (or any object with a string representation, like numbers)
# %d - Integers
# %f - Floating point numbers
# %.<number of digits>f - Floating point numbers
# with a fixed amount of digits to the right of the dot.
# This prints out: A list: [1, 2, 3]
mylist = [1, 2, 3]
print("A list: %s" % mylist)
| true |
4a4b8ac8860e64572d6045d88d3f138d6d8da389 | Zebfred/Intro-Python-I | /guided_practice/13_list_comprehensions.py | 1,247 | 4.3125 | 4 | """
List Comprehensions
"""
# creates a new list based on another list,
# in a single, readable line
# 1.
# # WITHOUT LIST COMPREHENSIONS
sentence = "the quick brown fox jumps over the lazy dog"
words = sentence.split()
word_lengths = []
#for word in words:
# if word != "the":
# print(words)
# print(word_lengths)
# # WITH LIST COMPREHENSIONS
sentence = "the quick brown fox jumps over the lazy dog"
words = sentence.split()
word_lengths = [len(word) for word in words if word != "the"]
print(words)
print(word_lengths)
"""
YOU DO
3 minute timer
"""
# Use a list comprehension to create a new list
# that has only names that start with the letter s
# and make sure all the names are properly
# capitalized in the new list.
# 1.
# # WITHOUT LIST COMPREHENSIONS
#names = ["Sarah", "jorge", "sam", "frank", "bob", "sandy", "shawn"]
#words = names.split()
#word_lengths = []
#for word in words:
# if word != "the":
# word_lengths.append(len(word))
# print(word_lengths)
names = ["Sarah", "jorge", "sam", "frank", "bob", "sandy", "shawn"]
#list comprehension about time you tackled it
capitalizedNames = [name.capitalize() for name in names if name[0].capitalize() == 'S']
print(capitalizedNames)
| true |
ff0d7f9293b248ff5993eef2342d51f7243e4142 | Cholpon05/first_task | /task_1.py | 203 | 4.15625 | 4 | name = input("Enter your name")
month = input("Enter month of your studies")
if month.lower() == "1":
print("You are beginner")
else:
if month.lower()!= "5":
print("You are intermediate") | true |
7a1b186a6f811c7f994f2acbd4e3b42275a53560 | WILLIDIO/ExercicioPython | /exercicio10.py | 629 | 4.15625 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
print("Faça um Programa que leia dois vetores com 10 elementos cada.")
print("Gere um terceiro vetor de 20 elementos,")
print("cujos valores deverão ser compostos pelos elementos intercalados")
print("dos dois outros vetores.")
print()
def criaVetor():
vetor = []
for i in range(10):
elemento = int(input("Digite um número: "))
vetor.append(elemento)
print("\n")
return vetor
vetor1 = criaVetor()
vetor2 = criaVetor()
vetor3 = []
for i in vetor1:
vetor3.append(i)
for j in vetor2:
vetor3.append(j)
print(vetor3)
print(type(vetor3))
| false |
406dfa62c21c4b8d6f33e8f250d74fdee2df716c | WILLIDIO/ExercicioPython | /exercicio2.py | 288 | 4.15625 | 4 | # -*- coding: utf-8 -*-
# Exercício 2
print(
"Faça um Programa que leia um vetor de 10 números reais e mostre-os na ordem inversa."
)
vetor = []
for i in range(10):
numero = float(input("Digite um número: "))
vetor.append(numero)
vetor.sort(reverse=True)
print(vetor)
| false |
b9b35da4c441c8c1ee33b0071eb41370f7cb5020 | wangpengda1210/Tetris | /Problems/Several testings/main.py | 224 | 4.15625 | 4 | def check(string: str):
if not string.isdigit():
print("It is not a number!")
elif int(string) >= 202:
print(int(string))
else:
print("There are less than 202 apples! You cheated on me!")
| true |
42cd76ecb6645b0fb4d94cceaa22de19491fe537 | RachelDiCesare93/Intro-Python | /src/day-1-toy/dicts.py | 758 | 4.40625 | 4 | # Make an array of dictionaries. Each dictionary should have keys:
#
# lat: the latitude
# lon: the longitude
# name: the waypoint name
#
# Make up three entries of various values.
waypoints = [
{
"lat": 43,
"lon": -121,
"name": "apartment"
},
{
"lat": 41,
"lon": -123,
"name": "mall"
},
{
"lat": 43,
"lon": -122,
"name": "starbucks"
}
]
# Write a loop that prints out all the field values for all the waypoints
for place in waypoints:
print('{}: latitude = {},longitude = {}'.format(place["name"],place["lat"],place["lon"]))
# Add a new waypoint to the list
waypoints.append({
"lat": 55,
"lon": -100,
"name": "chipotle"
})
print(waypoints)
| true |
02ee380cce9e0badf9dc42b5dde05a310a1e1655 | mitches-got-glitches/CAT_learning | /session7/list_remove_duplicates.py | 1,337 | 4.3125 | 4 | ### Solution to List Remove Duplicates Challenge (14) on practicepython.org
def remove_duplicates_using_loop(list_):
"""Takes a list and returns a list of the unique values."""
unique_values = []
for elem in list_:
if elem not in unique_values:
unique_values.append(elem)
return unique_values
def remove_duplicates_using_sets(list_):
"""Takes a list and returns a list of the unique values."""
return list(set(list_))
def main():
my_list = [2, 3, 65, 3, 'cheese', 'beans', 7, 3, 2, 'cheese', 765]
print(remove_duplicates_using_loop(my_list))
print(remove_duplicates_using_sets(my_list))
if __name__ == "__main__":
main()
def solution():
print("""
def remove_duplicates_using_loop(list_):
\"\"\"Takes a list and returns a list of the unique values\"\"\"
unique_values = []
for elem in list_:
if elem not in unique_values:
unique_values.append(elem)
return unique_values
def remove_duplicates_using_sets(list_):
\"\"\"Takes a list and returns a list of the unique values\"\"\"
return list(set(list_))
def main():
my_list = [2, 3, 65, 3, 'cheese', 'beans', 7, 3, 2, 'cheese', 765]
print(remove_duplicates_using_loop(my_list))
print(remove_duplicates_using_sets(my_list))
if __name__ == "__main__":
main()
""") | true |
b092ad55f62d344c79f7682693977db20482ee38 | mitches-got-glitches/CAT_learning | /session7/list_ends.py | 998 | 4.3125 | 4 | ### Solution to List Ends Challenge (12) on practicepython.org
def get_list_ends(list_):
"""Takes a list and returns the items at the start and end."""
return [list_[0], list_[-1]]
def main():
my_list = [765, 'ace', 20, 'twenty', 'bullseye']
ends = get_list_ends(my_list)
return ends
if __name__ == "__main__":
ends = main()
def solution():
print("""
def get_list_ends(list_):
\"\"\"Takes a list and returns the items at the start and end\"\"\"
return [list_[0], list_[-1]]
def main():
my_list = [765, 'ace', 20, 'twenty', 'bullseye']
ends = get_list_ends(my_list)
return ends
if __name__ == "__main__":
ends = main()
""")
def hint1():
print("""
Functions are defined in the following format:
def my_function(arg1, arg2, ...):
\"\"\"Docstring describing the function...\"\"\"
# Code that the does the work.
return output
""")
def hint2():
print("""
To get the last element in the list use negative indexing: my_list[-1]
""")
| true |
7e98a74d4f838d9390d3a179eab794f0a6357b0c | KLKln/Module7 | /fun_with_collections/basic_list_exception.py | 1,135 | 4.28125 | 4 | """
Program:basic_list_exception.py
Author: Kelly Klein
Last date modified: 6/21/2020
This program will take user input of numbers and store them in a list.
"""
def get_input():
"""
Use reST style.
:return: the number user entered
"""
while True:
try:
user_input = input(print('Enter a number to add to the list: '))
if user_input.isalpha():
raise ValueError
if int(user_input) < 0:
print('Too low!')
raise ValueError
if int(user_input) >= 50:
print('Too high!')
raise ValueError
except ValueError:
print('Positive numbers 50 or below please')
continue
return user_input
def make_list():
"""
Use reST style.
:return: the 3 numbers user entered
raises TypeError: raises an exception if user uses alphabet
"""
user_list = []
for i in range(0, 3):
user_number = get_input()
user_list.append(int(user_number))
print(user_list)
return user_list
if __name__ == '__main__':
make_list()
| true |
d631a702da8d091373579add218f64e2cfcc54b2 | alexandrezamberlan/RNA_Profunda | /6-broadcasting.py | 1,563 | 4.15625 | 4 | '''
Um conceito muito importante para entender no pacote numpy é "broadcasting".
É muito útil para executar operações matemáticas entre arrays de diferentes dimensões.
Veja http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html
Maças Carnes Ovos Batatas
carboidratos 56 0.0 4.4 68
proteinas 1.2 104 52 8
gordura 1.8 135 99 0.9
'''
import numpy as np
a = np.array([[56, 0, 4.4, 68],
[1.2, 104, 52, 8],
[1.8, 135, 99, 0.9]])
print(a)
calorias = a.sum(axis=0) #axis=0 significa coluna, enquanto axis=1 significa linhas
print("Calorias para cada alimento/coluna: " ,calorias)
#calculando a porcentagem de cada valor sobre a caloria total
porcentagem = 100*a/calorias.reshape(1,4)
print("A porcentagem para cada alimento")
print(porcentagem)
'''
Ideia geral de broadcasting é
matriz(m,n) (+ ou - ou * ou /) matriz(1,n) -> matriz(m,n)
'''
print("Outro exemplo de broadcasting.....")
def softmax(x):
"""Calcula softmax para cada linha de x.
Funciona em vetor e matrizes[n, m].
Argument:
x -- matriz do pacote numpy de dimensão (n,m)
Returns:
resultado -- matriz numpy igual ao softmax de x (n,m)
"""
x_elevada = np.exp(x)
x_somada = np.sum(x_elevada, axis = 1, keepdims = True)
resultado = x_elevada / x_somada
return resultado
matriz = np.array([
[9, 2, 5, 0, 0],
[7, 5, 0, 0 ,0]])
print("softmax da matriz = " + str(softmax(matriz)))
| false |
74e914f344dd866cdfe352af0cd09d61a29b2b16 | yunjipark0623/python_2018 | /07/carGame.py | 1,051 | 4.125 | 4 | ## 변수 선언 부분
parking = []
top, carName, outCar = 0, "A", ""
select = 9
## 메인(main) 코드 부분
while (select != 3) :
select = int(input("<1> 자동차 넣기 <2> 자동차 빼기 <3> 끝 : "))
if (select == 1) :
if (top >= 5) :
print("주차장이 꽉 차서 못들어감")
else :
parking.append(carName)
print("%s 자동차 들어감. 주차장 상태 ==> %s " % (parking[top], parking))
top += 1
carName = chr(ord(carName)+1)
elif(select == 2) :
if (top <= 0) :
print("빠져나갈 자동차가 없음")
else :
outCar = parking.pop()
print("%s 자동차 나감. 주차장 상태 ==> %s " % (outCar, parking))
top -= 1
carName = chr(ord(carName) -1)
elif(select == 3) :
break;
else :
print("잘못 입력했네요. 다시 입력하세요.")
print("현재 주차장에 %d대가 있음" % top)
print("프로그램을 종료합니다.")
| false |
0e65bc90087ee21668cfb4a261a6c0c9f57e1326 | xanthesoter/Computer-Science | /Calculating the Area of a Triangle.py | 493 | 4.40625 | 4 | # Calculating the Area of a Rectangle
print("This program calculates the area of a rectangle.")
while True:
length = float(input("Enter the length of rectangle:"))
width = float(input("Enter the width of rectangle: "))
Area = length * width
print("The area of the rectangle is:", Area)
answer = input("Do you need another calculation?")
if answer == "Yes" or answer == "yes" or answer == " yes" or answer == " Yes":
continue
else:
break
| true |
8ff8a5c8489cb41f536fc6aeedaadbc443c7f912 | shaun-macdonald/Programming1 | /Week1/Exercise5.py | 234 | 4.1875 | 4 | #Exercise 5 Week 1
width = int(input("Please enter the width of a triangle in cm: "))
height = int(input("Please enter the height of a triangle in cm: "))
area = width * height / 2
print("Area of the triangle is {} cm".format(area)) | true |
e7bce09e934c8f1ccde37a908299d4b8e8f7966b | dataCalculus/addTwoNumber | /0_addTwoNumbers_v2.py | 1,581 | 4.125 | 4 | # Python3 program to add two numbers
# loopa al options ekle v1
# başlangıç menüsü ekle v2
## 0. normal başlangıç user termination v2
## 1. counter console a yazdır. Kaçıncı döngü gibi. v2
## 2.
## 9. programdan çıkış v2
# sonuçlanan sayıyı yorumla : asal , tek/çift v3
# //////////////////////////////////
# sayıları veya sonuçları veritabanına yazabilirim
# OEIS ile ilişkilendirebilirim
# randomness ekleyebilirim
# olasılıksal sayılar ekleyebilirim
# sonuç hakkında yorumlar : asallık , tek çift vs
# //////////////////////////////////
def addTwoNumber():
number1 = input("First number: \n")
number2 = input("Second number: ")
# Adding two numbers
# User might also enter float numbers
sum = float(number1) + float(number2)
# Display the sum
# will print value in float
print("The sum of {0} and {1} is {2}".format(number1, number2, sum))
print("Çıkmak için n ye basın")
def menu():
print("""
0 : normal addition
1 : print Counter (n th step of loop)
9 : exit
""")
counter = 0
while True:
menu()
selection = input()
if selection == "0":
addTwoNumber()
elif selection =="1":
print(counter)
counter += 1
continue
elif selection == "9":
print("çıkılıyor...")
break
counter += 1
exit_string = input("")
if exit_string == "n":
print("Çıkılıyor...")
break
else :
continue | false |
0ac36bffb863f8946121457f6a7a768f0a881980 | ScarletMcLearn/PySnips | /PyFibonacci Sum.py | 862 | 4.125 | 4 | #ThisProgramPrintsTheFibonaciSequence
#FirstWeTakeTheNumberOfTermsToPrintFromUser
number_of_terms=int(input('Koyta Term Pirint Dibuh?:'))
#CreateVariableStartingTermAndNextTerm
#1stAnd2ndTermsOfTheSequence
#StoreTheirValues
starting_term=0
next_term =1
summation = 0
if number_of_terms>0:
print (starting_term,'',)
print ( )
print (summation)
if number_of_terms>1:
print (next_term,'',)
print ( )
print (summation + next_term)
for iteration in range (3, number_of_terms +1):
temporary_variable = next_term
summation = 2
next_term = next_term + starting_term
starting_term = temporary_variable
summation = summation + temporary_variable
print (next_term,'',)
print (' ')
print (summation)
| true |
f0d35684c7b6745022087d427240a1520201ea28 | iwashito230/pyractice | /python課題集/応用プログラミング演習問題集(基礎編)/4-2.py | 1,083 | 4.15625 | 4 | '''
例題4-3のサンプルコードを用いて,
(1)入力した数が10か10より大きいか10未満かを判定するプログラムを作りましょう.
(2)入力した数が1なら1,2なら2,それ以外ならetcと表示させましょう.
(3)最初のifの条件式を(x<0)とすると,実行結果は元のプログラムと変わってしまいます.
そこで,この条件式以外の部分を修正して,元のプログラムと同じ実行結果を出すプログラムに修正しましょう.
'''
def first():
x = int(input("Please enter an integer:"))
if x >= 10:
print('10ijou')
elif x < 10:
print('10miman')
def second():
x = int(input("Please enter an integer:"))
if x == 1:
print(x)
elif x == 2:
print(x)
else:
print('etc')
def third():
x = int(input("Please enter an integer:"))
if x <= 0 or x < 10:
print('10miman')
elif x >= 10:
print('10ijou')
if __name__ == '__main__':
#first()
#second()
third()
| false |
cbc847a96b354f9250a95053f10a34498a98e691 | ashutosh4398/Data-Structures | /Stack-Applications/EvaluatePostFix.py | 1,173 | 4.375 | 4 | "HERE WE HAVE ASSUMED THAT ALL THE INPUT STRINGS ARE VALID AND ONLY CONTAINS DIGITS [0-9]"
from Stack import Stack
operators = ['+','-','*','/','^']
def evaluatePostfix(expression):
"""
In postfix expression, we start scanning the expression from left to right
"""
stack = Stack()
for i in expression:
# check if the current character is an operator or digit
if i in operators:
# perform the operation
op2 = int(stack.pop())
op1 = int(stack.pop())
if i == '+':
res = op1 + op2
elif i == '-':
res = op1 - op2
elif i == '*':
res = op1 * op2
elif i == '/':
res = op1 / op2
elif i == '^':
res = op1 ** op2
# push the result into the stack
stack.push(res)
else:
stack.push(i)
stack.Print()
print('-'* 30)
# return the element left in stack
return stack.peek()
sample = input("Enter a valid postfix expression: ")
result = evaluatePostfix(expression = sample)
print(f"The result is {result}") | true |
f9909e4605d7e4239879470963db6db4cb046702 | ashutosh4398/Data-Structures | /LinkedList.py | 2,960 | 4.21875 | 4 | class Node():
def __init__(self,data):
self.data = data
self.next = None
# marks as the start of node / represents the linked list
head = None
print("Creating a linked list.....")
print("Enter elements and -1 at end: ")
def printList(head):
"PRINTS THE ENTIRE LINKED LIST"
temp = head
while(temp):
print(f"[{temp.data}] --> ",end='')
temp = temp.next
print('NULL')
def Insert(x,head):
"INSERT ELEMENTS AT THE BEGINNING OF LIST"
node = Node(x)
node.data = x
node.next = head
head = node
return head
def InsertAtN(pos,value,head):
"INSERTS ELEMENTS AT NTH POSITION"
count = 0
# this line is written just to stick with the convention of not using the head directly
temp = head
# keep track of previous node as well
prev = head
while count != pos and temp:
count += 1
prev = temp
temp = temp.next
new_node = Node(value)
new_node.data = value
new_node.next = temp
prev.next = new_node
def DeleteAtN(pos,head):
"DELETES A NODE AT NTH POSITION"
if pos == 0:
return head.next
count = 0
temp = head
prev = head
while count != pos and temp:
count += 1
prev = temp
temp = temp.next
# once we found the accurate position then just delete
prev.next = temp.next
del temp
return head
def ReverseLinkedListIterative(head):
temp = head
prev = None
while(temp):
var = temp.next
temp.next = prev
prev = temp
temp = var
return prev
def ReverseLinkedListRecursive(current):
"REVERSES A LINKED LIST USING RECURSION"
if current.next == None:
# last node
return current
head = ReverseLinkedListRecursive(current.next)
temp = current.next
current.next = None
temp.next = current
return head
while(True):
print("0: STOP")
print("1: Printing the linked list")
print("2: Insert at beginning")
print("3: Insert at nth position")
print("4: Delete a node at nth position")
print("5: Reverse a linked list using iterative method")
print("6: Reverse a linked list using Recursive method")
choice = int(input(">>>"))
if choice == 1:
printList(head)
elif choice == 2:
x = int(input("Enter value: "))
head = Insert(x,head)
elif choice == 3:
pos = int(input("Enter pos at which you want to insert the new node: "))
value = int(input("Enter value to be entered: "))
InsertAtN(pos,value,head)
elif choice == 4:
pos = int(input("Enter position of node to be deleted: "))
head = DeleteAtN(pos,head)
print("Deleted successfully....")
elif choice == 5:
head = ReverseLinkedListIterative(head)
printList(head)
elif choice == 6:
head = ReverseLinkedListRecursive(head)
printList(head)
elif choice == 0:
break | true |
8e7de3522a52c1fcafe60ec3fa186f36bd74ec28 | MercerBinaryBears/ReferenceSheet | /misc/dateTime.py | 1,236 | 4.15625 | 4 | #Counting Days to Event
>>> import time
>>> from datetime import date
>>> today = date.today()
>>> today
datetime.date(2007, 12, 5)
>>> today == date.fromtimestamp(time.time())
True
>>> my_birthday = date(today.year, 6, 24)
>>> if my_birthday < today:
... my_birthday = my_birthday.replace(year=today.year + 1)
>>> my_birthday
datetime.date(2008, 6, 24)
>>> time_to_birthday = abs(my_birthday - today)
>>> time_to_birthday.days
202
#Working with Dates
>>> from datetime import date
>>> d = date.fromordinal(730920) # 730920th day after 1. 1. 0001
>>> d
datetime.date(2002, 3, 11)
>>> t = d.timetuple()
>>> for i in t:
... print(i)
2002 # year
3 # month
11 # day
0
0
0
0 # weekday (0 = Monday)
70 # 70th day in the year
-1
>>> ic = d.isocalendar()
>>> for i in ic:
... print(i)
2002 # ISO year
11 # ISO week number
1 # ISO day number ( 1 = Monday )
>>> d.isoformat()
'2002-03-11'
>>> d.strftime("%d/%m/%y")
'11/03/02'
>>> d.strftime("%A %d. %B %Y")
'Monday 11. March 2002'
>>> 'The {1} is {0:%d}, the {2} is {0:%B}.'.format(d, "day", "month")
'The day is 11, the month is March.'
| false |
eeb7b857d2b596f49baaa60f1794b1c15633a1eb | gan3i/Python_Advanced | /DS_and_AT/Queue/generateBinary.py | 734 | 4.3125 | 4 | from queue import Queue
# Python program to generate binary numbers from
# 1 to n
# This function uses queu data structure to print binary numbers
def generatePrintBinary(n):
# Create an empty queue
q = Queue()
# Enqueu the first binary number
q.put("1")
# This loop is like BFS of a tree with 1 as root
# 0 as left child and 1 as right child and so on
while(n>0):
n-= 1
# Print the front of queue
s1 = q.get()
print (s1)
s2 = s1 # Store s1 before changing it
# Append "0" to s1 and enqueue it
q.put(s1+"0")
# Append "1" to s2 and enqueue it. Note that s2
# contains the previous front
q.put(s2+"1")
# Driver program to test above function
n = 10
generatePrintBinary(n)
| true |
6f5a93fc782ccd75ce2c07d1e70c04431379a090 | gan3i/Python_Advanced | /DS_and_AT/Tree/isBST.py | 1,017 | 4.46875 | 4 | # Python3 program to check
# if a given tree is BST.
import math
from treeBST import six
# A binary tree node has data,
# pointer to left child and
# a pointer to right child
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def isBSTUtil(root, prev):
# traverse the tree in inorder fashion
# and keep track of prev node
if root != None:
if not isBSTUtil(root.left, prev):
return False
# Allows only distinct valued nodes
if (prev != None and
root.data <= prev.data):
return False
prev = root
return isBSTUtil(root.right, prev)
return True
def isBST(root):
prev = None
return isBSTUtil(root, prev)
# Driver Code
if __name__ == '__main__':
root = Node(3)
root.left = Node(2)
root.right = Node(5)
root.right.left = Node(1)
root.right.right = Node(4)
#root.right.left.left = Node(40)
if (isBST(six) == None):
print("Is BST")
else:
print("Not a BST")
# This code is contributed by Srathore
| true |
bcf91d5b6807b5d36925feee03d851f68071b542 | HawiCaesar/python_practice | /multiples_3_5.py | 355 | 4.28125 | 4 | """
def check_multiple3(number):
if number > 0:
print "%d is not a multiple of 3" % number
"""
v3 = 0
v5 = 0
total = 0
for i in range(0,1000):
v3 = i%3
v5 = i%5
if i%3 == 0:
print "%d is multiple of 3" % i
total += i
elif i%5 == 0:
print "%d is multiple of 5" % i
total += i
print "The sum total of multiples 3 and 5 is %d " % total
| false |
08bfdbcb937c36af7aadf038d71d04ab56bc692f | rishu16111996/BINF-Projects | /Functions_Algorithms/basic_functions.py | 665 | 4.3125 | 4 | #!/usr/bin/env python3
# basic_functions
def multiply(a,b):
'''Multiply Function returns a * b
'''
return a * b
def hello_name(name="you"):
'''hello_name function returns Hello and name which is passed as argument and should print "you" if no argument is passed
'''
return("Hello, {}!".format(name))
def less_than_ten(numb):
'''This function returns list of numbers less then 10 in a list passed as argument
'''
final_list = []
for i in numb:
if i < 10:
final_list.append(i)
return(final_list)
#multiply(5, 10)
#hello_name("Akbar")
#hello_name()
#less_than_ten([1,5,81,10,8,2,102])
| true |
54b383b76d1447b4d74cc9b42ac0505f7fe0905e | luiziulky/Controlstructures | /Exercise 1.py | 210 | 4.125 | 4 | num = []
num.append(int(input('enter a number: ')))
num.append(int(input('enter a number: ')))
if num[0] == num[1]:
print('The two numbers are equals')
else:
print(f'the largest number is {max(num)}')
| true |
86da06db9cd3f85ff81c5c9dcb627f3024dcdd62 | vincent9228/Python | /Yuyq_P02Q05.py | 767 | 4.28125 | 4 | # Finding the number of days in a month
# FileName: Yuyq_P02Q05
# Prompt user for month in number.
m = int(input("Enter a month in number:"))
# Prompt user for a year.
year = int(input("Enter a year:"))
# All the moneth in order.
month = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August',
'september', 'October', 'November', 'December']
# Determine the number of day in the month and print result.
if m == 1 or m == 3 or m == 5 or m == 7 or m == 8 or m == 10 or m == 12:
print(month[m-1], year,"has",31,"days")
elif m == 4 or m == 6 or m == 9 or m == 11 :
print(month[m-1],year,"has" , 30,"days")
elif m == 2 and year % 4 == 0 :
print(month[m-1],year,"has",29,"days")
else:
print(month[m-1],year,"has",28,"days")
| true |
12dbc4a154055737568e474890eab9cca31b8206 | vincent9228/Python | /Yuyq_P02Q04.py | 290 | 4.3125 | 4 | # Dtermining leap year
# FileName: Yuyq_P02Q04
# Prompt user for a year.
year = int(input("Enter a year:"))
# determine if the year entered is a leap year and print result.
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0 :
print("leap year")
else :
print("Non leap year")
| true |
1869ad2df50f32bd7eabd835188bfa419c6f2330 | celidon/Schoolwork | /python/Week2/Exercise10.py | 672 | 4.125 | 4 | """
File Name: Exercise10.py
Developer: Anthony Hansen
Date Last Modified: 31.08.2013
Description: The assignment was to write a program that prompts for a
number until the number is a perfect square.
Email Address: hansen.tony92@gmail.com
"""
number_str = input("Please insert a positive number of your choice: ")
number_int = int(number_str)
while number_int > 0:
x = int(number_int ** (.5))
if (x * x) == number_int:
print (number_int, " is a perfect square. Its squareroot is ", x)
break
else:
number_str = input("Please insert a positive number of your choice: ")
number_int = int(number_str)
| true |
549150ab1f7bd6ce83748b27c4e3188f0d16598c | celidon/Schoolwork | /python/Week2/Exercise22.py | 920 | 4.15625 | 4 | """
File Name: Exercise22.py
Developer: Anthony Hansen
Date Last Modified: 31.08.2013
Description: The assignment was to write a program that prompts for a
number greater than 2 and then continuously takes the squareroot
until the number is less than 2
Email Address: hansen.tony92@gmail.com
"""
number_str = input("Please insert a positive number of your choice greater than 2: ")
number_int = int(number_str)
while number_int >= -1:
if number_int > 2:
attempt = 1
print("The squareroots of the number until it is lower than 2: ")
while number_int > 2:
print(attempt, ": ", number_int ** 0.5)
number_int = number_int ** 0.5
attempt += 1
break
else:
number_str = input("Please insert a positive number of your choice greater than 2: ")
number_int = int(number_str)
| true |
105f572f57a5fd809f73e413f3f74ec6c9179de4 | Suganthi2196/basic-of-python | /Pizza.py | 414 | 4.15625 | 4 | pizza=input("select the type of pizza you want \n1-small pizza\n2-medium pizza\n3-large pizza")
bill=0
if pizza=="1":
bill+=30
elif pizza=="2":
bill+=40
else:
bill+=50
print(f"your bill is {bill}")
pepper_onion=input("if you want to pepper onion select \nyes\nno")
if pizza=="1" and pepper_onion=="yes":
bill+=10
elif pizza=="2" and pepper_onion=="yes":
bill+=30
else:
bill=bill
print(bill) | true |
94214ffafc424e89eb49a4ce569105233da24a8c | Peixinho20/Python | /python/mundo2/a12/d41.py | 739 | 4.15625 | 4 | #ATÉ A AULA 12
'''
A Confederção Nacional de Natação precisa de uma programa que leia o ano de nascimento de um atleta e mostre sua
categoria de acordo com a idade:
- Até 9 anos: Mirim
- Até 14 anos: Infantil
- Até 19 anos: Junior
- Até 20 anos: Sênior
- Acima: Master
'''
nome = str(input('Digite seu nome: '))
idade = int(input('Agora informe sua idade: '))
if idade < 9:
print('{} está na categoria mirim!'.format(nome))
elif 9 <= idade < 14:
print('{} está na categoria infantil.'.format(nome))
elif 14 <= idade < 19:
print('{} está na categoria junior.'.format(nome))
elif 19 <= idade < 22:
print('{} está na categoria sênior.'.format(nome))
else:
print('{} está na categoria master.'.format(nome)) | false |
daef2fb9b3565ea1c196001e99dea0dea18ba8f8 | Peixinho20/Python | /python/mundo1/a7/d14.py | 269 | 4.21875 | 4 | '''
Crie um programa que converta uma temperatura digitada em °C e converta para °F.
'''
c = float(input('Informe a temperatura em °C: '))
f = (9/5)*c + 32
print('A temperatura \033[1;35;44m{:.1f}°C\033[m corresponde a \033[4;36;45m{:.1f}°F\033[m.'.format(c,f))
| false |
b77ea812fed4008827e1f5e9ba3688b0413936e0 | liuluyang/mk | /py3-study/函数编程课上代码/1902/10-23/列表元组集合.py | 2,061 | 4.125 | 4 |
"""
列表 元组 集合
"""
# 可变的数据类型
# 增删改查
students = ["冯亚尼", "曹泽涵", "张文哲", "曹怡", "张子涵",
"李佳伦", "张灿武", "丁明宇", "张鱼洋", "郭利炜",
"谷宣言", "彭子权", "屈晓明", "张家泽", "张丫丫",
"高江涛", "尹梦许"]
# 创建
res = 'abcd'
lst = []
# print(list(res))
# print(len(students))
# 增
students.append('小绿')
students.insert(20, '小黑') # 不报错
students.extend(['小绿', '小红'])
# print(students + ['小绿', '小红'])
# print(students)
# 删
students.remove('小绿')
p = students.pop() # 不存在的索引位 出现错误
# print(p)
# print(students)
# 改
students[-1] = '小紫'
# print(students)
# 查
# print(students.index('小黑'))
# print(students[10]) # 不存在的索引位 出现错误
# print(students.count('小黑'))
#
# print(students[10:110])
# print(students)
# print(students[10:5:-2])
# print(list(range(10, 100, 5)))
# lst_new = []
# for name in students:
# lst_new.insert(0, name)
# print(lst_new)
############################################# 元组
# 不可变的数据类型
# 特点:安全 稳定
tuple_new = tuple(students)
tuple_02 = (1,) # 一个元素的元组 书写方式
print(type(tuple_02))
# print(tuple_new)
################################################ 集合
# 可变的数据类型
# 里面的元素是不可变的
# 去重
# & | - ^
set_new = set()
set_new02 = {1, 2, 1}
# print(set_new02)
# print(type(set_new))
f01 = {'小白', '小黑', '小绿', '小红'}
f02 = {'小蓝', '小黑', '小绿', '小紫'}
# # 差集
# # f01里面有的f02没有
# print(f01 - f02)
# # f02里面有的f01没有
# print(f02 - f01)
#
# # 并集
# print(f01 | f02)
#
# # 交集 共同的好友
# print(f01 & f02)
#
# # 对称差集
# print(f01 ^ f02)
# 增
f01.add('小雪')
f01.add('小白')
print(hash('小白'))
print(f01)
# 删
f01.remove('小白')
print(f01.pop()) # 随机删除一个
print(f01)
print('小白' in f01)
print(len(f01))
| false |
a3cdfed74619b44d548946095f460109d92fd979 | liuluyang/mk | /py3-study/BaseStudy/mk_09_if_study/study_1.py | 794 | 4.3125 | 4 |
"""
流程控制
"""
"""
之前的学习代码都是依次由上至下的执行,
如果想做一些复杂的控制就需要用到判断语句,
来决定运行那些代码
"""
"""
但分支
"""
# age = int(input('请输入年龄:')) #注意类型转换
# if age < 18: #注意语法冒号:
# print('未满18岁') #注意语法缩进
"""
双分支
"""
# age = int(input('请输入年龄:'))
# if age < 18:
# print('未满18岁')
# else:
# print('已满18岁')
"""
多分支
依次判断,符合一个条件之后,不会再去判断其他条件
"""
# num = 10
# my_num = int(input('输入数字:'))
#
# if my_num > num:
# print('大于%d'%(num))
# elif my_num < num:
# print('小于%s'%(num))
# else:
# print('等于%s'%(num))
#
# print('结束') | false |
91af16488a7330b32347e7b36eaadd1c5fb38be8 | liuluyang/mk | /py3-study/BaseStudy/mk_12_try_except_study/study_1.py | 962 | 4.3125 | 4 |
"""
程序异常处理
"""
name = '小绿'
age = 20
# result = name + age
# # result = age + name
# print(result)
"""
简单异常处理
"""
# try:
# result = name + age
# print('程序执行成功')
# except:
# print('程序错误')
"""
捕获指定的异常
"""
# try:
# #result = name + age
# # print('h'[1])
# print('程序执行成功')
# except TypeError:
# print('类型错误')
# except IndexError:
# print('取值错误')
"""
捕获所有异常并打印异常信息
"""
# try:
# print('h'[1])
# print('程序执行成功')
# except Exception as e:
# print('错误信息:', e)
"""
自定义异常类
异常的传递过程
"""
class MyException(Exception):
pass
try:
raise MyException('我的自定义异常')
except Exception as e:
print(e)
print(e.args)
"""
不要过度使用异常,不用用它代替正常流程控制
try里面的代码块不宜过大
不可忽略异常
"""
| false |
f6c023ea555d3ea22d698be34cf653723d84001e | liuluyang/mk | /作业练习题/分类练习题/基础练习题/函数01-答案.py | 1,573 | 4.53125 | 5 |
"""
1. 说出下面代码的执行结果
def inner():
print('我是小函数')
return 1
def outter():
print('我是大函数')
return inner
inner()
print(inner())
outter()
print(outter())
def outter():
print('我是大函数')
return inner()
outter()
print(outter())
"""
# 分别执行 查看结果
"""
2. 说出下面代码的执行结果:
def num_add(num):
if num >= 10:
return 11
num += 1
print(num)
num_add(num)
print(num)
num_add(1)
"""
# 执行查看结果
"""
3. 说出下面代码的执行结果:
def num_add(num):
if num >= 10:
return 11
num += 1
print(num)
print(num_add(num))
print(num)
num_add(1)
"""
# 执行查看结果
"""
4. 说一下 可迭代对象、迭代器对象、生成器函数、生成器对象分别是什么以及他们的区别:
"""
"""
学面向对象之前:
1. 一般我们认为 可作用于for循环的都是 可迭代对象,例如字符串。列表等
2. 一个可迭代对象被iter()函数转换之后,就变成了一个迭代器对象,next()函数可取出迭代器对象里面的值。
3. 生成器函数也是函数,只不过函数里面有yield关键字,也就是说函数里面有yield关键字的函数,我们就说他是生成器函数。
4. 生成器函数执行之后,就变成了一个生成器对象,生成器对象也是一个可迭代对象
from typing import Iterable, Iterator, Generator
上面导入的对象,可判断某一个对象的类型 例如:isinstance('hello', Iterale)
"""
| false |
23411f39fa55151f047c7ca8be02effad2e63172 | Siddhesh4501/Crypto-systems | /columnar_transposition_decryption.py | 1,700 | 4.1875 | 4 | import math
def row(s,key):
# to remove repeated alphabets in key
temp=[]
for i in key:
if i not in temp:
temp.append(i)
k=""
for i in temp:
k+=i
print("The key used for encryption is: ",k)
arr=[['' for i in range(len(k))]
for j in range(int(len(s)/len(k)))]
# To get indices as the key numbers instead of alphabets in the key, according
# to algorithm, for appending the elementsof matrix formed earlier, column wise.
kk=sorted(k)
d=0
# arranging the cipher message into matrix
# to get the same matrix as in encryption
for i in kk:
h=k.index(i)
for j in range(len(k)):
arr[j][h]=s[d]
d+=1
print("The message matrix is: ")
for i in arr:
print(i)
# the plain text
plain_text=""
for i in arr:
for j in i:
plain_text+=j
print("The plain text is: ",plain_text)
msg=input("Enter the message to be decrypted: ")
key=input("Enter the key in alphabets: ")
row(msg,key)
'''
----------OUTPUT----------
Enter the message to be decrypted: Mu b___mid____crnm___ ew ___o ee___ps ____ytoy___
Enter the key in alphabets: expensive
The key used for encryption is: expnsiv
The message matrix is:
['M', 'y', ' ', 'c', 'o', 'm', 'p']
['u', 't', 'e', 'r', ' ', 'i', 's']
[' ', 'o', 'w', 'n', 'e', 'd', ' ']
['b', 'y', ' ', 'm', 'e', '_', '_']
['_', '_', '_', '_', '_', '_', '_']
['_', '_', '_', '_', '_', '_', '_']
['_', '_', '_', '_', '_', '_', '_']
The plain text is: My computer is owned by me_______________________
>>>
'''
| true |
dbad692dfe4b44f82e4197ae7b43cf1d81943ce3 | python101ldn/exercises | /Session_6/6d_shopping_solution.py | 392 | 4.21875 | 4 | # Let's go shopping!
inventory = {'apples': 3, 'pears': 2, 'bananas': 0}
# The program should:
# Ask what the shopper would like to buy, and take user input.
# Minus 1 of that item from that inventory.
item_name = input('What would you like to buy?')
# this will fail if item_name isn't in the dictionary - see 6c solution!
inventory[item_name] = inventory[item_name] - 1
print(inventory)
| true |
0efec63613416aaa7bf368361284f5fab0e70b58 | python101ldn/exercises | /Session_6/6e_shopping_v2_solution.py | 1,038 | 4.34375 | 4 | # Let's go shopping!
inventory = {'apples': 3, 'pears': 2, 'bananas': 0}
# Add the following functionality to your shopping program:
# i. If that item doesn't exist, let the user know.
# ii. If that item is sold out, let the user know.
# iii. Also ask the user for how many items they'd like to buy.
item_name = input('What would you like to buy?\n')
if item_name in inventory:
if inventory[item_name] == 0:
print('Sorry, that item has sold out!')
else:
how_many = input('How many ' + item_name + ' would you like to buy?\n')
how_many = int(how_many) # convert string to number (int = integer)
new_total = inventory[item_name] - how_many
# Ensures your inventory is never minus
if new_total < 0:
print('Sorry, we could only sell you ' + str(inventory[item_name]) + ' ' + item_name)
inventory[item_name] = 0
else:
inventory[item_name] = new_total
else:
print('Sorry, we don\'t sell those.')
print('Our stock: ')
print(inventory)
| true |
ae735a634003f7fb5ecbe8e50cec871a868cc022 | momentum-cohort-2019-02/w2d1--house-hunting-keclements | /.vscode/house_practice.py | 1,626 | 4.5625 | 5 | # Test case:
# Enter your annual salary: 120000
# Enter the percent of your salary to save, as a decimal: .10
# Enter the cost of your dream home: 1000000
# Number of months: 183
# get annual income
annual_salary = int(input("Enter your annual salary:"))
# figure out how much I want to save each month
portion_saved = float(inpout("Enter the percentage of you salary to save as a decimal:"))
# annual income monthly income
monthly_salary= annual_salary / 12
# get the price of the house and the percentage for the down payment
portion_saved = float ()
# Figure out how much I'm saving each month as a percentage of my income
# each month,
amount_saved_each_month = portion_saved * monthly_salary
total_cost = float)input("enter")
# caclculate the interest -- current savings * rate (0.04) / 12
down_payment = total_cost + portion_saved
# add the amount I'm saving to a running total
# Set initial information
current_saving = 0
current_month = 1
interest_rate = 0.04
# each month while our savings is < down payment
while current_saving < down_payment:
# calculate interest -- current saving * rate (0.04) / 12
interest = curren_savings * interest_rate / 12
# add interest to current saving
#current_saving - current_saving + interest
current_saving += interest # same as current_saving
# add the amount I'm sacing to my current saving
current_saving += amount_saved_each_month
# add 1 to current month
current_month += 1
# Report how many months that took
print("Number of months:", current_month)
#each month (amount of savings)* rate
# see the word each means yo have a loop | true |
9fa56107bcf263be4f73411be0beae9d2ed18d1d | RohitDhankar/Machine-Learning-with-Python_ML_Py | /PythonBasics/temp_scripts/lsComp.py | 1,546 | 4.125 | 4 | #TODO -- starts Corey code
nums = [1,2,3,4,5,6,7,8,9,10]
ls_com = [n for n in nums]
print(ls_com)
ls_com_1 = [n*2 for n in nums] # Squares of All NUMS
print(ls_com_1)
ls_com_2 = [n for n in nums if n%2 ==0] # All Even NUMS Only
print(ls_com_2)
#
"""
Get a Tuple each -- for a Letter + Number Pair == (letter,number_int)
Letters to come from string -- abcd
Nums to come from List -- 0123
"""
print(" "*90)
ls_com_3 = [(str1,num_int) for str1 in "abcd" for num_int in range(4)] #
print(ls_com_3)
#
print(" "*90)
ls_vals = [["Nested_LS_1"],[1,2,3],["Nested_LS_2"],["Nested_LS_3"]]
ls_com_4 = [{str_keys,nested_lists} for str_keys in "abcd" for nested_lists in ls_vals] #
print(ls_com_4)
#TODO -- Corey code below ?
#List Comprehensions is the process of creating a new list from an existing one.
intsLs = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
# We want 'n' for each 'n' in intsLs
my_list = []
for n in intsLs:
my_list.append(n)
print(my_list)
#
my_list = [n for n in intsLs]
print(my_list)
#
# We want 'n*n' for each 'n' in nums
# my_list = []
# for n in nums:
# my_list.append(n*n)
# print(my_list)
# #
# my_list = []
# print(my_list)
#
animLS = ['cat', 'dog', 'rat']
def enumerateFunc(animLS):
for ids, animName in enumerate(animLS):
#print('#%d: %s' % (ids + 1, animName))
print('#%d: %s' % (ids, animName)) # 0 Index
print(" "*90)
#
enumerateFunc(animLS)
#
ls_ints = [0, 1, 2, 3, 4]
def sqrLsComp(ls_ints):
sqrs = [x ** 2 for x in ls_ints]
print(sqrs) #
print(" "*90)
#
sqrLsComp(ls_ints)
#
| false |
925b663842c68a898ebdc9fb448c6e7bfa23a92b | jokihassan/calc | /tcalc.py | 577 | 4.40625 | 4 | # Program make a simple calculator that can add, subtract, multiply and divide using functions
print(f"Select operation.")
print(f"1.+")
print(f"2.-")
print(f"3.*")
print(f"4./")
# Take input from the user
choice = input("Enter choice( +, -. *, / ):")
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
def switch_op(operator, x, y):
return {
"+": x + y,
"-": x - y,
"*": x * y,
"/": x / y
}.get(operator, "Please select a valid operator")
print(f"{num1} {choice} {num2} = {switch_op(choice,num1,num2)}")
| true |
b673d1b9ca5d9dcab43609caf70609d94fa26405 | pdinkins/cookbook | /DB/Physics/prime.py | 2,555 | 4.21875 | 4 | #Prime Number Checker
#Parker Dinkins
'''
This program asks for a number between 0 and 5000
If the number isn't in that range it asks for it again
When a proper number is entered it checks if it is prime
If the numbr is prime it prints the two factors
If the number is not prime it prints all the factors
Finally it asks if you want run the checker again or not
'''
# This function takes a number and prints the factors
def print_factors(x):
print("The factors of", x, "are:")
for i in range(1, x + 1):
if x % i == 0:
print(i)
print(x, "is NOT a prime number")
# this functoin check to see if a number is prime and if so prints that out
# if the numbe is not prime it pushes the user input variable into the print_factors function
def prime_checker():
try:
# user input
a = int(input("Enter a number between 0 and 5000: "))
# checks to make sure the number is within the specified range
if a > 5000:
# prints out and error if the check fails and reruns the function with clean memory
print('\n\t****ERROR****')
print('Enter a number between 0 and 5000\n')
return prime_checker()
# place hold variable
k = 0
# this finds the number of factors of the number
for i in range(1, a):
if a % i == 0:
k = k + 1
# this checks to see if the number has less than or one factor
# if the number satisfies this then it is prime and it prints out
if k <= 1:
print('The factors of your number are:')
print('1')
print(a, 'is a prime number')
# if the number has more than one factor it is not prime and it lands here
# the number is then put into the print_factors function
else:
print_factors(x=a)
# this handles the error when the user inputs something other than number into the input statement
except ValueError:
print('\n\t****Invalid*Input****\n\tPlease enter a number\n')
# loop variables
run = True
run1 = True
# first loop that runs the functions when the program one time when the program is opened
while run1:
prime_checker()
break
# second loop that asks the user if they want to run the program again or quit
while run:
option = input("\nContinue and run again? [y/n]: ").lower()
if option == "y":
prime_checker()
elif option == "n":
break
else:
print("\nNot a valid option. Please enter 'y' or 'n'")
| true |
23ec16528547f62e364ee252cf7ae4f841d6c624 | SquareKnight/onb-math | /solutions/euler030.py | 1,054 | 4.125 | 4 | """Digit fifth powers
n;Raise digits to nth power;int;5
#digits #power
Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:
1634 = 1**4 + 6**4 + 3**4 + 4**4
8208 = 8**4 + 2**4 + 0**4 + 8**4
9474 = 9**4 + 4**4 + 7**4 + 4**4
As 1 = 1**4 is not a sum it is not included.
The sum of these numbers is 1634 + 8208 + 9474 = 19316.
Find the sum of all the numbers that can be written as the sum of fifth powers of their digits.
"""
powers_list = dict()
def raise_to_nth(x, power):
global powers_list
digits = [powers_list[c] for c in str(x)]
return sum(digits)
def attempt_1(n):
global powers_list
powers_list = dict()
for i in range(0, 10):
powers_list[str(i)] = i**n
solutions = []
for i in range(2, 354294):
if i == raise_to_nth(i, n):
print(i)
solutions.append(i)
return sum(solutions)
def run(n):
return attempt_1(n)
if __name__ == '__main__':
print(run(5))
| true |
cfc7fc8732bea6fe22a2c31c7e9057f0ed70ec62 | micronax/python_huffman_rle_compressor | /bintree.py | 1,928 | 4.21875 | 4 | #!/usr/bin/env python3
__author__ = "Fabian Golle <me@fabian-golle.de>"
__copyright__ = "Fabian Golle <me@fabian-golle.de>"
__version__ = "1.0"
__revision__ = "f0b3ab7"
__status__ = "Production"
class Node(object):
"""Represents a Node in a binary tree"""
weight = 0
value = ''
left = None
right = None
def __init__(self, value, weight):
super(Node, self).__init__()
self.value = value
self.weight = weight
def is_leaf(self):
"""Checks, if the current node is a leaf"""
return ((self.left == None) and (self.right == None))
def __lt__(self, other):
"""Performs a real less than comparision between current and other Node"""
return (self.weight < other.weight)
def __gt__(self, other):
"""Performs a real greater than comparision between current and other Node"""
return (self.weight > other.weight)
def __eq__(self, other):
"""Checks, if current Node equals other Node"""
return (self.weight == other.weight) if (self and other) else False
def __repr__(self):
return repr(self.value) + ", " + repr(self.weight)
def __add__ (self, other):
"""Links two Nodes to a new parent one"""
if(isinstance(other, Node) == False):
raise NotImplementedError
#self.value + other.value
newNode = Node(None, self.weight + other.weight);
newNode.left = self;
newNode.right = other;
return newNode;
def traverseTree(self, method='preorder'):
if (method not in ['preorder', 'inorder', 'postorder', 'front']):
raise NotImplementedError
lft = self.left.traverseTree(method) if self.left is not None else [];
rght = self.right.traverseTree(method) if self.right is not None else [];
#cur = [self.value, self.weight];
cur = [self.weight];
if (method == 'preorder'):
return cur + lft + rght
elif (method == 'inorder'):
return lft + cur + rght
elif (method == 'postorder'):
return lft + rght + cur
elif (method == 'front'):
return cur if self.is_leaf() == True else [] + lft + rght
| true |
7417bf1933e1b9c43ba5be7d111269f6ce9c7ddc | JacobBHartman/holbertonschool-higher_level_programming | /0x0B-python-input_output/9-add_item.py | 900 | 4.25 | 4 | #!/usr/bin/python3
"""
this module contains a script that adds all arguments to a Python list,
and then save them to a file
"""
import json
from sys import argv
import os.path
def save_to_json_file(my_obj, filename):
"""
this functions writes an Object to a text file using a JSON
representation
"""
with open(filename, mode='w', encoding='utf-8') as json_file:
json.dump(my_obj, json_file)
def load_from_json_file(filename):
"""
this function creates an Object from a "JSON file"
"""
with open(filename, mode='r', encoding='utf-8') as f:
return json.load(f)
if __name__ == "__main__":
filename = "add_item.json"
my_obj = []
if os.path.isfile(filename):
my_obj = load_from_json_file(filename)
for i in range(1, len(argv)):
my_obj.append(argv[i])
save_to_json_file(my_obj, filename)
| true |
c752dd7a768d06d7ddace7a24e95278a95d0284e | LauIsaac/ECE434 | /hw01/etchasketch.py | 1,248 | 4.21875 | 4 | #!/usr/bin/env python3
"""
ECE434 HW1 Part 6: Etch-a-sketch
A simple etch-a-sketch program
"""
__author__ = "Isaac Lau"
__version__ = "0.1.0"
__license__ = "MIT"
"""
A helper function for cleanly printing a 2D list
"""
def printHelper(grid):
for row in grid:
for e in row:
print(e, end = " ")
print()
def main():
""" Main entry point of the app """
n = 15
m = 15
playerX = 7
playerY = 7
board = [["-"] * m for i in range(n)]
board[playerY][playerX] = 'P'
printHelper(board)
while True:
board[playerY][playerX] = 'X'
command = input('Please enter a direction (up, down, left, right, clear): ')
if command == 'up':
playerY -= 1
elif command == 'down':
playerY += 1
elif command == 'left':
playerX -= 1
elif command == 'right':
playerX += 1
elif command == 'clear':
board = [["-"] * m for i in range(n)]
board[playerY][playerX] = 'P'
printHelper(board)
if __name__ == "__main__":
""" This is executed when run from the command line """
main() | true |
94ec424c89decabfdda8c83f68cfd5daceac066b | lucashsouza/Desafios-Python | /CursoEmVideo/Aula20/ex097.py | 392 | 4.25 | 4 | # Exercicio 097 - Função para texto
'''
Faça um programa que tenha uma função chamada escreva(), que receba um texto
qualquer como parâmetro e mostre uma mensagem com o tamanho adaptável
'''
def mensagem(txt):
tam = len(txt)
print('~'*tam)
print(txt)
print('~'*tam, '\n')
mensagem('Hello, world!')
mensagem('Python é a a melhor linguagem de programação')
| false |
d9b005a66c52cae807fa3a7bd20d6764990ddafc | lucashsouza/Desafios-Python | /CursoEmVideo/Aula21/ex102.py | 1,253 | 4.40625 | 4 | """Crie um programa que tenha uma função fatorial() que receba dois parâmetros:
1. Indique o número a calcular
2. Show (Valor lógico) indicando se será mostrado na tela o processo de
cálculo do fatorial - Opcional
"""
def titulo():
print('-' * 45)
print('{:^45}'.format('Função Fatorial '))
print('-' * 45)
return ''
def fim():
from time import sleep
sleep(3)
return '\n*Fim de programa..*'
def fatorial(num=1, show=False):
"""
-> Calcula a fatorial de um número.
:param num: Número a ser calculado fatorial.
:param show: (opcional) Mostrar ou não a conta.
:return: valor da fatorial do número.
*Desenvolvido por Lucas Souza, github.com/lucashsouza *.
"""
fat = 1
for cnt in range(num, 0, -1):
if show:
print(f'{cnt}', end='')
if cnt > 1:
print(' x ', end='')
else:
print(' = ', end='')
fat *= cnt
return fat
# PROGRAMA PRINCIPAL
print(titulo())
n = int(input('Digite um número: '))
# Show = True / Mostra a conta
# Show = False / Não mostra a conta
print(fatorial(n, show=True))
print()
# Visualizar Docstring da funçao Fatorial ()
help(fatorial)
print(fim())
| false |
fc2ef9c296b7cf16c17b7f59f4987ad0db52d2ff | lucashsouza/Desafios-Python | /CursoEmVideo/Aula21/ex103.py | 856 | 4.15625 | 4 | """
Crie um programa que tenha uma função ficha(), que receba dois parametros opcionais:
1. Nome de um Jogador
2. Quantos gols ele marcou
O programa deverá ser capaz de mostrar a ficha do jogador, mesmo que algum dado não tenha sido informado corretamente.
"""
def titulo():
print('-' * 45)
print('{:^45}'.format('Função Ficha de jogadores '))
print('-' * 45)
return ''
def fim():
from time import sleep
sleep(3)
return '\n*Fim de programa..*'
def ficha(jog='<desconhecido>', gol=0):
print(f'\nJogador {jog} fez {gol} gol(s) no campeonato.')
# Programa principal
print(titulo())
nome = str(input('Nome do Jogador: '))
gols = str(input('Numero de Gols: '))
if gols.isnumeric():
gols = int(gols)
else:
gols = 0
if nome.strip() == '':
ficha(gol=gols)
else:
ficha(nome, gols)
print(fim())
| false |
bbc780ed0103def7945394ae4993eb9e6b2f5cba | SiddharthaSarma/python-learning | /variables/lists.py | 443 | 4.1875 | 4 | # tuples are immutable objects where as lists are mutable objects
# tuples are indicated by braces() where as lists are indicated by square brackets[]
def main():
# tuples
a = (1, 2, 3, 4, 5)
print(a)
# lists
b = [1, 2, 3, 4, 5]
print(b)
# looping over lists
for i in b:
print(i)
print()
# Looping over strings
string = 'Hello'
for i in string:
print(i)
print()
main()
| true |
4f3753cb67e07505f1414ac8c0b4a91542c9819a | kyleyasumiishi/codewars | /python/spin_words.py | 524 | 4.15625 | 4 |
# Takes a string of one or more words, and returns the same string, but with all words n letters or more reversed
def spin_words(sentence, n):
updated_words_list = []
for word in sentence.split(" "):
updated_words_list.append(word[::-1]) if len(word) >= n else updated_words_list.append(word)
return " ".join(updated_words_list)
print(spin_words("Write a function that takes in a string of one or more words, and returns the same string, but with all five or more letter words reversed", 5)) | true |
0a7d91faa7d44763e4fb03e39abbdae36ec7c6ca | Shivani225/FST-M1 | /python/Activity4.py | 1,255 | 4.15625 | 4 | Player1 = input("Enter the name of Player 1: ")
Player2 = input("Enter the name of Player 2: ")
while True:
choice_Player1 = input(Player1 + " ,what do you choose in Rock, Paper, Scissor?").lower()
choice_Player2 = input(Player2 + " ,what do you choose in Rock, Paper, Scissor?").lower()
if(choice_Player1 == choice_Player2):
print("It is a tie!")
elif(choice_Player1 =="rock"):
if(choice_Player2 == "paper"):
print("Paper Wins!")
else:
print("Scissor Wins!")
elif(choice_Player1 =="paper"):
if(choice_Player2 == "scissor"):
print("scissor Wins!")
else:
print("Rock Wins!")
elif(choice_Player1 =="scissor"):
if(choice_Player2 == "rock"):
print("Rock Wins!")
else:
print("Paper Wins!")
else:
print("Invalid Input! Please select something in Rock, Paper or Scissor")
repeat_game = input("Do you want to play another round, Yes or No").lower()
if(repeat_game == "yes"):
pass
elif(repeat_game == "no"):
raise SystemExit
else:
print("You entered invalid input, exiting the game. Thank You")
raise SystemExit
| true |
5ba9fd313c9efef0b23e68a4013b04456c031c88 | gabrielSSimoura/OddOrEven | /main.py | 441 | 4.1875 | 4 | # Ask the user for a number.
# Depending on whether the number is even or odd, print out an appropriate message to the user.
def isEven(number):
if (number % 2 == 0):
return 1
else:
return 0
def main():
userNumber = int(input("Type a number: "))
userNumber = isEven(userNumber)
if(userNumber):
print("Your number is Even")
else:
print("Your number is Odd")
return 0
main()
| true |
aa203245f314df29d0c81f31562687105f44db59 | cburian/Learning_DataStructures_Algorithms | /Algorithms/Recursion/a3_factorial.py | 857 | 4.4375 | 4 | """
"""
def factorial_iterative(n):
fact = 1
for i in range(1, n+1):
fact *= i
return fact
# test
print('Factorial iterative: ', end='')
print(factorial_iterative(4))
def factorial_recursive(n):
if n == 0:
return 1
return factorial_recursive(n-1) * n
# test
print('Factorial recursive: ', end='')
print(factorial_recursive(4))
# ======= dynamic programming =======
def factorial(n, memory={0: 1, 1: 1}):
"""Calculates factorial using dynamic programming.
Args:
n: the natural number that is the input for the algorithm.
memory: the results dictionary will be updated with each function call.
Returns:
factorial of number n.
"""
if n in memory:
return memory[n]
else:
memory[n] = n * factorial(n-1)
return memory[n]
print(factorial(4))
| true |
7b4ab33980d367bf41a09c349c82c6a1fc53547d | cburian/Learning_DataStructures_Algorithms | /Data_Structures/PyCharm_DataStr/Implemented Data Structures/b_queue_class.py | 1,619 | 4.46875 | 4 | class Queue:
def __init__(self):
self.items = []
def enqueue(self, item):
"""
Takes in an item and inserts that item into the 0th
index of the list that is representing the Queue
Runtime is O(n) because inserting into the 0th
index of a list forces all other items in the list
to move one index to the right.
"""
self.items.insert(0, item)
def dequeue(self):
"""
Returns and removes the front-most item of the Queue,
represented by the last item in the list.
The runtime is O(1), because indexing to the end of a
list happens in constant time
"""
if self.items:
return self.items.pop()
return None
def peek(self):
"""
Returns the last item in the list, the front-most
item in teh queue.
The runtime is constant because we're just indexing
to the last item of the list and returning the value
found there.
"""
if self.items:
return self.items[-1]
return None
def size(self):
"""
Returns the size of the Queue, represented by the
length of the list
The runtime is constant time, because we're returning
the length
"""
return len(self.items)
def is_empty(self):
"""
Returns Boolean expressing whether or not the list
representing the Queue is empty.
Runs in constant time, because it's only checking
for equality.
"""
return self.items == []
| true |
6b1bd681f532ac5f861ba7534516c2c529c9fc20 | cburian/Learning_DataStructures_Algorithms | /Data_Structures/DS02_Queue/ch2_challenge_print_queue_my.py | 2,025 | 4.3125 | 4 | """
Create 3 classes that, together, model how a printer
could take print jobs out of a print queue.
Requirements:
1st class: PrintQueue - follows the queue data structure
implementation
2nd class: Job - pages attribute = random from 1 to 10
- print_page() - decrements pages
- check_complete() - checks if all pages
have been printed
3rd class: Printer - get_job() - makes use of the queue's
built-in dequeue method to take
the first job in the print queue
off of the queue.
- !account for the case where
PrintQueue.items is empty
- print_job()
"""
from Data_Structures.DS02_Queue.ch2_01_queue_class import Queue
from random import randint
class PrintQueue(Queue):
def __init__(self):
super().__init__()
class Job:
def __init__(self):
self.pages = randint(1, 10)
self.print_q = PrintQueue()
self.pages_left = self.print_q.size()
def print_page(self):
"""
Decrements pages
"""
self.pages_left -= 1
return self.print_q.dequeue()
def check_complete(self):
"""
Checks weather or not all pages have been printed
"""
return self.print_q.is_empty()
# def pages_left(self):
# """
# Returns the nr of pages left to print
# """
# return self.print_q.size()
class Printer:
def __init__(self):
self.job = Job()
def get_job(self):
"""
Makes use of the queue's built-in dequeue method to take
the first job in the print queue off of the queue.
! Account for the case where PrintQueue.items is empty
"""
if self.job.check_complete():
return None
return self.job.print_page()
def print_job(self):
return self.get_job()
| true |
66ad6ca76124a9a13aaea94b881b8b69e1d3cdc7 | artyrkonovalov/ITstepPython | /Манипуляция с текстом.py | 839 | 4.125 | 4 | #Манипуляция с текстом
text = "Всегда мечтали сделать слова краивыми и легкими?"
print('Исходный текст')
print(text)
print('\nА в верхнем регистре слабо?')
print(text.upper())
print('\nНу а про нижний регистр что скажите?')
print(text.lower())
print('\nХмб а как сделать все первые буквы большими?')
print(text.title())
print('\nКак бы это че-нить вредительский подменить?')
print(text.replace("красивыми',"страшными"))
print('\nПоменяем регистры наоборот = 0')
print(text.swapcase())
print('\nНу а теперь все как и было...')
print(text)
input("\n\nPress Enter, to continue...")
| false |
470800e54e2f05568125f2799cb14cd7b364a7be | artyrkonovalov/ITstepPython | /Python/Задание 4.py | 372 | 4.28125 | 4 | '''Вычислить площадь круга S=pi*r*r, pi описать как константу,
значение переменной r ввести с клавиатуры.'''
pi = 3.14
pi = float(pi)
r = float(input('Введите радиус = '))
S = pi * r * r
print("Площадь окружности = ", S)
input("Press Enter to continue...")
| false |
fdacd8b3f59219b66247c11614b2388be5d1e05c | vish856/Python-programs | /grade.py | 933 | 4.28125 | 4 | #Lists Challenge 6: Grade Sorter App
print("Welcome to the Grade Sorter App")
#Initialize list and get user input
grades = []
grades.append((input("what's you first grade(9-100) :")))
grades.append((input("what's you second grade(9-100) :")))
grades.append((input("what's you third grade(9-100) :")))
grades.append((input("what's you forth grade(9-100) :")))
print("\nYour grades are: " + str(grades))
#Sort the list from highest to lowest
grades.sort(reverse=True)
print("\nYour grades from highest to lowest are: " + str(grades))
#Removing the lowest two grades.
print("\nThe lowest two grades will now be dropped.")
removed_grade = grades.pop()
print("Removed grade: " + str(removed_grade))
removed_grade = grades.pop()
print("Removed grade: " + str(removed_grade))
#Recap remaining grades
print("\nYour remaining grades are: " + str(grades))
print("Nice work! Your highest grade is " + str(grades[0]) + ".")
| true |
82f2cc6703e8b4ab7c836d712c09790f49839932 | keshavprasadgubbi/Project1 | /strings.py | 1,202 | 4.46875 | 4 | print("Giraffe Academy ")
#creating a string variable
phrase = "Elephant Academy"
print(phrase + " is awesome!") #can only conctenate string variables
#Functions : Little block of code that we can run and will
# perform a specific operation for us; can use functions to
#modify our strings or get information about our strings
#to call a function use .function_name()
# common preexisting string variable related functions :
# .lower(),.upper()
#to check if the string is given way or not, can use many .is_functionname() and will return a true or false value
#can use these functions in combinations with each other
print(phrase.lower())
print(phrase.upper())
print(phrase.islower())
print(phrase.lower().isupper())
print(phrase.upper().isupper())
#can figure out length of the string with len() function; can also get the individual
#character via the index with string_variable[obj], with index starting with 0
print(len(phrase))
print(phrase[10])
# .index() function is useful for passing the parameters as arguments to the function
# and will return the value at its particular index
print(phrase.index("Aca"))
# .replace(old_str, new_str) function
print(phrase.replace("Academy", "is Cute!")) | true |
f570bb2d85331acf5e290eade2441c482681c43a | Jonwodi/Dictionary-Data-Structure | /main.py | 2,264 | 4.28125 | 4 | # Dict items are key value pairs enclosed in curly brackets
# Dict is ordered as of python 3.7
# Dict is mutable
# Dict keys are unique, cannot have duplicates
# Elements can be of different data types
'''
Dict Attributes
'''
# print(dir(dict))
# print(help(dict.pop))
'''
Creating Python Dictionary
'''
# dict = {}
# dict = {"Name": "Jordan", "Age": 23}
# dict["Age"] = 24
# dict = dict([("MJ", 23), ("Kobe", 24)])
# print(dict)
# print(type(dict))
'''
Access Dictionary Values
'''
# dict = {"Name": "Jordan", "Age": 23}
# print(dict["Name"])
# print(dict.get("Age"))
# print(dict.keys())
# print(dict.values())
# dict = [{"Name": "Jordan", "Age": 23},{"Name": "Steph", "Age": 30}]
# print(type(dict))
# print(dict)
# print(dict[0])
# print(dict[1])
# print(dict[1]["Name"])
# for n in range(len(dict)):
# print(dict[n]["Name"])
# for n in range(len(dict)):
# print(dict[n]["Age"])
'''
Changing Dictionary elements
'''
# dict = {"Name": "Jordan", "Age": 23}
# dict["Name"] = "Jay"
# dict["Age"] = 24
# print(type(dict))
# print(dict)
# print(id(dict))
# ==========================================
# dict = {"Name": "Jordan", "Age": 23}
# dict.update({"Name": "Steph", "Age": 30})
# dict["Age"] = 24
# print(type(dict))
# print(dict)
# print(id(dict))
# ==========================================
# dict = {"Name": "Jordan", "Age": 23}
# dict.setdefault("Name","Steph")
# dict.setdefault("Language","Python")
# dict["Age"] = 24
# print(type(dict))
# print(dict)
# print(id(dict))
'''
Remove Element From Dictionary
'''
# dict = {"Name": "Jordan", "Age": 23}
# dict.pop("Name")
# print(type(dict))
# print(dict)
# print(id(dict))
# =====================================
# dict = {"Name": "Jordan", "Age": 23}
# dict.popitem()
# print(type(dict))
# print(dict)
# print(id(dict))
# ==========================================
# dict = {"Name": "Jordan", "Age": 23}
# dict.clear()
# print(type(dict))
# print(dict)
# print(id(dict))
# =============================================
# dict = {"Name": "Jordan", "Age": 23}
# del dict
# print(type(dict))
# print(dict)
# print(id(dict))
'''
Dictionary Membership Test
'''
# dict = {"Name": "Jordan", "Age": 23}
# print("Name" in dict)
# print("Name" not in dict)
# print("Names" in dict)
| false |
7978dca630cf4056b5d606ebc310992df61e653d | Astromniac/Projects | /Implementation/Collatz/collatz.py | 359 | 4.375 | 4 | value = input("Please enter a number...\n")
try:
value = int(value)
except ValueError:
print("\nYou did not enter a valid integer...")
counter = 0
while value != 1:
if value % 2 == 0:
value = value / 2
else:
value = value * 3 + 1
print(value)
counter = counter + 1
print("The number of steps to reach 1 is", counter) | true |
f1e8d510edc8198c76e348cf782f6e0f8b415eee | wuworkshop/LPTHW | /ex3/ex3-ec1.py | 1,035 | 4.3125 | 4 | # Prints 'I will now count my chickens:'
print "I will now count my chickens:"
# Prints 'Hens 30'
print "Hens", 25 + 30 / 6
# Prints 'Roosters 97'
print "Roosters", 100 - 25 * 3 % 4
# Prints 'Now I will count the eggs:'
print "Now I will count the eggs:"
# Prints '7' even though it should be 6.75. This is due to how
# computers handle fractions - see floating-point-gui.de for explanation
print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
# Prints 'Is it true that 3 + 2 < 5 - 7?'
print "Is it true that 3 + 2 < 5 - 7?"
# Prints 'False'
print 3 + 2 < 5 - 7
# Prints 'What is 3 + 2? 5'
print "What is 3 + 2?", 3 + 2
# Prints 'What is 5 - 7? -2'
print "What is 5 - 7?", 5 - 7
# Prints 'Oh, that's why it's False.'
print "Oh, that's why it's False."
# Prints 'How about some more.'
print "How about some more."
# Prints 'Is it greater? True'
print "Is it greater?", 5 > -2
# Prints 'It is greater or equal? True'
print "It is greater or equal?", 5 >= -2
# Prints 'Is it less or equal? False'
print "Is it less or equal?", 5 <= -2 | true |
ef6c96d27f6fe639e573985a4dc0a578bde79d6d | Yosha2707/data_structure_algorithm | /asigments_files/dp_2/knapsack.py | 1,487 | 4.125 | 4 | # 0 1 Knapsack - Problem
# Send Feedback
# A thief robbing a store can carry a maximal weight of W into his knapsack. There are N items, and i-th item weigh 'Wi' and the value being 'Vi.' What would be the maximum value V, that the thief can steal?
# Input Format :
# The first line of the input contains an integer value N, which denotes the total number of items.
# The second line of input contains the N number of weights separated by a single space.
# The third line of input contains the N number of values separated by a single space.
# The fourth line of the input contains an integer value W, which denotes the maximum weight the thief can steal.
# Output Format :
# Print the maximum value of V that the thief can steal.
# Constraints :
# 1 <= N <= 20
# 1<= Wi <= 100
# 1 <= Vi <= 100
# Time Limit: 1 sec
# Sample Input 1 :
# 4
# 1 2 4 5
# 5 4 8 6
# 5
# Sample Output 1 :
# 13
# Sample Input 2 :
# 5
# 12 7 11 8 9
# 24 13 23 15 16
# 26
# Sample Output 2 :
# 51
from sys import stdin
def knapsack(weights, values, n, maxWeight) :
pass
def takeInput() :
n = int(stdin.readline().rstrip())
if n == 0 :
return list(), list(), n, 0
weights = list(map(int, stdin.readline().rstrip().split(" ")))
values = list(map(int, stdin.readline().rstrip().split(" ")))
maxWeight = int(stdin.readline().rstrip())
return weights, values, n, maxWeight
#main
weights, values, n, maxWeight = takeInput()
print(knapsack(weights, values, n, maxWeight)) | true |
6ed56b3d731ffaa06088196fbabf252350722367 | dtekluva/COHORT3B9 | /builtinfunctions.py | 2,637 | 4.25 | 4 | # values_range = range(10) # by default if range is given only one option then the it will stat from zero and end at the option it is passed, step is equal to 1 by default
# print(values_range)
# values_list = list(values_range) # a range must be converted to a list to see its values
# print(values_list)
# values_range = range(15, 30, 3) # range
# print(values_range)
# values_list = list(values_range)
# print(values_list)
# ## REVERSED
# reversed_list = list(reversed(values_list)) # reversed takes a list and flips it making the first item become the last and the last item become the first. This function returns a reverse object by default and needs to be converted into a list to view it's items.
# print(reversed_list)
# # ROUND
# x = 10.33343
# rounded_value = round(x)
# print(rounded_value)
# rounded_value = round(x, 4) # round take a number and the number of decimal places required and rounds it off according to the decimal places.
# print(rounded_value)
# sorted builtin function
values = [2,6,1,9,2,2,4,5]
sorted_values = sorted(values) # takes an unsorted range of values and sorts in ascending order. To sort in descending order the argument reversed can also be passed as set to true.
print(sorted_values)
sorted_values = sorted(values, reverse=True)
print(sorted_values)
# sum built in function
print(sum([2,6,1,9,2,2,4,5]))
print(sum([50,50]))
# dict built in function
# students = dict(ade = ["ade", 30, 105], john = ["john", 25, 147], jake = ["jake", 40, 160])
# print(students)
# my_stuff= dict()
# print(my_stuff)
# # "adamu"
# # 10000
# # [1000,1000,1000]
# # sets are unordered and do not allow repitition they can be used to get unique values in a list of numbers.
# print(values)
# print(set(values))
# MAP TAKES A LIST OF VALUES AND ALSO A FUNCTION AND THEN TRIES TO DO THE FUNCTION ON EACH OF THE VALUES OF THE LIST OF VALUES
# names = ["Jonah", "Kunle", "Saheed", "Lekan"]
# def make_upper(name):
# return "Mr. " + name.upper()
# upper_case_names = map(make_upper, names) # CONVERT ALL NAMES IN LIST TO UPPER CASE AND ADD MR TO THEM
# print(list(upper_case_names))
# names = ["Jonah", "Kunle", "Saheed", "Lekan"]
# def make_upper(name):
# return sorted(name.upper())
# upper_case_names = map(make_upper, names)
# print(list(upper_case_names))
# numbers = [1,2,3,4,5,6,7,8,9]
# def square_nums(number):
# return number * number
# squared_nums = map(square_nums, numbers)
# print(list(squared_nums))
# ages = [23, 44, 20, 38, 19, 15]
# def square_nums(number):
# return 2021 - number
# squared_nums = map(square_nums, ages)
# print(list(squared_nums))
| true |
010cee46dc86b6b6cbf015e17714ac7e2825ef02 | 191akhil/python-files | /add.py | 485 | 4.1875 | 4 | #write a program to take 2 numbers from the user,
#then take option to add/subtract/mutiple/divide
#and perform that operation
a=int(input("value of a:"))
b=int(input("value of b:"))
c=a+b
print("addition of a and b:",c)
d=a-b
print("substaction of a and b:",d)
e=a*b
print("multiplication of a and b:",e)
f=a/b
print("division of a and b:",f)
OUTPUT
value of a:6
value of b:8
addition of a and b: 14
substaction of a and b: -2
multiplication of a and b: 48
division of a and b: 0.75
| true |
3db7112d28ce4b0babb121c31c0d2aceccae3911 | climb4hope/algorithms | /python/src/matrix.py | 2,668 | 4.21875 | 4 |
class Matrix:
"""
This class describes the matrix
"""
def __init__(self, m, n, data):
self.matrix = data
self.m = m
self.n = n
def __str__(self):
#s = '\n'.join([' '.join([str(item) for item in row]) for row in self.rows])
#return s + '\n'
pass
def transpose_matrix(matrix):
"""
This method transposes matrix in place
:param matrix:
:return:
"""
row_num = len(matrix)
col_num = len(matrix[0])
new_matrix = [[0] * row_num for c in range(col_num)]
print_matrix(matrix)
for r in range(row_num):
for c in range(col_num):
new_matrix[c][r] = matrix[r][c]
print_matrix(new_matrix)
def transpose_matrix_in_place(matrix):
"""
This method transposes the matrix in place without
the use of the external memory (except one element)
:param matrix:
:return:
"""
row_num = len(matrix)
col_num = len(matrix[0])
# Check if the matrix is square
if row_num == col_num:
for c in range(col_num - 1):
for r in range(c + 1, row_num):
tmp = matrix[c][r]
matrix[c][r] = matrix[r][c]
matrix[r][c] = tmp
else:
# the matrix is not square
pass
return matrix
def cycle_based_transposition(matrix, M, N):
"""
Performs cycle based matrix transposition
:param matrix:
:param N:
:param M:
:return:
"""
Q = N * M - 1
# perform data swapping
for k in range(1, Q):
# Generate cycles
cycles = []
c = k
while True:
c = c * N % Q
cycles.append(c)
if c == k:
break
# Move teh data in each cycle
l = len(cycles)
tmp = matrix[k]
print(l, cycles)
for i in reversed(range(1, l)):
matrix[cycles[i]] = matrix[cycles[i-1]]
matrix[cycles[0]] = tmp
return matrix
def print_matrix(matrix, M, N):
"""
This method prints the matrix
:param matrix:
:return:
"""
for r in range(N):
s = '['
for c in range(M - 1):
s += str(matrix[r][c]) + ', '
s += str(matrix[r][N - 1]) + ']'
print(s)
return
if __name__ == "__main__":
matrix = [[1, 2],
[3, 4],
[5, 6]]
#m1 = transpose_matrix(matrix)
#transpose_matrix_in_place(matrix)
print_matrix(matrix, 3, 2)
cycle_based_transposition(matrix, 3, 2)
print_matrix(matrix, 3, 2)
| true |
db42f9407086d7ac26c2f15dd59843c80d0e75a2 | emilgab/caesar-cipher | /caesar.py | 1,896 | 4.1875 | 4 | # imports the string module for getting alphabet
import string
class CaesarCipher():
alphabet = string.ascii_lowercase
def __init__(self, seed):
self.seed = seed
# constructs a ciphered alphabet from the seed set by the user
self.cipher_alphabet = self.alphabet[self.seed:] + self.alphabet[0:self.seed]
def encrypt(self, message):
# goes through the message and encrypts it using the index position of each letter in the original alphabet.
encrypted_msg = ""
for char in message:
if char == " ":
encrypted_msg += " "
else:
encrypted_msg += self.cipher_alphabet[(self.alphabet.index(char.lower()))]
print(encrypted_msg)
def decrypt(self, message):
# reverses the process of encryption by using the ciphered alphabet index in the original alphabet.
decrypted_msg = ""
for char in message:
if char == " ":
decrypted_msg += " "
else:
decrypted_msg += self.alphabet[(self.cipher_alphabet.index(char.lower()))]
print(decrypted_msg)
def __repr__(self):
return f"The seed for this cipher is {self.seed}"
if __name__ == "__main__":
seed_in = int(input("What should the seed (position fix) be? "))
t = CaesarCipher(seed_in)
print("Cipher created successfully! Seed: {} \n".format(t.seed))
decision = input("Type ENC to encrypt a message or DEC to decrypt as message. ")
if decision.lower() == "enc":
raw_msg = input("What message do you want to encrypt? ")
print("Your encrypted message is: ")
t.encrypt(raw_msg)
elif decision.lower() == "dec":
enc_msg = input("What encrypted message do you want to decrypt? ")
print("Your message decrypted reads: ")
t.decrypt(enc_msg)
| true |
e06ace56adaa42c063441be92b459e7f1fdfe0ea | T-Santos/Daily-Coding-Problems | /9_DCP.py | 1,341 | 4.1875 | 4 | '''
Given a list of integers, write a function that returns the
largest sum of non-adjacent numbers.
For example:
[2, 4, 6, 8] should return 12, since we pick 4 and 8.
[5, 1, 1, 5] should return 10, since we pick 5 and 5.
'''
#from math import abs
def largest_sum_1(numbers):
# O(N^2) solution - nested loops
if not numbers:
return 0
if len(numbers) <= 2:
return 0
largest = 0
for num_1_pos, num_1 in enumerate(numbers[:-2]):
for num_2 in numbers[num_1_pos+2:]:
largest = num_1 + num_2 if num_1 + num_2 > largest else largest
return largest
def largest_sum(numbers):
# O(nlogn) - for the sort
if not numbers:
return 0
if len(numbers) <= 2:
return 0
sort_pos = sorted(
[(number,position) for position,number in enumerate(numbers)],
reverse = True,
key = lambda x: x[0])
largest = sort_pos[0]
second_largest = sort_pos[1] if abs(sort_pos[0][1] - sort_pos[1][1]) > 1 else sort_pos[2]
return largest[0] + second_largest[0]
def unit_tests():
assert largest_sum([]) == 0
assert largest_sum([1,2]) == 0
assert largest_sum([1,1,1]) == 2
assert largest_sum([1,2,3]) == 4
assert largest_sum([2,4,6,8]) == 12
assert largest_sum([5,1,1,5]) == 10
assert largest_sum([2,8,3,8]) == 16
assert largest_sum([5,4,3,2,1]) == 8
print("PASS")
def main():
unit_tests()
if __name__ == '__main__':
main() | true |
79337163486a78485edaaf830a69be2840a13ca9 | Rosmend-Morathis/learnpython | /ReturnFunction.py | 922 | 4.21875 | 4 | # 利用闭包返回一个计数器函数,每次调用它返回递增整数:
# 闭包:
# 在一个函数 f 中又定义了函数 g,并且,内部函数 g 可以引用外部函数 f 的参数和局部变量
# 当外部函数 f 返回内部函数 g 时,相关参数和变量都保存在返回的函数中。
# 返回的函数并没有立刻执行,而是直到调用了f()才执行
def createCounter():
n = 0
def counter():
nonlocal n
# 如果没有nonlocal声明(3.2版本后引入),会发生异常 UnboundLocalError
# local variable 'n' referenced before assignment
n = n + 1
return n
return counter
# 测试:
counterA = createCounter()
print(counterA(), counterA(), counterA(), counterA(), counterA()) # 1 2 3 4 5
counterB = createCounter()
if [counterB(), counterB(), counterB(), counterB()] == [1, 2, 3, 4]:
print('测试通过!')
else:
print('测试失败!') | false |
945486d497de5a4cb3a824058d42e30a11acf992 | dheeraj-2000/dsalgo | /CodeVita/railway.py | 972 | 4.21875 | 4 | # Program to find minimum number of platforms required on a railway station
# Returns minimum number of platforms reqquired
def findPlatform(arr,dep,n):
# Sort arrival and departure arrays
arr.sort()
dep.sort()
# plat_needed indicates number of platforms needed at a time
plat_needed = 1
result = 1
i = 1
j = 0
# Similar to merge in merge sort to process all events in sorted orderwhile (i < n and j < n):
# If next event in sorted order is arrival, increment count of platforms neededif (arr[i] < dep[j]):
plat_needed+=1
i+=1
# Update result if needed if (plat_needed > result):
result = plat_needed
# Else decrement count of platforms neededelse:
plat_needed-=1
j+=1
return result
# driver code
arr = [900, 940, 950, 1100, 1500, 1800]
dep = [910, 1200, 1120, 1130, 1900, 2000]
n = len(arr)
print("Minimum Number of Platforms Required = ",findPlatform(arr, dep, n))
| true |
5c8ab3367b9af1ce0085ca9669c1210ba464b652 | dheeraj-2000/dsalgo | /DP/edit distance.py | 637 | 4.125 | 4 | # Function to find Levenshtein Distance between X and Y
# m and n are the number of characters in X and Y respectively
def dist(X, m, Y, n):
# base case: empty strings (case 1)
if m == 0:
return n
if n == 0:
return m
# if last characters of the strings match (case 2)
cost = 0 if (X[m - 1] == Y[n - 1]) else 1
return min(dist(X, m - 1, Y, n) + 1, # deletion (case 3a))
dist(X, m, Y, n - 1) + 1, # insertion (case 3b))
dist(X, m - 1, Y, n - 1) + cost) # substitution (case 2 + 3c)
if __name__ == '__main__':
X = "kitten"
Y = "sitting"
print("The Levenshtein Distance is", dist(X, len(X), Y, len(Y)))
| false |
dbd08142d4a0bd08388bd3f2a937286ba0753de5 | dheeraj-2000/dsalgo | /Top Interview Questions/Solutions/Arrays/ReverseTheArray.py | 318 | 4.1875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
#code
# Link to question - https://practice.geeksforgeeks.org/problems/reverse-the-string/0
def reverse(li):
for ele in li:
print(ele[::-1])
numbers = int(input())
li = []
for i in range(numbers):
ele = input()
li.append(ele)
reverse(li)
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.