blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
b87cafe0bec26f966a8c027f0aa4e3311be3a18f | chris4540/algorithm_exercise | /basic/arr_search/rotated_arr/simple_approach.py | 1,736 | 4.3125 | 4 | """
https://www.geeksforgeeks.org/search-an-element-in-a-sorted-and-pivoted-array/
1) Find out pivot point and divide the array in two
sub-arrays. (pivot = 2) /*Index of 5*/
2) Now call binary search for one of the two sub-arrays.
(a) If element is greater than 0th element then
search in left array
(b) Else Search in right array
(1 will go in else as 1 < 0th element(3))
3) If element is found in selected sub-array then return index
Else return -1.
"""
from typing import List
def find_pivot_idx(arr: List[int]) -> int:
""" Find the pivot point using binary search
Example:
>>> find_pivot_idx([3, 4, 5, 6, 1, 2])
3 # becasue arr[3] is 6
>>> find_pivot_idx([3, 4, 5, 6, 7, 8, 1, 2])
55
"""
def _find_pivot_idx_rec(arr: List[int], low: int, high: int):
# base cases for recussion
if high < low:
return -1 # cannot find
if high == low:
return high
# ----------------------------
mid = (low + high) // 2
print("mid=", mid)
assert mid < high
# consider if we pin-point the pivot
if (arr[mid] > arr[mid+1]):
return mid
if (arr[mid-1]> arr[mid]):
return mid-1
if arr[low] >= arr[mid]:
return _find_pivot_idx_rec(arr, low, mid-1)
# if arr[mid+1] >= arr[high]:
return _find_pivot_idx_rec(arr, mid+1, high)
# -------------------
ret = _find_pivot_idx_rec(arr, 0, len(arr)-1)
if ret == -1:
raise ValueError("Cannot find the pivot point.")
return ret
if __name__ == '__main__':
arr = [3, 4, 5, 6, 7, 8, 1, 2]
res = find_pivot_idx(arr)
print(res) | true |
4a3368612d71c0d50ea714669551caf6922696ba | Sakshipandey891/sakpan | /vote.py | 285 | 4.3125 | 4 | #to take age as input & print whether you are eligible or not to vote?
age = int(input("enter the age:"))
if age==18:
print("you are eligible for voting")
elif age>=18:
print("you are eligible for voting")
else:
print("you are not eligible for voting")
| true |
d4fc59edb7222118899818e3a6bfb3e84d57797e | MikhaelMIEM/NC_Devops_school | /seminar1/1.py | 574 | 4.21875 | 4 | def reverse_int(value):
reversed_int = 0
while value:
reversed_int = reversed_int*10 + value%10
value = value // 10
return reversed_int
def is_palindrome(value):
if value == reverse_int(value) and value%10 != 0:
return 'Yes'
else:
return 'No'
if __name__ == '__main__':
while True:
try:
val = abs(int(input()))
except ValueError:
print('Value is not integer')
continue
except KeyboardInterrupt:
break
print(is_palindrome(val))
| true |
b4b5b23dff3ef54135b31a52c397ab7bb347c298 | ashwani99/ds-algo-python | /sorting/merge_sort.py | 1,092 | 4.34375 | 4 | def merge_sort(arr):
l = len(arr)
return _merge_sort(arr, 0, l-1)
def _merge_sort(arr, start, end):
if start < end:
mid = (start+end)//2
_merge_sort(arr, start, mid)
_merge_sort(arr, mid+1, end)
merge(arr, start, mid, end)
return arr
def merge(arr, start, mid, end):
result = []
left = start
right = mid+1
# compare and fill while both left and right array are not empty
while left <= mid and right <= end:
if arr[left] <= arr[right]:
result.append(arr[left])
left += 1
else:
result.append(arr[right])
right += 1
# if left has some left put all in result
while left <= mid:
result.append(arr[left])
left += 1
# if right has some left put all in result
while right <= end:
result.append(arr[right])
right += 1
# replacing values into the original array
for i in range(len(result)):
arr[i+start] = result[i]
if __name__ == '__main__':
print(merge_sort([5, 4, 3, 2, 1, -9, 5, 3]))
| true |
8839d7b99405de758cab6ca4c4bd04718891c34c | ashwani99/ds-algo-python | /sorting/mergesort_inplace.py | 872 | 4.125 | 4 | def merge_sort(arr):
n = len(arr)
return _merge_sort(arr, 0, n-1)
def _merge_sort(arr, start, end):
if start < end:
mid = (start+end)//2
_merge_sort(arr, start, mid)
_merge_sort(arr, mid+1, end)
_merge(arr, start, mid, end)
return arr
def _merge(arr, start, mid, end):
left = start
right = mid+1
# if already sorted
if arr[mid] <= arr[right]:
return
while left <= mid and right <= end:
if arr[left] < arr[right]:
left += 1
else:
index = right
value = arr[right]
while index != left:
arr[index] = arr[index-1]
index -= 1
arr[left] = value
left += 1
mid += 1
right += 1
if __name__ == '__main__':
print(merge_sort([9, 7, 8, 3, 2, 10, 1, 7]))
| false |
7024125f920382245e33eae4f71d857d6b3f24b7 | shensleymit/HapticGlove | /Haptic Feedback Code/RunMe2.py | 1,725 | 4.375 | 4 | #################################################
# This asks the user which function they would #
# like to see, and loads that one. Ideally, #
# this won't be needed, and instead the choice #
# of function and the function will all be part #
# of one file. #
#################################################
if __name__ == '__main__':
print "What function do you want? Here are your choices."
print "2^x"
print "sin(x)"
print "y = x"
print "y = x^2"
print "xz plane"
print "yz plane"
retry = True
while retry == True: #continually prompts user until they pick a recognized function
choice = raw_input("Please pick one of these! Hit enter after typing your choice here: ").lower()
if choice == "2^x":
retry = False
print "Loading..."
execfile("exp.py") #executes the file that corresponds to the picked function
elif choice == "sin(x)" or choice == "sinx": #can interpret it with or without parentheses
retry = False
print "Loading..."
execfile("sinx.py")
elif choice == "y = x" or choice == "y=x":
retry = False
print "Loading..."
execfile("x.py")
elif choice == "y = x^2" or choice == "y=x^2":
retry = False
print "Loading..."
execfile("x2.py")
elif choice == "yz plane":
retry = False
print "Loading..."
execfile("xplane.py")
elif choice == "xz plane":
retry = False
print "Loading..."
execfile("yplane.py")
else:
print "I'm sorry, I didn't get that."
| true |
9d272a9c8c1733568d01335040bc94a3bec2eb1c | aaronbushell1984/Python | /Day 1/Inputs.py | 1,596 | 4.3125 | 4 | # Python has Input, Output and Error Streams
# Python executes code sequentially - Line by Line
# Python style guide https://www.python.org/dev/peps/pep-0008/
# Add items to input stream with input - Print variable to output stream
name = input('enter your name: ')
print("Your name is", name)
# Input takes input and outputs as a string by default. To add to age then use int(x) to cast to number
age = int(input("enter your age:"))
print("Your age is", age)
# += adds and assigns to variable in shorthand, -= subtracts and assigns, *= multiplies and assigns
age += 10
print("Your age in a decade will be", age)
# Built-in functions with parameters example
print(max(5,2,9,4))
print(min(5,2,9,4))
# Functions can be assigned to a variable
maximum = print(max(5,2,9,4))
print(maximum)
# Indent blocks - MUST BE INDENTED
if maximum > 8:
print("maximum is greater than 8")
"""
TO ACCESS PYTHON KEYWORDS -
Enter Python compiler in terminal (type python)
IMPORT A LIBRARY FOR KEYWORD
Enter - import keyword
Enter - print(keyword.kwlist)
'False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield'
"""
# NB. DO NOT USE VARIABLES OR FILE NAMES WITH KEYWORDS
# NB. PYTHON WILL PRODUCE AN INDENT ERROR IF A SPACE PRECEDES FUNCTION
# NB. VARIABLES MUST NOT START WITH A NUMBER, ARE CASE SENSITIVE
# NB. CONVENTION is to_use_variable_with_lowercase_underscores | true |
e24d82a2699dd90ef9551b67975fad2f77bd84a1 | bolducp/MIT-6.00SC-OpenCourseWare-Solutions | /Set 1/problem_2.py | 1,235 | 4.15625 | 4 | # Problem Set 1, Problem 2: Paying Off Debt in a Year
def get_outstanding_balance():
outstanding_balance = round(float(raw_input("Enter the outstanding balance on the credit card: ")), 2)
return outstanding_balance
def get_annual_interest_rate():
annual_interest_rate = round(float(raw_input("Enter the annual interest rate as a decimal: ")), 2)
return annual_interest_rate
def main():
starting_balance = get_outstanding_balance()
annual_interest_rate = get_annual_interest_rate()
monthly_interest_rate = annual_interest_rate/12.0
min_monthly_payment = 10.0
outstanding_balance = starting_balance
while outstanding_balance > 0:
months = 0
min_monthly_payment += 10.0
outstanding_balance = starting_balance
for month in range(1, 13):
if outstanding_balance > 0:
outstanding_balance = outstanding_balance * (1 + monthly_interest_rate) - min_monthly_payment
months += 1
print "\n" + "RESULT"
print "Monthly payment to pay off debt in 1 year:", min_monthly_payment
print "Number of months needed:", months
print "Balance:", round(outstanding_balance, 2)
if __name__ == "__main__":
main()
| true |
1564137dce26a1cb9dfdeab8552a7246d5ee491a | keerthiballa/PyPart5 | /palindrome.py | 447 | 4.34375 | 4 | def is_palindrome(value: str) -> bool:
"""
This function determines if a word or phrase is a palindrome
:param value: A string
:return: A boolean
"""
return value.replace(" ", "").lower() == value[::-1].replace(" ","").lower()
# ballakeerthi@zipcodes-MacBook-Pro-3 PyPart5 % python3 -m unittest test_palindrome.py
# .
# ----------------------------------------------------------------------
# Ran 1 test in 0.000s
#
# OK | false |
93fb4f4dab9e74fa1da1499eaa5f874cb2710e15 | danielblignaut/movie-trailer-application | /media.py | 1,185 | 4.15625 | 4 | class Movie() :
""" This class provides a way to store movie related data """
VALID_RESTRICTIONS = ["G", "PG", "PG-13", "R"]
def __init__(self, title, storyline, image_poster, youtube_trailer, rating, restriction) :
self.title = title
self.storyline = storyline
self.image_poster = image_poster
self.youtube_trailer = youtube_trailer
if(Movie.check_rating(rating)) :
self.rating = rating
else :
self.rating = "N/A"
if(Movie.check_restriction(restriction)) :
self.restriction = restriction.upper()
else :
self.restriction = "N/A"
'''this static method provides a way to check if the movies's age restriction is valid '''
@staticmethod
def check_restriction(restriction) :
for static_restriction in Movie.VALID_RESTRICTIONS :
if(static_restriction == restriction.upper()) :
return True
return False
'''this static method provides a way to check if the movies's rating is valid '''
@staticmethod
def check_rating(rating) :
if(rating >= 0 and rating <= 5) :
return True
return False
| true |
2134dde3da45d97bed30599df119beb184f15eaa | kwahome/python-escapade | /fun-with-problems/in_place_string_reverse.py | 1,685 | 4.3125 | 4 | # -*- coding: utf-8 -*-
#============================================================================================================================================
#
# Author: Kelvin Wahome
# Title: Reversing a string in-place
# Project: python-escapade
# Package: fun-with-problems
#
#
# Write a function to reverse a string in-place
#
# Since strings in Python are immutable, first convert the string into a list of characters, do the in-place reversal on that list, and
# re-join that list into a string before returning it. This isn't technically "in-place" and the list of characters will cost O(n)O(n)O(n)
# additional space, but it's a reasonable way to stay within the spirit of the challenge. If you're comfortable coding in a language with
# mutable strings, that'd be even better!
#
#============================================================================================================================================
import sys
def reverse_string(string):
string = list(string)
# walk towards the middle, from both sides
for left in range(len(string) / 2):
right = -left - 1
# swap the front char and back char
string[left], string[right] = \
string[right], string[left]
return ''.join(string)
def main():
proceed = False
print "Reversing a string with an in-place function"
print "------------------------------------------"
string = raw_input("Enter the string to reverse: ")
print "\n"
print "Original string: "
print string
print "\n"
print "Reversed string:"
print "\n"
print reverse_string(string)
print "\n"
if __name__ == "__main__":
try:
sys.exit(main())
except Exception:
print "An error has occured"
| true |
9485759ef1b43b19642b35039ec0e5a0e5408f36 | raylyrainetwstd/MyRepo | /M07_Code_Fixed.py | 2,458 | 4.1875 | 4 | #this function takes an input from a user in response to a question
#if the user input is not a number, is_num doesn't accept the user input
def is_num(question):
while True:
try:
x = int(input(question))
break
except ValueError:
print("That is not a number")
continue
return x
#this function asks the user about information about their pet
#The user will answer in strings, except for when asked for pet's age
class cat():
def __init__(self):
self.name = input("\nWhat is your pet's name?\n")
self.type = input(f"What type of pet is {self.name}?\n").lower()
self.color = input(f"What color is {self.name}?\n").lower()
self.age = is_num(f"How old is {self.name}?\n")
#This function asks the user their name and about one of their pets
#after getting info on the pet, the program asks the user if they want to add info about another pet
#the program will continue to add pets to the pet list until the user says they don't wanna add more
#The program then writes a new txt file listing the user and all the pets the user talked about
def main():
pet = []
response = "y"
name = input("Hello! What is your name?\n")
while response != "n":
pet.append(cat())
while True:
response = input("\nDo you have another pet? Y|n: ").lower()
if response == "y" or response == "":
break
elif response == "n":
break
else:
print("\nYou did not make a correct response, please use a 'Y' for yes and a 'n' for no.")
continue
num_pets = len(pet)
with open('My_Pet_List.txt','w') as file:
if num_pets == 1:
file.write(f"{name} has one pet, it's name is {pet[0].name}.\n\n")
else:
file.write(f"{name} has {num_pets} pets. Those pet's names are:")
count = 0
for i in pet:
count += 1
if count == 1:
file.write(f" {i.name}")
elif count != 1:
file.write(f", {i.name}")
file.write(".\n\n")
for i in pet:
file.write(f"{i.name} is a {i.color} {i.type} and is {i.age} years old.\n")
#this is in here for security
#this is making sure that the program isn't opening up any other projects
if __name__ != "__main__":
main()
else:
exit
| true |
91cd8ab16e42d87249023a65929e46bc756e857a | raylyrainetwstd/MyRepo | /SDEV120_M02_Simple_Math.py | 452 | 4.1875 | 4 | #get two numbers from user
#add, subtract, multiply, and divide the two numbers together and save the values to variables
#print the results on one line
num1 = int(input("Please type a number: "))
num2 = int(input("Please type another number: "))
addition = str((num1 + num2))
subtraction = str((num1 - num2))
multiplication = str((num1 * num2))
division = str((num1 / num2))
print(addition + " " + subtraction + " " + multiplication + " " + division) | true |
3042a58e9d3deadaad9caa2291f2a672798b482d | cuichacha/MIT-6.00.1x | /Week 2: Simple Programs/4. Functions/Recursion on non-numerics-1.py | 621 | 4.25 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 15 20:54:15 2019
@author: Will
"""
def isIn(char, aStr):
'''
char: a single character
aStr: an alphabetized string
returns: True if char is in aStr; False otherwise
'''
if aStr=="":
return False
if char==aStr[int(len(aStr)/2)]:
return True
elif char>aStr[int(len(aStr)/2)] and int(len(aStr)/2)!=0:
return isIn(char, aStr[int(len(aStr)/2):])
elif char<aStr[int(len(aStr)/2)] and int(len(aStr)/2)!=0:
return isIn(char, aStr[0:int(len(aStr)/2)])
else:
return False
| true |
f1f4ca1185dda31236ba9bd5ceded47043312d59 | enireves/converter | /andbis.py | 462 | 4.25 | 4 | weather = input("What's the weather like? ")
temperature = input("What temperature is it? ")
if weather == "rainy" and temperature == "cold" :
print("Take an umbrella and a warm jacket.")
elif temperature == "warm":
print("Take an umbrella and a shirt.")
elif weather == "sunny" and temperature == "cold":
print("Take sunglasses and a warm jacket.")
elif temperature == "warm":
print("Take sunglasses and a shirt.")
else :
print("Stay home!") | true |
083a2d404922c25ca29310ead58938ebcf613db7 | quangvinh86/python-projecteuler | /PE-010/summation_of_primes.py | 949 | 4.125 | 4 | """
Solution to Project Euler problem 10
@author: vinh.nguyenquang
@email: quangvinh19862003@gmail.com
"""
import math
UPPER_LIMIT = 2000000
def is_prime(number):
if number <= 1:
return False
elif number <= 3:
return True
elif not number % 2:
return False
max_range = int(math.sqrt(number)) + 1
for counter in range(3, max_range, 2):
if not number % counter:
return False
return True
def calc_summation_of_primes():
sum_of_prime = 2
number = 3
while number <= UPPER_LIMIT:
if is_prime(number):
sum_of_prime += number
number += 2
return sum_of_prime
if __name__ == "__main__":
import time
start = time.time()
##
result = calc_summation_of_primes()
##
done = time.time()
elapsed = done - start
print("Prime sum of all primes below {} is {}".format(UPPER_LIMIT, result))
print("elapsed time: {}s".format(elapsed))
| true |
cc7bf998dc1b446c9bbe4b5f1455c5e62b7c8276 | FrankCardillo/practice | /2016/codewars/python_practice/digital_root.py | 577 | 4.21875 | 4 | # A digital root is the recursive sum of all the digits in a number.
# Given n, take the sum of the digits of n.
# If that value has two digits, continue reducing in this way until a single-digit number is produced.
# This is only applicable to the natural numbers.
def digital_root(n):
total = 0
stringified = str(n)
for char in stringified:
total += int(char)
if total <= 9:
return total
else:
stringified_total = str(total)
total = 0
for char in stringified_total:
total += int(char)
return total
| true |
b7fab26d44f16a123f15142f6aac5cd697abcf58 | fearlessfreap24/codingbatsolutions | /Logic-2/make_chocolate.py | 572 | 4.125 | 4 | def make_chocolate(small, big, goal):
# not enough bricks
if big * 5 + small < goal:
return -1
# not enough small bricks
goalmod = goal % 5
if goalmod > small:
return -1
# enough small bricks
if big < goal // 5:
return goal - (big * 5)
if big >= goal // 5:
return goal % 5
if __name__ == "__main__":
print(make_chocolate(4, 1, 9)) # 4
print(make_chocolate(4, 1, 10)) # -1
print(make_chocolate(4, 1, 7)) # 2
print(make_chocolate(6, 2, 7)) # 2
print(make_chocolate(7, 1, 12)) # 7
| true |
58724808401d4280a852997f06a00f4480d75aeb | Maidou0922/Maidou | /阶乘.py | 421 | 4.15625 | 4 | b=int(input("pls input number:"))
def fact(a):
result=1
if a < 0:
return("Error") # should be Error
elif a == 0 or a==1:
return(str(a))
while a > 1:
tmp=a*(a-1)
result=result*tmp
a -=2
return result #return after loop
print(fact(b))
print("")
#
#fact of 5 should be 120, not 20, 5*4*3*2*1 = 120 , pls check your logic of func | true |
73f05af982732d91004c84a6686e2116e2e1b705 | rinkeshsante/ExperimentsBackup | /Python learning-mosh/Python Files/learn_02.py | 1,123 | 4.15625 | 4 | # from the python mega course
# to run the entire code remove first ''' pair from code
# create text file named test.txt containg multiple lines
# file handling opening t& reading the file
'''
file = open("test.txt", "r")
content = file.readlines()
# file.read() for all content reading
# file.seek(0) to readjustng the reading pointer
print(content)
content = [i.rstrip('\n') for i in content]
# to remove \n from numbers
print(content)
file.close()
'''
# creating new file or rewrite existing one
'''
file = open('test1.txt', 'w')
file.write("line 1\n")
file.write("line 2\n")
file.close()
'''
# appending existing files
'''
file = open('test1.txt', 'a')
file.write("line 3\n")
file.write("line 4\n")
file.close()
'''
# notes
# r+ => both reading and writing , add at beginning of text
# w+ => writing and reading , create if it don't exist i.e. it overwrites
# a+ => add at the end
# with method no need to close
'''
with open('test1.txt', 'a+') as file:
file.seek(0) # to bring pointer at start
content = file.read()
file.write("line 5\n")
file.write("line 6\n")
print(content)
'''
| true |
e4c11407f315d7ee14c92362ce290ac3665076cc | shanshanya123/test | /string.py | 588 | 4.15625 | 4 | str1="hello world "
str2="python hello world "
print("str1[0]:",str1[0])
print("str2[0:5]:",str2[0:5])
l=str1.__len__()
print("更新字符串:",str1+str2)
str3=str1+str2
print(str3)
print(str3.find(str2))
print(str3.count('h'))
print(str1.capitalize())
print(str1.center(50,'+'))
str = "字符串函数";
str_utf8 = str.encode("UTF-8")
str_gbk = str.encode("GBK")
print(str)
print("UTF-8 编码:", str_utf8)
print("GBK 编码:", str_gbk)
print("UTF-8 解码:", str_utf8.decode('UTF-8', 'strict'))
print("GBK 解码:", str_gbk.decode('GBK', 'strict'))
| false |
f09c699d0bf7d7486a1f0f881eee9f61686d6403 | axentom/tea458-coe332 | /homework02/generate_animals.py | 1,713 | 4.34375 | 4 | #!/usr/bin/env python3
import json
import random
import petname
import sys
"""
This Function picks a random head for Dr. Moreau's beast
"""
def make_head():
animals = ["snake", "bull", "lion", "raven", "bunny"]
head = animals[random.randint(0,4)]
return head
"""
This Function pulls two random animals from the petname library and mashes their bodies together for Dr. Moreau's beast
"""
def make_body():
body1 = petname.name()
body2 = petname.name()
body = body1 + "-" + body2
return body
"""
This Function creates an even number between 2-10 inclusive to be the number of arms in Dr. Moreau's beast
"""
def make_arms():
arms = random.randint(1,5) * 2
return arms
"""
This function creates a multiple of three between 3-12 inclusive to be the nuber of legs in Dr. Moreau's beast
"""
def make_legs():
legs = random.randint(1,4) * 3
return legs
"""
This function creates a non-random number of tails equal to the sum of arms and legs
This function REQUIRES the presence of a legs and arms int variable
"""
def make_tails(arms_str, legs_str):
tails = int(arms_str) + int(legs_str)
return tails
def create_animal():
head = make_head()
body = make_body()
arms = make_arms()
legs = make_legs()
tails = make_tails(arms, legs)
animal = {'head': head, 'body': body, 'arms': arms, 'legs': legs, 'tails': tails}
return animal
def main():
animals_list = {}
animals_list['animal'] = []
for i in range(0,20):
animal = create_animal()
animals_list['animal'].append(animal)
with open(sys.argv[1], 'w') as out:
json.dump(animals_list, out, indent=2)
if __name__ == '__main__':
main()
| true |
84db20f7bfcaa6dd31784c4b6b23739fdc1a249d | Arjun-Pinpoint/InfyTQ | /Programming Fundamentals using Python/Day 3/Assignment 22.py | 557 | 4.125 | 4 | '''
Write a Python program to generate the next 15 leap years starting from a given year. Populate the leap years into a list and display the list.
Also write the pytest test cases to test the program.
'''
#PF-Assgn-22
def find_leap_years(given_year):
list_of_leap_years=[]
count=0
while(count<15):
if(given_year%400==0 or given_year%4==0):
list_of_leap_years.append(given_year)
count+=1
given_year+=1
return list_of_leap_years
list_of_leap_years=find_leap_years(2000)
print(list_of_leap_years)
| true |
030f3b5229cd74842dd83ad861f3463d5e1681e6 | Arjun-Pinpoint/InfyTQ | /Programming Fundamentals using Python/Day 7/Assignment 47.py | 1,317 | 4.3125 | 4 | '''
Write a python function, encrypt_sentence() which accepts a message and encrypts it based on rules given below and returns the encrypted message.
Words at odd position -> Reverse It
Words at even position -> Rearrange the characters so that all consonants appear before the vowels and their order should not change
Note:
1. Assume that the sentence would begin with a word and there will be only a single space between the words.
2. Perform case sensitive string operations wherever necessary.
Also write the pytest test cases to test the program.
Sample Input Expected Output
the sun rises in the east eht snu sesir ni eht stea
'''
#PF-Assgn-47
def encrypt_sentence(sentence):
sentence=sentence.split()
res=""
for i in range(len(sentence)):
if i%2==0:
word=sentence[i]
reverse=word[::-1]
res+=reverse+" "
else:
vowels="aeiouAEIOU"
word=sentence[i]
vowel=""
non_vowel=""
for w in word:
if w in vowels:
vowel+=w
else:
non_vowel+=w
res+=non_vowel+vowel+" "
return res
sentence="The sun rises in the east"
encrypted_sentence=encrypt_sentence(sentence)
print(encrypted_sentence)
| true |
8853b70819c16150e377d6c4a3654c1f36810c61 | Jit26k/HacktoberFestContribute | /Algorithms/Array/ReverseArray.py | 464 | 4.28125 | 4 | import Arrays
def reversingAnArray(start, end, myArray):
while(start < end):
myArray[start], myArray[end - 1] = myArray[end - 1], myArray[start]
start += 1
end -= 1
if __name__ == '__main__':
myArray = Arrays.Array(10)
myArray.insert(2, 2)
myArray.insert(1, 3)
myArray.insert(3, 1)
print('Array before Reversing:',myArray)
reversingAnArray(0, len(myArray), myArray)
print('Array after Reversing:',myArray) | false |
92f91f8292a0b48d2cb75c94955a0187327cb563 | jandirafviana/python-exercises | /my-python-files/aula06_desafio004.py | 2,986 | 4.1875 | 4 | n1 = int(input ('Digite um número: '))
n2 = int(input('Digite outro número: '))
s = n1 + n2
print('A soma entre {} e {} é {}'.format(n1, n2, s))
a = input('Digite algo: ')
print('O tipo primitivo desse valor é ', type(a))
n = input('Digite algo: ')
# Esse 'n' que estamos analisando é um objeto. Em n.isnumeric por exemplo.
# Todo objeto tem características e realiza funcionalidade. Tem atributos e métodos.
# Todo objeto string tem métodos (isnumeric, isalnum)
# No caso desse código, como tem parênteses depois de cada objeto, a gente está trabalhando métodos.
print('{} É um número?'.format(n), n.isnumeric())
print('{} É alfanumérico?'.format(n), n.isalnum())
print('{} É uma letra do alfabeto?'.format(n), n.isalpha())
print('{} É um valor ASCII?'.format(n), n.isascii())
# Um valor ASCII é um valor entre 0 e 127.
print('{} É um número decimal?'.format(n), n.isdecimal())
print('{} É um digito?'.format(n), n.isdigit())
# Verifica se a string consiste apenas de digitos.
print('{} É um identificador?'.format(n), n.isidentifier())
# O isidentifier() retornará True se todos os caracteres são
# válidos para escrever um identificador no código, então eles
# são letras maiúsculas e minúsculas, dígitos, desde que não
# seja o primeiro caractere e mais alguns caracteres Unicode.
print('{} Está minúsculo?'.format(n), n.islower())
# Python string method islower() checks whether all the
# case-based characters (letters) of the string are lowercase.
print('{} Está maiúsculo?'.format(n), n.isupper())
print('{} É printável?'.format(n), n.isprintable())
# O isprintable() retornará True quando todos os caracteres são
# visíveis quando manda imprimi-los, isto incluindo os óbvios,
# mas também alguns menos óbvios como os que geram espaço em branco
# que não deixam de serem imprimíveis. Um exemplo de caractere não
# imprimível é o nulo (\0). Ele tem que ocupar espaço em tela ou papel.
# O mais comum de usá-lo é saber que se ele contará para determinar
# o espaço ocupado em um impressão qualquer em qualquer suporte
# ou se poderá causar algum erro por que criar uma situação
# inesperada, por exemplo um \8 que é um backspace, então ele pode
# retroceder uma caractere, então em vez de ocupar mais um caractere
# ele ocupa menos, apagando o anterior.
print('{} É um espaço?'.format(n), n.isspace())
# Python string method isspace() checks whether the string consists
# of whitespace.
print('{} Está capitalizada?'.format(n), n.istitle())
#Ou seja, primeira letra maiúscula.
print('{} É uma letra do alfabeto?'.format(n), n.__init_subclass__())
s = 'I Love Python.'
if s.isalnum() == True:
print('É alfanumérico')
else:
print('Não é alfanumérico')
s = 'Python'
if s.istitle() == True:
print('Titlecased String')
else:
print('Not a Titlecased String')
s = 'Eu adoro Python.'
if s.isupper() == True:
print('A frase está em maiúsculo')
else:
print('Não está em maiúsculo')
| false |
e4d361c009cd1a4cd312d9ebd6cf5cdd5019c954 | JRobinson28/CS50-PSets | /pset7/houses/import.py | 933 | 4.125 | 4 | from cs50 import SQL
from sys import argv, exit
from csv import reader, DictReader
db = SQL("sqlite:///students.db")
def main():
# Check command line args
if len(argv) != 2:
print("Exactly one commmand line argument must be entered")
exit(1)
# Open CSV file given by command line arg
with open(argv[1], "r") as csvfile:
reader = DictReader(csvfile)
# Loop through students
for row in reader:
nameSplit = ((row["name"]).split())
# Insert None where there is no middle name
if (len(nameSplit) == 2):
nameSplit.insert(1, None)
# Insert each student into students table of students.db using db.execute
db.execute("INSERT INTO students (first, middle, last, house, birth) VALUES(?, ?, ?, ?, ?)",
nameSplit[0], nameSplit[1], nameSplit[2], row["house"], row["birth"])
main() | true |
7157f20e3565c8ec175b673725fd2073ad8ae33e | fennieliang/week3 | /lesson_0212_regex.py | 1,082 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 25 14:40:57 2021
@author: fennieliang
"""
#useful links for regular expression
#http://python-learnnotebook.blogspot.com/2018/10/python-regular-expression.html
#https://www.tutorialspoint.com/python/python_reg_expressions.htm
#regular expression
import re
string = 'I bet you’ve heard of Harry James Poter for 11,000,000.00 times.'
#string = "We are leaving in Taipei City in Taiwan"
'''
#match capital words
#matches = re.finditer('([A-Z][a-z]+\s)', string)
#matches = re.finditer('([A-Z][a-z]+\s+[A-Z][a-z]+\s)', string)
matches = re.finditer('([A-Z][a-z]+\s){1,}', string)
for word in matches:
print (word[0])
try names with first and last names or even middle names
then a find_name function to the class
'''
#match money style digits
#matches = re.finditer('(\d+\s)', string)
#matches = re.finditer('(\d+\.\d\d\s)', string)
matches = re.finditer('(\d+,){0,}(\d+.)(\d+)', string)
for digit in matches:
print (digit[0])
'''
try big money with decimals
add a find_digit function to the class
''' | true |
d32aa6fa40b6dd5c0201e74f53d5bd581d6a3fe9 | josephcardillo/lpthw | /ex19.py | 1,825 | 4.375 | 4 | # creating a function called cheese_and_crackers that takes two arguments.
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print(f"You have {cheese_count} cheeses.")
print(f"You have {boxes_of_crackers} boxes of crackers.")
print("Get a blanket.\n")
print("We can just give the function numbers directly:")
# calls this function, and passes two integers into it:
cheese_and_crackers(20, 30)
print("OR, we can use variables from our script:")
# sets two variables to integers
amount_of_cheese = int(input("How many cheeses? "))
amount_of_crackers = int(input("How many crackers? "))
# calls function and passes in the variables we just set
cheese_and_crackers(amount_of_cheese, amount_of_crackers)
print("We can even do math inside too:")
# calls function and passes two arguments in the form of addition
cheese_and_crackers(10 + 20, 5 + 6)
print("And we can combine the two, variables and math:")
# calls function and passes in two arguments that are a combination of variables and integers added together
cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)
# creating my own function
def my_function(book, music, food):
print(f'my favorite book is {book}.')
print(f'I like listening to {music}')
print(f'I love to eat {food}')
# call the function and pass three arguments to it
my_function("crime and punishment", "philip glass", "pizza")
# set three variables to something using the input function
favorite_book = input("What's your favorite book? ")
favorite_music = input("What's your favorite music? ")
favorite_food = input("What's your favorite food? ")
# call the function again, passing in these new variables
my_function(favorite_book, favorite_music, favorite_food)
from sys import argv
script, book, music, food = argv
my_function(book, music, food)
| true |
7f97672e9989079ecf723aad9f71c57952440e35 | josephcardillo/lpthw | /ex15.py | 795 | 4.375 | 4 | # imports argv module from sys
from sys import argv
# the two argv arguments
script, filename = argv
# Using only input instead of argv
# filename = input("Enter the filename: ")
# Opens the filename you gave when executing the script
txt = open(filename)
# prints a line
print(f"Here's your file {filename}:")
# The read() function opens the filename that's set to the txt variable
print(txt.read())
print("Type the filename again:")
txt.close()
# prompt to input the filename again
file_again = input("> ")
# sets variable txt_again equal to the open function with one parameter: the variable file_again
txt_again = open(file_again)
# prints the content of the example15_sample.txt file by calling the read function on the txt_again variable.
print(txt_again.read())
txt_again.close() | true |
09f1000e2058e584e8261d7dc437af52c3709674 | IslamOrtobaev/This_is_my_own_private_repository_and_I_will_not_be_harassed | /Алгоритмы и структуры данных на Python. Базовый курс/Урок 1. Практическое задание/task_6.py | 760 | 4.34375 | 4 | """
Задание 6. Пользователь вводит номер буквы в алфавите.
Определить, какая это буква.
Пример:
Введите номер буквы: 4
Введёному номеру соответствует буква: d
Подсказка: используйте ф-ции chr() и ord()
"""
user_input_symbol = int(input('Введите номер буквы: '))
if 0 < user_input_symbol < 27:
user_input_symbol = user_input_symbol + 96
print(f'Введёному номеру соответствует буква: {chr(user_input_symbol)}')
else:
print('Перезапустите программу и введите номер буквы от 1 до 26.')
| false |
6c7beee44a89b6b3f5c99e9164ebfe51db81e734 | IslamOrtobaev/This_is_my_own_private_repository_and_I_will_not_be_harassed | /Алгоритмы и структуры данных на Python. Базовый курс/Урок 2. Практическое задание/task_2_1.py | 1,043 | 4.15625 | 4 | """
2. Посчитать четные и нечетные цифры введенного натурального числа.
Например, если введено число 34560, то у него 3 четные цифры
(4, 6 и 0) и 2 нечетные (3 и 5).
Подсказка:
Для извлечения цифр числа используйте арифм. операции
Пример:
Введите натуральное число: 44
В числе 44 всего 2 цифр, из которых 2 чётных и 0 нечётных
ЗДЕСЬ ДОЛЖНА БЫТЬ РЕАЛИЗАЦИЯ ЧЕРЕЗ ЦИКЛ
"""
user_number = int(input('Введите число: '))
evens = odds = digits = 0
cycle_number = user_number
while cycle_number > 0:
if cycle_number % 2 == 0:
evens += 1
else:
odds += 1
cycle_number = cycle_number // 10
digits += 1
print(f'В числе {user_number} всего {digits} цифр, из которых {evens} чётных и {odds} нечётных.') | false |
6fb99f7f646c260eb763fc5804868a9bcf529971 | Shubham1744/HackerRank | /30_Days_of_code/Day_1_Data_Types/Solution.py | 777 | 4.25 | 4 |
int_2 = int(input())
double_2 = float(input())
string_2 = input()
# Read and save an integer, double, and String to your variables.
sum_int = i + int_2
sum_double = d + double_2
sum_string = s + string_2
# Print the sum of both integer variables on a new line.
# Print the sum of the double variables on a new line.
# Concatenate and print the String variables on a new line
print(sum_int)
print(sum_double)
print(sum_string)
# Declare second integer, double, and String variables.
# Read and save an integer, double, and String to your variables.
# Print the sum of both integer variables on a new line.
# Print the sum of the double variables on a new line.
# Concatenate and print the String variables on a new line
# The 's' variable above should be printed first.
| true |
cff97b2c99af7fe57a02233fb49e0e09db361242 | bagreve/Nivelacion | /26082019/000000.py | 771 | 4.15625 | 4 | # En la nivelacion numero 6,se ensana como usar y crear diccionarios
d = {} # Se crea un diccionario vacio
d["George"] = 24 # se crean nuevos valores ligados a llaves , siendo George la llave y su edad el valor
d["Tom"] = 32
d["Jenny"] = 20
d[10] = 100 # no solo se pueden crear listas con llaves de strings y valores numericos, se pueden
print d["George"] # crear todas las combinaciones
print d[10] # para imprimir un valor solo se llama al diccionario con la llave
for key, value in d.items(): # en este caso se quiere imprimir tanto las llaves como los valores en orden
print "key:", key # es por eso que se busca en internet y se encuentra el for aqui utilizado
print "value:", value # para imprimir lo deseado.
print ""
| false |
250bbfc0aac5bf851b2cdb6ca2ca7fc5a2d658af | josealbm/PracticasPython | /Práctica 3/P3E2.py | 684 | 4.25 | 4 | #Práctica 3 - Ejercicio 2 - José Alberto Martín
#Pida al usuario 5 números y diga si estos estaban en
#orden decreciente, creciente o desordenados.
print ("Escribe cinco números y te diré que orden has utilizado")
a=int(input("Escribe el primer número "))
b=int(input("Escribe el segundo número "))
c=int(input("Escribe el tercer número "))
d=int(input("Escribe el cuarto número "))
e=int(input("Escribe el quinto número "))
if a>b and b>c and c>d and d>e:
print ("Has escrito tus números en orden decreciente")
elif a<b and b<c and c<d and d<e:
print ("Has escrito tus números en orden creciente")
else:
print ("Has escrito los números desordenados")
| false |
670efb0e6c1807247434ea2b21f83dbccddb5e28 | josealbm/PracticasPython | /Práctica 7/P7E4.py | 428 | 4.25 | 4 | #Práctica 7 -Ej 4 - José Alberto Martín Marí
#Escribe un programa que pida una frase, y le pase como parámetro
#a una función dicha frase. La función debe sustituir todos
#los espacios en blanco de una frase por un asterisco,
#y devolver el resultado para que el programa principal la imprima
#por pantalla.
def asterisco(p):
b=" "
c="*"
print (p.replace(b,c))
frase=input("Escribe una frase ")
asterisco(frase)
| false |
6dad818288d32ed0797f59fc4af3700c49a6e6b8 | josealbm/PracticasPython | /Práctica 5/P5E12.py | 1,901 | 4.125 | 4 | #Práctica 5 - Ejercicio 12 - José Alberto Martín Marí
#Escriu un programa per a jugar a endevinar un nombre (l'usuari pensa un nombre i el programa
#l'ha d'endevinar). El programa comença demanant entre què nombres està el nombre
#a endevinar i després intenta endevinar de què nombre es tracta. L'usuari va
#dient si el nombre que ha dit el programa és menor, major o igual al que s'ha cercat.
#Valor mínim: 0
#Valor màxim: 100
#Pensa un nombre entre 0 i 100 a ver si ho puc endevinar.
#És 50?: major
#És 75?: menor
#És 62?: menor
#És 56?: major
#És 59?: igual
#Gràcies per jugar amb jo
#Pots perfeccionar el programa fent (ampliació per a qui vagi molt sobrat):
#• que al principi el programa s'asseguri de què el valor màxim és superior al valor mínim.
#• Que el programa detecti “trampes”, per exemple, si quan dius “25” li deim”major” i al dir “26”
#li deim “menor”, el programa ha de dir que estam fent trampes i ha de deixar de jugar amb
#nosaltres.
encontrado= False
minim=int(input("Dime un valor mínimo "))
maxim=int(input("Dime un valor máximo "))
print ("Piensa un número entre", minim,"y", maxim,"e intentaré adivinarlo \n \
Tienes que contestarme si es mayor, menor o igual que el que piensas")
if maxim<=minim:
maxim=int(input("%d no es mayor que %d, vuelve a intoducir el máximo "%(maxim,minim)))
import random
secret=random.randint(minim,maxim)
while not encontrado:
adivina=input("¿Es %d?"%secret)
if adivina=="mayor":
minim=adivina
secret=random.randint(minim,maxim)
elif adivina=="menor":
maxim==adivina
secret=random.randint(minim,maxim)
else:
if adivina=="igual":
encontrado= True
print ("Tu numero secreto era", secret,". Gracias por jugar conmigo")
| false |
ad07b60b0c4d663663a286ca854833a903e3ee6a | Philiplam4516/TRM | /Python Workshop/Advnaced Python/Codes/Functions/Functions/F05.py | 431 | 4.125 | 4 | '''
Write a program to get a circle radius from terminal,
and then compute the area of the circle by a function
'''
PI = 3.14
def compute_circle_area(radius):
return radius*radius*PI
def main():
print("Enter a circle radius (m)")
radius=input()
radius = float(radius) # type cast from string to float
area = compute_circle_area(radius=radius)
print("area of the circle is {:.5f} m2".format(area))
return
main() | true |
307cabfc949ee7f6af494726552b2228f09249d5 | jahanzebhaider/Python | /if\else/else.py | 1,841 | 4.15625 | 4 | #THIS CODE WILL PRINT THR HONDA CAR WITH UPPER CASE AND REST WITH LOWER CASE ALPHABETS
cars=['audi','bmw','honda','toyota','suzuki']
for car in cars:
if car =='Honda':
print(car.upper())
else:
print(car.lower())
# checking nother of checking in list
if 'ponks' in cars:
print("it's not their")
elif 'bmw' not in cars:
print('it is their')
names=['ali','ahmed','muetaza']
if names !='ali':
print('their is no ali present in list')
#checking if for numerical value
no=17
if no ==17:
print('no is present')
else:
print('no is not present')
marks=80
if marks>70 and marks<100:
print('A')
else:
print('Fail')
#price for diff student
age=input('Enter your age')
age=int(age)
if age<5:
print("YOU ARE NOT ELIGIBLE")
elif age<10:
price=10
print('your age is ' + str(age) +".Your admission fees is"+ str(price))
elif age<18:
price=0
print('your age is ' + str(age) +".Your admission fees is"+ str(price))
#using in statement in if condition
pizza=['mashroom','cheese']
if 'mashroom' in pizza:
print('pizza is ready')
elif 'pepproni' in pizza:
print('pizza will take time')
else:
print('pizza')
#alien game 0.1
alien_colour=['red','yellow','green']
if 'green' in alien_colour:
print('You Earned 5 points')
elif 'yellow' in alien_colour:
print('Your earned 10 points')
elif 'red' in alien_colour:
print('you earned 15 ponts')
#stages of life
age=89
if age<2:
print('you are a baby')
elif age >=2 and age<4:
print('toddller')
elif age >=4 and age<13:
print('kid')
elif age >=13 and age<20:
print('teenager')
elif age >=20 and age<65:
print('addult')
else:
print('Elder')
#favorite food
favorite_food=['banana','apple','mango'] | true |
5db7c26589e626757b3bd3c34f6470a4667b4508 | TheCoderIsBibhu/Spectrum_Internship | /Task1(PythonDev)/prgm2.py | 232 | 4.25 | 4 | #2 Given a number find the number of zeros in the factorial of the number.
num=int(input("Enter a Number: "))
i=0
while num!=0:
i+=int(num/5)
num=num/5
print("The Number of zeros in factorial of the number is ",i) | true |
dd2203fe3867099c933500e09d4b8e8e70933cb8 | fran-byte/python_exercises | /tests/excepciones/ValueError.py | 921 | 4.21875 | 4 |
# (_ _ _ _ __ |_ |_ _
# | | (_|| ) |_)\/|_(-
# /
# Realiza una función llamada agregar_una_vez() que reciba una lista y un elemento, uno a uno.
# La función debe añadir el elemento al final de la lista con la condición de no repetir ningún elemento.
lista=[]
def agregar_una_vez(lista, elementos):
try:
if elementos not in lista:
lista.append(elementos)
print("\nLista Fusionada: ",lista,"\n")
else:
raise ValueError
except ValueError:
print("\nValueError: Elemento duplicado: ", elementos,"\n")
print("\nPrimer Envío: [10, -2, 'Hola','Adios'],'Hola")
agregar_una_vez([10, -2, "Hola","Adios"],"Hola")
print("Segundo Envío: [10, -2, 'Hola','Adios'],'Adios")
agregar_una_vez([10, -2, "Hola","Adios"],"Adios")
print("Tercer Envío: [10, -2, 'Hola','Adios'],'Python")
agregar_una_vez([10, -2, "Hola","Adios"],"Python")
| false |
c33def97afff545464952faa066c663e1d472491 | RyanMolyneux/Learning_Python | /tutorialPointWork/lab5/test2.py | 1,186 | 4.5625 | 5 | #In this session we will be working with strings and how to access values from them.
print("\nTEST-1\n----------------------------\n");
"""Today we will test out how to create substrings, which will involve slicing
of an existing string."""
#Variables
variable_string = "Pycon"
variable_substring = variable_string[2:-1]
#Note minus 1 is a short hand index for the end of the string.
if(len(variable_string) == len(variable_substring)):
print("\n\n'variable substring' is not a substring of 'variable_string'");
else:
print("\n\nvariable substring is a stubstring of variable string.");
print("\nTEST-2\n------------------------------\n");
#Updating String
"""This is better well known as concatinating to a string two ways of doing this
are during print or as assignment , assignment is some what permanant as long as
you do not reinitialise the string but print is not permenant as soon as you exit
the print method that concatinated value is gone."""
variable_string_permanent = variable_string +" is On!!!.";
print("\n\nPrint using temporary concatination : ",variable_string+" is On!!!");
print("\n\nPrint using permenant re assignment : ",variable_string_permanent); | true |
20d19ed63a0dd22c377a915facdb707c2b069732 | RyanMolyneux/Learning_Python | /pythonCrashCourseWork/Chapter 8/8-8-UserAlbums.py | 844 | 4.1875 | 4 | #Chapter 8 ex 8 date : 21/06/17.
#Variables
albums = []
#Functions
def make_album(artistName,albumTitle,num_tracks = ""):
"Creates a dictionary made up of music artist albums."
album = {"artist" : artistName,"album title": albumTitle}
if num_tracks:
album["number of tracks"] = num_tracks
return album
#Body
print("\n--------------------------------------\n\tStore Your Favourites Today\n--------------------------------------\n\nExample ",make_album("Jimmo","Jambo","3"))
for album in range(0,3):
albums.append(make_album(input("\n\nPlease enter artist name : "),input("Please enter album title :")))
if(input("Do you wish to quit : ") == "q"):
print("\nThank you for using Favorites come back soon Goodbye")
break
while albums:
print("\nAlbums\n---------------------------\n",albums.pop()) | true |
01cb8a39730aca55603be93355359da08d0a453e | RyanMolyneux/Learning_Python | /pythonCrashCourseWork/Chapter 10/ex10/main.py | 526 | 4.25 | 4 | """This will be a basic program which just consists of code counting the number of times 'the' appears in a text file."""
#Chapter 10 ex 10 DATE:17/07/18.
#Import - EMPTY
#Variables
file_name = ""
text = ""
#Objects - EMPTY
#Functions - EMPTY
#Body
file_name = input("\n\nPlease enter name of the file & rember extensions.\nInput : ")
with open(file_name) as fileObject:
text = fileObject.read()
print("\n\nThe number times 'the' has been used in ",file_name," is ",str(text.lower().count("the"))) | true |
8d1bb14e3ea2315a1011b0abf715739c4e9b710a | darkleave/python-test | /Test/venv/Example/2/5.py | 267 | 4.28125 | 4 | #序列相加,只有相同类型的序列才能进行链接操作
addList = [1,2,3] + [4,5,6]
print(addList)
addString = 'Hello, ' + 'world!'
print(addString)
#字符串和列表类型不同,无法进行链接
addListString = [1,2,3] + 'world!'
print(addListString) | false |
182c3617675992814e9548d390db913b2f08fb7e | darkleave/python-test | /Test/venv/Example/2/4.py | 525 | 4.15625 | 4 | #步长示例
#步长通常都是隐式设置的,默认步长为1,分片操作就是按照这个步长逐个遍历序列的元素,然后返回开始和
#结束点之间的所有元素
numbers = [1,2,3,4,5,6,7,8,9,10]
num1 = numbers[0:10:2]
print(num1)
num2 = numbers[3:6:3]
print(num2)
num3 = numbers[::4]
print(num3)
num4 = numbers[8:3:-1]
print(num4)
num5 = numbers[10:0:-2]
print(num5)
num6 = numbers[0:10:-2]
print(num6)
num7 = numbers[::-2]
print(num7)
num8 = numbers[5::-2]
print(num8)
num9 = numbers[:5:-2]
print(num9) | false |
7694fe65590f429966a4315ed28b3dfaf1be8b6b | darkleave/python-test | /Test/venv/Example/4/5.py | 791 | 4.125 | 4 | #使用get()的简单数据库
people = {
'Alice':{
'phone':'2341',
'addr':'Foo drive 23'
},
'Beth':{
'phone':'9102',
'addr':'Bar street 42'
},
'Cecil':{
'phone':'3158',
'addr':'Baz avenue 90'
}
}
#针对电话号码和地址使用的描述性标签,会在打印输出的时候用到
labels = {
'phone':'phone number',
'addr':'address'
}
name = input('Name: ')
#查找电话号码还是地址?
request = input('Phone number (p) or address (a)?')
#使用正确的键
if request == 'p': key = 'phone'
if request == 'a': key = 'addr'
#使用get()提供默认值
person = people.get(name,{})
label = labels.get(key,key)
result = person.get(key,'not available')
print("%s's %s is %s." % (name,label,result))
| false |
4bc87ec0732a1bbae109667d396bc02610ecb6c7 | Gustacro/learning_python | /become_python_developer/3_Ex_Files_Learning_Python/Exercise Files/Ch3/calendars_start.py | 1,776 | 4.25 | 4 | #
# Example file for working with Calendars
#
# import the calendar module
import calendar
# create a plain text calendar
c = calendar.TextCalendar(calendar.SUNDAY)
# st = c.formatmonth(2019, 12, 0, 0) # "formatmonth" method allow format a particular month into a text string
# print(st)
# create an HTML formatted calendar
# hc = calendar.HTMLCalendar(calendar.SUNDAY)
# st = hc.formatmonth(2019,12)
# print(st)
# loop over the days of a month
# zeros mean that the day of the week is in an overlapping month
# for i in c.itermonthdays(2019, 12):
# print(i) # zeros at start and end, are the days that belongs to another month
# The Calendar module provides useful utilities for the given locale,
# such as the names of days and months in both full and abbreviated forms
# for name in calendar.month_name:
# print(name)
# for day in calendar.day_name:
# print(day)
# Calculate days based on a rule: For example, consider
# a team meeting on the first Friday of every month.
# To figure out what days that would be for each month,
# we can use this script:
print("Team meeting will be on: ")
for m in range(1,13): # loop over all the months
# Get and array of weeks that represent each one of the months
cal= calendar.monthcalendar(2019, m) # Specify year, m = month number
# create variables that represent week one and week two where the first FRIDAY will fall into
weekone = cal[0]
weektwo = cal[1]
# let's check if the first FRIDAY falls into the first week of the month or in the second week
if weekone[calendar.FRIDAY] != 0: # if the first FRIDAY = zero, it means that that Friday belongs to another month
meetday = weekone[calendar.FRIDAY]
else:
meetday = weektwo[calendar.FRIDAY]
print('%10s %2d' % (calendar.month_name[m], meetday)) | true |
a212f533bf41ef324030787837c59924207f7b9d | bansal-ashish/hackerR | /Python/Introduction/division.py | 1,753 | 4.34375 | 4 | #!/usr/bin/env python
"""
In Python, there are two kinds of division: integer division and float
division.
During the time of Python 2, when you divided one integer by another integer,
no matter what, the result would always be an integer.
For example:
>>> 4/3
1
In order to make this a float division, you would need to convert one of the
arguments into a float.
For example:
>>> 4/3.0
1.3333333333333333
Since Python doesn't declare data types in advance, you never know when you
want to use integers and when you want to use a float. Since floats lose
precision, it's not advised to use them in integral calculations.
To solve this problem, future Python modules included a new type of division
called integer division given by the operator //.
Now, / performs float division, and // performs integer division.
In Python 2, we will import a feature from the module __future__ called
division.
>>> from __future__ import division
>>> print 4/3
1.3333333333333333
>>> print 4//3
1
Note: The __ in __future__ is a double underscore.
Task
Read two integers and print two lines. The first line should contain integer
division, a//b. The second line should contain float division, a/b.
You don't need to perform any rounding or formatting operations.
Input Format
The first line contains the first integer, aa. The second line contains the
second integer, bb.
Output Format
Print the two lines as described above.
Sample Input
4
3
Sample Output
1
1.3333333333333333
"""
from __future__ import division, print_function
def main():
"""Division challenge."""
first_int = int(raw_input())
second_int = int(raw_input())
print(first_int // second_int)
print(first_int / second_int)
if __name__ == '__main__':
main()
| true |
35815caac7564a6be04e75a3af3b12139b97eced | jaredcooke/CP1404Practicals | /prac1/fromscratch.py | 442 | 4.15625 | 4 | number_of_items = int(input("Number of items: "))
total_cost = 0
while number_of_items <= 0:
print("Invalid number of items!")
number_of_items = int(input("Number of items: "))
for i in range(number_of_items, 0, -1):
price_of_item = float(input("Price of item: "))
total_cost += price_of_item
if total_cost > 100:
total_cost = round(total_cost * 0.9, 2)
print("Total price for", number_of_items, "items is $", total_cost)
| true |
a90ca0253478d5f3ed76ae32ed0b59607ba40d9c | jathinraju/module-3 | /python module 3/prgm9.py | 257 | 4.3125 | 4 | #prgm on to check is palindrome are not
n = int(input("enter a number:"))
rev = 0
while(n != 0):
remi = n%10
rev = rev*10+remi
n = n//10
print("reverse of the number:",rev)
if n==rev :
print(n,"is a palindrome ")
else :
print("it is not a palindrome")
| false |
8b348d1a210524f7884e2602f3fe820adb0398e0 | KoretsValentyn/py_zoo | /zoo.py | 1,035 | 4.15625 | 4 | """There are three kinds of animals in a zoo. """
class Zoo:
"""implementation zoo object"""
def __init__(self):
self.animals = []
def get_animals(self):
"""return all animals in zoo"""
return self.animals
def add(self, animal):
"""add new animal in zoo"""
self.animals.append(animal)
class Animal:
"""animal object"""
def __init__(self, name):
self.name = name
self.word = ""
def get_name(self):
"""return name animal"""
return self.name
def say(self):
"""return word """
return self.word
class Dog(Animal):
"""dog implementation"""
def __init__(self, name):
super().__init__(name)
self.word = "woof"
class Cat(Animal):
"""cat implementation"""
def __init__(self, name):
super().__init__(name)
self.word = "meow"
class Bird(Animal):
"""bird implementation"""
def __init__(self, name):
super().__init__(name)
self.word = "tweet"
| false |
a3af7a2a970e81045dfc09b7efcd54e8107f203c | melrjcr/GIT_DailyChall | /Caesar_Cipher.py | 521 | 4.25 | 4 | text = input('insert text to encrypt: ')
pattern = int(input('choose a shift pattern: '))
alphabet = abcdefghijklmnopqrstuvwxyz
def encrypt(text, pattern):
result = ""
for i in range(len(text)):
char = text[i]
if char.isupper():
result += chr((ord(char) + pattern - (ord('A'))) % len(alphabet) + (ord('A')))
else:
result += chr((ord(char) + pattern - (ord('a'))) % len(alphabet) + (ord('a')))
return result
print(f'Caesar Cipher: {encrypt(text, pattern)}')
| false |
8369dabbbe5680471488c495cf5a9b8599e11ea8 | orbache/pythonExercises | /exercise1.py | 541 | 4.40625 | 4 | #!/usr/bin/python
__author__ = "Evyatar Orbach"
__email__ = "evyataro@gmail.com"
'''Exercise 1
Create a program that asks the user to enter their name and their age. Print out a message addressed to them that tells them the year that they will turn 100 years old.
'''
from datetime import datetime
year = datetime.now().strftime("%Y")
name = raw_input("Please enter your name\n")
age = raw_input("Please enter your age\n")
print("Hi %s,\nIn 100 year from now you will be %s and the year is going to be %s" %(name, str(int(age) + 100), str(int(year) + 100)))
| true |
3bd707a6c0b5a2ffb1657ae2ac8465452aa30d6d | orbache/pythonExercises | /exercise14.py | 747 | 4.5625 | 5 | #!/usr/bin/python
__author__ = "Evyatar Orbach"
__email__ = "evyataro@gmail.com"
'''Exercise 14
Write a program (using functions!) that asks the user for a long string containing multiple words.
Print back to the user the same string, except with the words in backwards order.
For example, say I type the string:
My name is Michele
Then I would see the string:
Michele is name My
shown back to me.
'''
import string
str = raw_input("Please enter your string\n")
def delimiterHandler(v_str,v_delimiter):
return string.split(str,v_delimiter, )
def reverseString(v_list):
newList = []
i = len(v_list)-1
while i >= 0:
newList.append(v_list[i])
i -= 1
return ' '.join(newList)
print reverseString(delimiterHandler(str,' '))
| true |
c8cf7a7c6b5a999bcad80cc8a3ab48492a2aabf4 | brunoleej/study_git | /Basic/Algorithm/Basic/OOP/Public_private_protected_ex.py | 1,311 | 4.15625 | 4 | # 원 클래스 생성하기
# attribute : 원 반지름, 원 이름
# method
# 1. 원 이름 리턴 메소드
# 2. 원 넓이 리턴 메소드
# 참고(원 넓이 식) : 3.14 X 원 반지름 **2(원 반지름의 제곱)
# 3. 원 길이 리턴 메소드
# 참고(원 길이 식) : 2 X 3.14 X 원 반지름
# 생성자에서만 attribute 값 설정 가능
# attribute는 private으로 설정
'''
class Circle:
def __init__(self, radius : float, name : str):
self.__radius = radius
self.__name = name
def get_name(self):
return self.__name
def get_area(self):
return 3.14 * self.__radius**2
circle = Circle(3, 'dave')
print(circle.get_name(), circle.get_area()) # dave 28.26
print() #
'''
class Circle:
def __init__(self, radius : float, name : str):
self.__radius = radius
self.__name = name
def get_name(self):
return self.__name
def get_area(self):
return 3.14 * self.__radius**2
def get_length(self):
return 2 * 3.14 * self.__radius
circle = Circle(3, 'dave')
print(circle.get_name(), circle.get_area(), circle.get_length()) # dave 28.26 18.84
| false |
1d70db077c874f75b3911d94f58428037734fa66 | saurabhchris1/Algorithm-and-Data-Structure-Python | /Bubble_Sort/Bubble_Sort_Iterative_Optimized.py | 644 | 4.3125 | 4 | # Bubble Sort Iterative Optimized
# Print i,j will help you figure out calculations
def bubble_sort_iterative(num_arr):
len_arr = len(num_arr)
flag = True
for i in range(len_arr):
if not flag:
break
flag = False
for j in range(len_arr - i - 1):
print(i, j)
if num_arr[j] > num_arr[j + 1]:
flag = True
num_arr[j], num_arr[j + 1] = num_arr[j + 1], num_arr[j]
return num_arr
if __name__ == '__main__':
num = [2, 11, 6, 4, 7, 8]
sorted_arr = bubble_sort_iterative(num)
print ("The sorted array is : " + str(sorted_arr))
| false |
5270f1e5b8d4285e401d440476bc077ee89b0315 | Themis404/completed_tasks | /task_twelve/task_twelve.py | 1,092 | 4.5625 | 5 | '''
2. В одном файле в каждой строке записаны координаты пар точек.
Каждая координата отделена от другой пробелом.
Например, строка вида 3 6 -2 4 означает, что координаты первой точки (3;6), второй - (-2;4).
Во второй файл требуется построчно записать наибольшее и наименьшее расстояние между точками
'''
import math
def rangeCoords(coords: list):
coords = [int(num) for num in coords]
length = math.sqrt((coords[0]-coords[2])**2 + (coords[1]-coords[3])**2)
return length
def main():
maxLength = 0
file = open('coordinates.txt', 'rt')
for line in file:
coords = line.split()
length = rangeCoords(coords)
print('Координаты двух точек: ', coords)
if length > maxLength:
maxLength = length
print(maxLength)
file.close()
if __name__ == '__main__':
main()
| false |
b71c8353038c7cac83a834e5b047cc735648b371 | abelar96/PythonPrograms | /HW2.py | 425 | 4.21875 | 4 | ##Diego Abelar Morales
def distance(s, h):
return s * h
speed = int(input("What is the speed of the vehicle in mph?: "))
hours = int(input("How many hours has it traveled: "))
print("Hours Distanced Traveled")
print("------------------------------")
for time in range(1, 1 + hours):
distance(speed, time)
print(time, " ", distance(speed, time))
print("Average mph: ", (speed * hours)/hours)
| true |
0d58826718124173c580fddc80ab18717d8db13e | Vaishnav95/bridgelabz | /testing_programs/vending_notes.py | 758 | 4.40625 | 4 | '''
Find the Fewest Notes to be returned for Vending Machine
a. Desc -> There is 1, 2, 5, 10, 50, 100, 500 and 1000 Rs Notes which can be
returned by Vending Machine. Write a Program to calculate the minimum number
of Notes as well as the Notes to be returned by the Vending Machine as a
Change
b. I/P -> read the Change in Rs to be returned by the Vending Machine
c. Logic -> Use Recursion and check for largest value of the Note to return change
to get to minimum number of Notes.
d. O/P -> Two Outputs - one the number of minimum Note needed to give the
change and second list of Rs Notes that would given in the Change
'''
from utils import Util
amount = int(input("Enter the amount: "))
notes = Util()
resulting_notes = notes.vending_machine(amount)
| true |
de3f20a97b1f6ad9a4f09553914f7a0b4b55ee54 | Vaishnav95/bridgelabz | /algorithm_programs/sort_merge.py | 700 | 4.15625 | 4 | '''
Merge Sort - Write a program to do Merge Sort of list of Strings.
a. Logic -> To Merge Sort an array, we divide it into two halves, sort the two halves
independently, and then merge the results to sort the full array. To sort a[lo, hi),
we use the following recursive strategy:
b. Base case: If the subarray length is 0 or 1, it is already sorted.
c. Reduction step: Otherwise, compute mid = lo + (hi - lo) / 2, recursively sort the
two subarrays a[lo, mid) and a[mid, hi), and merge them to produce a sorted
result.
'''
from utils import Util
elements_number = int(input("Enter number of elements : "))
merge_object = Util()
result_array = merge_object.merge_sort(elements_number)
| true |
6c802e64c761ee9de46c355b25dad866c867ded1 | Vaishnav95/bridgelabz | /logical_programs/tic_tac_toe.py | 630 | 4.25 | 4 | '''
Cross Game or Tic-Tac-Toe Game
a. Desc -> Write a Program to play a Cross Game or Tic-Tac-Toe Game. Player 1
is the Computer and the Player 2 is the user. Player 1 take Random Cell that is
the Column and Row.
b. I/P -> Take User Input for the Cell i.e. Col and Row to Mark the ‘X’
c. Logic -> The User or the Computer can only take the unoccupied cell. The Game
is played till either wins or till draw...
d. O/P -> Print the Col and the Cell after every step.
e. Hint -> The Hints is provided in the Logic. Use Functions for the Logic...
'''
from utils import Util
cross_object = Util()
play = cross_object.cross_game()
| true |
b3a26c56d18f363bfb1cba242bff0d33a3363414 | cod3baze/initial-python-struture | /solo_learn/handle_files/readin.py | 293 | 4.1875 | 4 | #Para recuperar cada linha em um arquivo, você pode usar o método
# readlines para retornar uma lista na qual cada elemento é uma linha no arquivo.
file = open("textos.txt", "r")
#print(file.readline())
#file.close()
# ou usando um loop FOR
for line in file:
print(line)
file.close() | false |
f2784c8cc19167c649f41b9f077b127c8eb04cbe | svshriyansh/python-starter | /ex2fiborecur.py | 244 | 4.15625 | 4 | def fib(n):
if n == 1:
return 0
elif n == 2:
return 1
else:
return fib(n-1) + fib(n-2)
m = int(input("Enter the number to find its fibonacci: "))
for Num in range(1, m+1):
print(fib(Num),end=' ')
| true |
a2380c2f8ea772778259ae69c8851a5ebffffb8e | itodotimothy6/CTCI | /Arrays-&-Strings/1.4/solution.py | 1,566 | 4.25 | 4 | # Given a string, write a function to check if it is a permutation of a
# palindrome. A palindrom is a word or phraze that is the same forwards and
# backwards. A permutation is a rearrangement of letters. A palindrome does not
# need to be linited to just dictionary words.
# Note: a maximum of one character should have an odd count for a string
# permutation to be a palindrome
# O(n) time : O(1) space
def palindrome_permutation(s):
table = {}
for char in s:
curr = char.lower()
if ord('a') <= ord(curr) and ord(curr) <= ord('z'):
table[curr] = table.get(curr, 0) + 1
odd_count = 0
for char in table:
if table[char] % 2 != 0:
odd_count += 1
if odd_count > 1:
return False
else:
return True
# O(n) time O(1) space
def count_set_bits(n):
total = 0
while n:
total += n & 1
n = n >> 1
return total
def palindrome_permutation_using_bitmask(s):
mask = 0
for char in s:
if ord(char.lower()) < ord('a') or ord(char.lower()) > ord('z'):
continue
char_ascii = ord(char.lower()) - ord('a')
if mask & (1 << char_ascii):
mask = mask & ~(1 << char_ascii)
else:
mask = mask | (1 << char_ascii)
if count_set_bits(mask) > 1:
return False
return True
def main():
s = "Tact Coa"
assert palindrome_permutation(s) == True
assert palindrome_permutation_using_bitmask(s) == True
print("Passed all test cases!")
if __name__ == '__main__':
main()
| true |
f2ce02fe4a649be8b2646c34427984151f68b8be | 23devanshi/pandas-practice | /Automobile Dataset/Exercises.py | 2,191 | 4.34375 | 4 | # Exercises taken from : https://pynative.com/python-pandas-exercise/
import pandas as pd
import numpy as np
#pd.display
df = pd.read_csv('D:/Python tutorial/Pandas Exercises/1 Automobile Dataset/Automobile_data.csv')
df.shape
#: From given data set print first and last five rows
print(df.head())
print(df.tail())
#Question 2: Clean data and update the CSV file
#Replace all column values which contain ‘?’ and n.a with NaN.
df.replace(('?','n.a'), np.nan, inplace = True)
print(df)
#Question 3: Find the most expensive car company name
#Print most expensive car’s company name and price.
print(df.sort_values('price', ascending=False).loc[0, 'company'])
#Question 4: Print All Toyota Cars details
print(df[df.company == 'toyota'].describe())
#Question 5: Count total cars per company
df.company.value_counts()
#Question 6: Find each company’s Higesht price car
print(df[df.groupby('company').price.transform('max') == df.price])
#Question 7: Find the average mileage of each car making company
df.groupby('company')['average-mileage'].mean()
#Question 8: Sort all cars by Price column
print(df.sort_values('price', ascending=False))
#Question 9: Concatenate two data frames using the following conditions
GermanCars = {'Company': ['Ford', 'Mercedes', 'BMV', 'Audi'], 'Price': [23845, 171995, 135925 , 71400]}
japaneseCars = {'Company': ['Toyota', 'Honda', 'Nissan', 'Mitsubishi '], 'Price': [29995, 23600, 61500 , 58900]}
cars = pd.concat([pd.DataFrame(GermanCars), pd.DataFrame(japaneseCars)], axis = 0)
cars.Company = cars.Company.str.strip()
print(cars)
#Question 10: Merge two data frames using the following condition
#Create two data frames using the following two Dicts, Merge two data frames, and append the second data frame as a new column to the first data frame.
Car_Price = {'Company': ['Toyota', 'Honda', 'BMV', 'Audi'], 'Price': [23845, 17995, 135925 , 71400]}
car_Horsepower = {'Company': ['Toyota', 'Honda', 'BMV', 'Audi'], 'horsepower': [141, 80, 182 , 160]}
meta = pd.DataFrame(Car_Price).merge(pd.DataFrame(car_Horsepower), left_on = 'Company', right_on = 'Company', how = 'inner')
print(meta)
| true |
25b050106a89f63ea2133a42edc2fb2359379ee2 | victorparra96/Dictionaries-in-Python- | /exercise9.py | 2,093 | 4.25 | 4 | """
Escribir un programa que gestione las facturas pendientes de cobro de una empresa. Las facturas se almacenarán en
un diccionario donde la clave de cada factura será el número de factura y el valor el coste de la factura. El programa
debe preguntar al usuario si quiere añadir una nueva factura, pagar una existente o terminar. Si desea añadir una
nueva factura se preguntará por el número de factura y su coste y se añadirá al diccionario. Si se desea pagar una
factura se preguntará por el número de factura y se eliminará del diccionario. Después de cada operación el programa
debe mostrar por pantalla la cantidad cobrada hasta el momento y la cantidad pendiente de cobro.
"""
invoice = {}
total = [0]
def create_dict(num_invoice, invoice_value):
invoice.update({num_invoice: invoice_value})
return invoice
def payment_invoice(num_invoice):
if num_invoice in invoice:
suma = int(invoice[num_invoice]) + int(total[0])
total[0] = suma
invoice.pop(num_invoice)
else:
print("Invoice {} not exists, try again".format(num_invoice))
def show_data() -> str:
suma = sum(invoice.values())
return "Cantidad cobrada {}, pendiente por cobro {}".format(total[0], suma)
if __name__ == '__main__':
next = True
while next:
iterador = str(input("Que neceitas hacer, Agregar/pagar/Salir. A/P/S ").lower().strip())
if iterador == 'a':
num_invoice = str(input("Enter a new invoice ").lower().strip())
invoice_value = input("Enter a value for the invoice # {} ".format(num_invoice)).strip()
if invoice_value.isdigit():
create_dict(num_invoice, int(invoice_value))
print(show_data())
else:
print("Enter only numbers, try again")
elif iterador == 'p':
num_invoice = str(input("Enter number of invoice ").lower().strip())
payment_invoice(num_invoice)
print(show_data())
else:
next = False
break | false |
5a909adc2afee84b66d5b2b234ba71e55da4e5a3 | A-creater/turtle_exemple | /event_button.py | 2,384 | 4.28125 | 4 | import turtle
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
class Button(turtle.Turtle):
point1: Point
point2: Point
title: str
def __init__(self, point1: Point, point2: Point, title: str):
super(Button, self).__init__()
self.point1 = point1
self.point2 = point2
self.title = title
self.draw_button()
def draw_button(self):
""" Рисование кнопки"""
turtle.tracer(False)
self.hideturtle()
self.up()
self.goto(self.point1.x, self.point1.y)
self.down()
self.goto(self.point2.x, self.point1.y)
self.goto(self.point2.x, self.point2.y)
self.goto(self.point1.x, self.point2.y)
self.goto(self.point1.x, self.point1.y)
turtle.tracer(True)
def on_button(self, x, y):
""" Обработчик нажатия кнопки"""
pass
def test_button(self, x: int, y: int):
""" Проверка нажатия на кнопку и вызов обработчика"""
pass
class SquareButton(Button):
def on_button(self, x, y):
""" Обработчик нажатия на кнопку"""
print('Нажата квадратная кнопка')
def test_button(self, x: int, y: int):
if self.point1.x < x < self.point2.x and self.point1.y > y > self.point2.y:
print(f'( {x}, {y})')
self.on_button(x, y)
class RoundButton(Button):
pass
class HelloButton(SquareButton):
def on_button(self, x, y):
print(f'HelloButton {self.title}')
turtle.tracer(False)
t = turtle.Turtle()
t.up()
t.goto(x, y)
turtle.tracer(True)
b1 = SquareButton(Point(-300, 0), Point(-200, -200), title="1")
b2 = SquareButton(Point(0, 0), Point(200, -200), title="2")
b4 = SquareButton(Point(-50, 40), Point(20, -20), title="3")
builtins = [b1, b2, b4]
def on_click_screen(x, y):
for obj in builtins:
obj.test_button(x, y)
# def button_on_click(x, y):
# if x1 < x < x2 and y1 > y > y2:
# print(f"Квадратная кнопка нажата {x}, {y}")
# if (x**2+y**2) <= (radius**2):
#
# print(f"Круглая кнопка {x}, {y}")
turtle.onscreenclick(on_click_screen)
turtle.done()
# (x - x0)^2 + (y - y0)^2 <= R^2
| false |
554e1ac6391e6f8582fcf1e48f3d724e4d992c42 | Romeo2393/First-Code | /Comparison Operator.py | 220 | 4.21875 | 4 | temperature = 30
temperature = int(input("What's the temperature outside? "))
if temperature > 30:
print("It's a hot day")
elif temperature < 10:
print("Its a cold day")
else:
print("Enjoy your day") | true |
3eebb69e178befbda33ea9fe8289474751af63b8 | Reyloso/Test_Ingenieria_datos | /fibonacci.py | 2,958 | 4.1875 | 4 |
from math import log10, sqrt
"""
Serie Fibonacci
La secuencia de Fibonacci es una secuencia de números con la relación:
𝐹𝑛=𝐹𝑛-1𝐹𝑛-2, donde 𝐹1=1 y 𝐹2=1
Resulta que 𝐹541 contiene 113 dígitos y es el primer número de Fibonacci donde los
últimos 9 dígitos son una secuencia pan-digital (que contiene todos los números del 1 al 9,
pero no es necesario que estén en orden). Por otro lado 𝐹2749 contiene 757 dígitos y es el
primer número de Fibonacci donde los primeros 9 dígitos son una secuencia pan-digital. 𝐹𝑘 es
el primer número de Fibonacci donde los primeros 9 dígitos son una secuencia pan-digital y
donde los últimos 9 dígitos también son una secuencia pan-digital.
¿Cuánto es 𝐾?
serie fibonacci es una serie infinita en la que la suma de dos números consecutivos
siempre da como resultado el siguiente número (1+1=2; 13+21=34).
Los números y las fórmulas pandigitales son aquellas expresiones matemáticas en cuya construcción
aparecen al menos una vez todos los dígitos que constituyen la base de numeración en la que están escritos. La base 10 es la más usada para construir expresiones
pandigitales, pues se trata de la base más pequeña que usa todos los guarismos existentes (0, 1, 2, ,3 ,4 ,5, 6, 7, 8, 9) para denotar números.
"""
# en este caso se utiliza una formula racion de oro
M = 1000000000
# segun la formula se le saca la raiz cuadrada a 5
sqrt5 = sqrt(5)
# esto da solo los primeros 10 digitos
fn = (sqrt5+1)/2
# siguiendo la formula halla el logaritmo de fn
phi = log10(fn)
# y luego se procede a hallar el logaritmo a raiz cuadrada de 5
logsqrt5 = log10(sqrt5)
def test(n):
"""fucion que valida si n es un numero pan digital mientras no contenga todos los numeros"""
if n < 100000000: return False
flags = [0]*10
flags[0] = 1
while n > 0:
n, m = n//10, n%10
if flags[m]: return False
flags[m] = 1
return True
def run():
a, b, k = 1, 1, 2
while True:
""" while que buscar la serie fibonacci entre todos los numeros de la serie hasta llegar a 𝐹2749 """
a, b, k = b, a+b, k+1
a, b, k = b % M, (a+b)%M, k+1
# se comprueba si el numero cumple con las condiciones de pan digital
if test(b):
# se k se multiplica por el log de fn y se le resta el logaritmo de la raiz cuadrada de 5
phik = phi*k-logsqrt5
# se halla n donde 10 elevenado a la potencia de la variable donde se almaceno el resultado de la multiplicacion anterior
# menos el logaritmo de fn por el valor de k mas 9 y luego se usa // para hacer una divicion entre 10 el resultado sera un numero entero
n = int(10**(phik-int(phi*k)+9))//10
# se usa de forma recursiva esta funcion para determinar si el valor de n cumple las condiciones para ser pandigital
if test(n): break
print("el valor de k es", k)
run()
| false |
84e23d7bb5df3549b754b9785c6c4a906f504a97 | zacniewski/Decorators_intro | /05_decorators_demystified.py | 1,460 | 4.1875 | 4 | """The previous example, using the decorator syntax:
@my_shiny_new_decorator
def another_stand_alone_function():
print "Leave me alone"
another_stand_alone_function()
#outputs:
#Before the function runs
#Leave me alone
#After the function runs
Yes, that's all, it's that simple. @decorator is just a shortcut to:
another_stand_alone_function = my_shiny_new_decorator(another_stand_alone_function)
"""
"""Decorators are just a pythonic variant of the decorator design pattern.
There are several classic design patterns embedded in Python to ease development, like iterators.
Of course, you can cumulate decorators:"""
def bread(func):
def wrapper():
print "</''''''\>"
func()
print "<\______/>"
return wrapper
def ingredients(func):
def wrapper():
print "#tomatoes#"
func()
print "~salad~"
return wrapper
def sandwich(food="--ham--"):
print food
sandwich()
#outputs: --ham--
sandwich = bread(ingredients(sandwich))
sandwich()
#outputs:
#</''''''\>
# #tomatoes#
# --ham--
# ~salad~
#<\______/>
#Using the Python decorator syntax:
@bread
@ingredients
def sandwich(food="--ham--"):
print food
sandwich()
#outputs:
#</''''''\>
# #tomatoes#
# --ham--
# ~salad~
#<\______/>
#The order you set the decorators MATTERS:
@ingredients
@bread
def strange_sandwich(food="--ham--"):
print food
strange_sandwich()
#outputs:
##tomatoes#
#</''''''\>
# --ham--
#<\______/>
# ~salad~ | true |
f170a6023f6c27d8c4e1b77ff865275fa33dd551 | david-ryan-alviola/winter-break-practice | /hackerRankPython.py | 1,977 | 4.40625 | 4 | # 26-DEC-2020
# Print Hello, World! to stdout.
print("Hello, World!")
# Given an integer, , perform the following conditional actions:
# If is odd, print Weird
# If is even and in the inclusive range of 2 to 5, print Not Weird
# If is even and in the inclusive range of 6 to 20, print Weird
# If is even and greater than 20, print Not Weird
n = input()
if (n % 2 == 0):
if (n >= 2 and n <= 5):
print("Not Weird")
elif (n >=6 and n <= 20):
print("Weird")
else:
print("Not Weird")
else:
print("Weird")
# The provided code stub reads two integers from STDIN, a and b. Add code to print three lines where:
# The first line contains the sum of the two numbers.
# The second line contains the difference of the two numbers (first - second).
# The third line contains the product of the two numbers.
print(a + b)
print(a - b)
print(a * b)
# The provided code stub reads two integers, a and b, from STDIN.
# Add logic to print two lines. The first line should contain the result of integer division, a//b . The second line should contain the result of float division, a/b .
# No rounding or formatting is necessary.
print(a//b)
print(a/b)
# 30-DEC-2020
# The provided code stub reads an integer, n, from STDIN. For all non-negative integers i < n, print i^2.
if n >= 0:
for i in range(n):
print(i * i)
# Given a year, determine whether it is a leap year. If it is a leap year, return the Boolean True, otherwise return False.
# Note that the code stub provided reads from STDIN and passes arguments to the is_leap function. It is only necessary to complete the is_leap function.
def is_leap(year):
leap = False
if(year % 4 == 0 and year % 100 > 0):
leap = True
else:
if (year % 100 == 0 and year % 400 == 0):
leap = True
return leap
# Print the list of integers from 1 through n as a string, without spaces.
for i in range(n):
print(i + 1, end="")
| true |
10eadac8c43d0dab3039732e0fa8b497a875c3b7 | arturfil/data-structures-and-algorithms | /sort/insertion_sort.py | 453 | 4.21875 | 4 | def insertion_sort(arr):
# traverse through index 0 to len(arr)
for i in range(1, len(arr)):
current_value = arr[i]
position = i
while position > 0 and arr[position - 1]>current_value:
arr[position] = arr[position-1]
position = position - 1
arr[position] = current_value
# testing algorithm
arr_1 = [5,2,7,99,22,33,66,32,11,22]
print(f"Unsorted array {arr_1}")
insertion_sort(arr_1)
print(f"\nSorted array {arr_1}")
| false |
701c8ac9df8e1544c22b63d94e2894fbf20ab04c | PaulGG-Code/Security_Python | /Simple_File_Character_Calculator.py | 242 | 4.1875 | 4 | #open file in read mode
file = open("D:\data.txt", "r")
#read the content of file
data = file.read()
#get the length of the data
number_of_characters = len(data)
print('Number of characters in text file :', number_of_characters)
| true |
835f358f71f3a8e6361c2c5fa0a8ed765e58386b | jakupierblina/learning-python | /tutorial/set.py | 1,059 | 4.1875 | 4 |
x = set('abcde')
y = set('bdxyz')
print('e' in x) # membership
print(x-y) #difference
print(x | y) #union
print(x & y) #intersection
print(x ^ y) #symmetric difference
print(x > y, x < y) #superset, subset
z = x.intersection(y) #find the same elements
z.add('SPAM')
print(z)
z.update(set(['X', 'Y'])) #update the set and add two elements
print(z)
z.remove('X') #delete one element
print(z)
print(y)
for item in y:
print(item * 3)
''' Why sets?
Set operations have a variety of common uses, some more practical than mathematical
'''
L=[1,2,3,1,1,3,4,5]
set(L)
L=list(set(L)) #remove duplicates
print(L)
#check if an elements exits in a set
print(7 in L)
A = "spam"
B = A
B = "shrubbery"
print(A)
A = ["spam"]
B = A
B[0] = "shrubbery"
print(A)
A = ["spam"]
B = A[:]
B[0] = "shrubbery"
print(A)
S = 'hello,world'
print(S.split(','))
print(S.isdigit())
print(S.rstrip())
print(S.lower())
print(S.endswith('spam'))
print(S.encode('latin-1'))
for x in S: print(x)
print('spam' in S)
print([c * 1 for c in S])
print(map(ord, S))
print(S * 2) | true |
0a4cf1075711c3b98b5d6dfd88b0065aec99c044 | stephenchenxj/myLeetCode | /findDiagonalOrder.py | 1,512 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
498. Diagonal Traverse
Medium
Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order as shown in the below image.
Example:
Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,4,7,5,3,6,8,9]
Explanation:
Note:
The total number of elements of the given matrix will not exceed 10,000.
Accepted
62,044
Submissions
133,071
"""
class Solution(object):
def findDiagonalOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
r = len(matrix)
if r == 0:
return []
c = len(matrix[0])
print(r)
print(c)
print(matrix[r-1][c-1])
result = []
for i in range(r-1+c):
print('i = %d' %i)
if i%2 == 0:
#go up right
for j in range(i+1):
if (i-j) < r and j < c:
result.append(matrix[i-j][j])
else:
#go down left
for j in range(i+1):
if(i-j) <c and j<r:
result.append(matrix[j][i-j])
return result
def main():
print(len([]))
matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
ret = Solution().findDiagonalOrder(matrix)
print(ret)
if __name__ == '__main__':
main() | true |
f8ff8c47fe3b6f6532182ec3474a1405f8293638 | stephenchenxj/myLeetCode | /reverseInteger.py | 1,146 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Oct 5 00:44:11 2019
@author: stephen.chen
"""
'''
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers
within the 32-bit signed integer range: [−2^31, 2^31 -1]. For the purpose of
this problem, assume that your function returns 0 when the reversed integer
overflows.
'''
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
sign = 1
if x < 0:
sign = -1
x= -1*x
result = 0
while x > 0:
y = x % 10
x = int((x-y)/10)
result = result*10 + y
result = sign*result
if result < -2**31 or result > 2**31-1:
return 0
return result
def main():
mySolution = Solution()
print (mySolution.reverse(12030))
if __name__ == "__main__":
main() | true |
da0019078824aa244442fbf23e20fb33814c05af | stephenchenxj/myLeetCode | /shuffle.py | 1,386 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Oct 11 20:26:42 2019
@author: stephen.chen
Shuffle an Array
Shuffle a set of numbers without duplicates.
Example:
// Init an array with set 1, 2, and 3.
int[] nums = {1,2,3};
Solution solution = new Solution(nums);
// Shuffle the array [1,2,3] and return its result. Any permutation of [1,2,3] must equally likely to be returned.
solution.shuffle();
// Resets the array back to its original configuration [1,2,3].
solution.reset();
// Returns the random shuffling of array [1,2,3].
solution.shuffle();
"""
import copy
import random
class Solution(object):
def __init__(self, nums):
self.array = nums
self.original = list(nums)
def reset(self):
self.array = self.original
self.original = list(self.original)
return self.array
def shuffle(self):
aux = list(self.array)
for idx in range(len(self.array)):
remove_idx = random.randrange(len(aux))
self.array[idx] = aux.pop(remove_idx)
return self.array
print (random.randrange(2))
l = [1,2,3,4]
print(l.pop(2))
print(l)
mySolution = Solution([1,2,3,4])
print(mySolution.shuffle())
print(mySolution.reset())
print(mySolution.shuffle())
# Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.reset()
# param_2 = obj.shuffle() | true |
89da494a7cae93de6c64d9220ff8a598c14499e0 | stephenchenxj/myLeetCode | /python_search_dict_by_value.py | 220 | 4.28125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 13 15:06:15 2020
@author: chen
"""
mydict = {1:'a', 2:'b', 3:'a'}
value = 'a'
keys = [ key for key,val in mydict.items() if val==value ]
print(keys) | false |
b0ba8f4f5411931d0d106a1e4ff75c15deb4a32c | christian-alexis/edd_1310_2021 | /colas.py | 2,818 | 4.15625 | 4 | #PRUEBAS DE LAS COLAS
class Queue:
def __init__(self):
self.__data = list()
def is_empty (self):
return len(self.__data)==0
def length(self):
return len(self.__data)
def enqueue(self,elem):
self.__data.append(elem)
def dequeue (self):
if not self.is_empty():
return self.__data.pop(0)
else:
return None
def to_string (self):
cadena = ""
for elem in self.__data:
cadena = cadena + "|" + str(elem)
cadena = cadena +"|"
return cadena
#PRUEBAS DE LAS COLAS CON PRIORIDAD NO ACOTADA
class PriorityQueue:
"""
This priority queue uses a given number as priority order.
The smallest number has the higher priority
"""
def __init__(self):
self.__data = list()
def is_empty (self):
return len(self.__data)==0
def length(self):
return len(self.__data)
def enqueue(self, value: str, priority: int) -> None:
"""Add the value the queue based on its priority"""
self.__data.append((value, priority))
self.__data = reorder_queue(self.__data)
def dequeue (self):
if not self.is_empty():
return self.__data.pop(0)
else:
return None
def to_string (self):
cadena = ""
for elem in self.__data:
cadena = cadena + "|" + str(elem)
cadena = cadena +"|"
return cadena
def reorder_queue(queue):
return sorted(queue, key=lambda v: v[1])
#PRUEBAS DE LAS COLAS CON PRIORIDAD ACOTADA
class BoundedPriorityQueue:
def __init__( self , niveles):
self.__data=[Queue() for x in range(niveles) ]
self.__size=0
def is_empty(self):
return self.__size == 0
def length(self):
return self.__size
def enqueue(self,prioridad,elem):
if prioridad < len(self.__data) and prioridad >= 0:
self.__data[prioridad].enqueue(elem)
self.__size +=1
def dequeue (self):
if not self.is_empty():
for nivel in self.__data:
if not nivel.is_empty():
self.__size -=1
return nivel.dequeue()
def to_string (self):
if not self.is_empty():
for nivel in range (len(self.__data)):
print(f"Nivel {nivel}-->{ self.__data[nivel].to_string()}")
print("-------------------------------------------------------")
else:
print("\n************** EL BARCO FUE ABANDONADO **************\n")
| true |
0ffe4afc95e64efe667b76c42dbae97687b2160d | mendozatori/python_beginner_proj | /rainfall_report/rainfall_report.py | 1,305 | 4.3125 | 4 | # Average Rainfall Application
# CONSTANTS
NUM_MONTHS = 12
# initialize
total_inches = 0.0
# input
years = int(input("How many years are we calculating for? "))
while years < 0:
print("Please enter a valid number of years!")
years = int(input("How many years are we calculating for? "))
# x will continue to increment by 1 until it reaches number of years inputted
for x in range(years):
print('')
print('---------------------')
print("RAINFALL FOR YEAR " + str(x + 1))
print('---------------------')
print('')
# y will continue to increment by 1 until it reaches 12 "months"
for y in range(NUM_MONTHS):
month_rain = float(input("Inches of rainfall for month " + str(y + 1) + ": "))
while month_rain < 0:
print("Please enter a valid number of inches of rainfall!")
month_rain = float(input("Inches of rainfall for month " + str(y + 1) + ": "))
total_inches = total_inches + month_rain
# calculations
total_months = NUM_MONTHS * years
average_rainfall = total_inches / total_months
print('')
print("-------SUMMARY--------")
print("Number of months: ", total_months)
print("Total inches of rainfall: ", total_inches)
print("Average rainfall per month: ", average_rainfall) | true |
3b811ee60b5aee105510e413af107661e2127836 | tenzin1308/PythonBasic | /Class/TypesOfMethods.py | 711 | 4.125 | 4 | """
We have 3 types of Methods:
a) Instances/Object Methods
b) Class Methods
c) Static Methods
"""
class Student:
# Class/Static Variable
school = "ABC School"
def __init__(self, m1, m2, m3):
self.m1 = m1
self.m2 = m2
self.m3 = m3
# Instances/Object Methods
def avg(self):
return (self.m1 + self.m2 + self.m3) / 3
# Class Methods
@classmethod ## Decorator
def getSchool(cls):
print(cls.school)
# Static Methods
@staticmethod
def info():
print("This is Static Method")
s1 = Student(67, 87, 76)
s2 = Student(98, 67, 78)
print(s1.avg())
print(s2.avg())
Student.getSchool()
Student.info()
| true |
23f386c4f97055645a6724a76dc49f3b7a93c93b | pc2459/learnpy | /csv_parse.py | 2,455 | 4.15625 | 4 | """
Write a script that will take three required command line arguments - input_file,
output_file, and the row_limit. From those arguments, split the input CSV into
multiple files based on the row_limit argument.
Arguments:
1. -i: input file name
2. -o: output file name
3. -r: row limit to split
Default settings:
1. output_path is the current directory
2. headers are displayed on each split file
3. the default delimiter is a comma
"""
from __future__ import division
import argparse
import csv
import os
import math
import sys
# create a parser to handle command-line arguments
parser = argparse.ArgumentParser()
#store input file name
parser.add_argument('-i', action='store')
#store output file name
parser.add_argument('-o', action='store')
#store number of rows
parser.add_argument('-r', action='store')
args = parser.parse_args()
total_rows = 0
# check to see if rows is an integer
try:
rows = int(args.r)
except ValueError:
# error handle and quit if does not eixst
print "You didn't input an integer"
sys.exit(0)
# check to see if input exists
try:
with open(args.i) as file:
pass
except IOError:
# error handle and quit if does not exist
print "Your input file does not exist"
sys.exit(0)
# count total number of rows
with open(args.i) as input:
total_rows = sum(1 for row in input)-1
if total_rows <= rows:
print "The split number is more than or equal to the size of the CSV to split"
sys.exit(0)
##########################
#find out the number of CSVs needed
segments = math.ceil(total_rows/rows)
#open the input and begin to read
input = open(args.i, "r")
reader = csv.reader(input)
# Store the header
header = reader.next()
# Create an list to store header + N rows
templist = []
current = 1
rownum = 0
while current <= segments:
# Add rows to the templist
for i in range(rows):
try:
line = reader.next()
templist.append(line)
rownum += 1
except StopIteration:
pass
# Write the templist to an output
with open(args.o+str(current)+".csv", "wb") as output:
writer = csv.writer(output)
# Write in the header
writer.writerow(header)
# Write in the remainder of the lines
for line in templist:
writer.writerow(line)
# Print out message to the user
print "Chunk written to {} with {} lines".format(args.o+str(current)+".csv",rownum)
# Reset the templist, row counters
templist = []
rownum = 0
# Move on to the next output file
current += 1
input.close() | true |
da75fe91a98fc2861ee2fbf266e5223eeac0c9b4 | austincunningham/python_exercises | /5_Miles_to_Feet.py | 275 | 4.21875 | 4 | #!/usr/bin/python3
def Miles_to_Feet(Miles):
feet = (Miles * 5280)
print ("%1.0f feet in %1.0f miles" %(feet,Miles))
def main():
print("Enter number of miles to convert to feet")
mile = input(">")
Miles_to_Feet(mile)
if __name__=='__main__':
main()
| false |
2791583af83b9ff15ac5fe9d30acd2313e6cfd2a | kirteekishorpatil/dictionary | /studant_data_8.py | 375 | 4.34375 | 4 | # i=0
# dict1={}
# if i<3:
# num=input("enter the student name")
# num2=int(input("enter the students marks"))
# i=i+1
# new_type={num:num2}
# dict1.update(new_type)
# print(dict1)
num=input("enter the student name")
num2=int(input("enter the students marks"))
# i=0
dict1={}
# while i<8:
new_type={num:num2}
dict1.update(new_type)
# i=i+1
print(dict1)
| true |
7af8b77a791d567ac85b2749936633f166f719f7 | Ratashou/Tic-Tac-Toe | /tictactoe.py | 2,675 | 4.25 | 4 | #! python3
#A program to make a simple tic tac toe/noughts and crosses game
theBoard = {'top-L': ' ', 'top-M': ' ', 'top-R': ' ',
'mid-L': ' ', 'mid-M': ' ', 'mid-R': ' ',
'bot-L': ' ', 'bot-M': ' ', 'bot-R': ' '} #the different positions on the board
def printBoard(ticSpace):
print(ticSpace['top-L'] + '|' + ticSpace['top-M'] + '|' + ticSpace['top-R'])
print('-+-+-')
print(ticSpace['mid-L'] + '|' + ticSpace['mid-M'] + '|' + ticSpace['mid-R'])
print('-+-+-')
print(ticSpace['bot-L'] + '|' + ticSpace['bot-M'] + '|' + ticSpace['bot-R']) #this function prints out a n+c board
printBoard(theBoard)
print('Who is going first? X or O?')
turn = input()
while turn != 'X' and turn!= 'O': #for an incorrect input
print('A correct value wasn''t entered')
print('Please enter either X or O to determine which piece will go first')
turn = input()
usedMoves = [] #a list to check whether a selected move has been chosen already or not
for i in range(9): #for all 9 positions on the board
print ('Choose a position to place an ' + turn + '''
top-L (for top left)
top-M (top middle)
top-R (top right)
mid-L (middle left)
mid-M (the middle)
mid-R (middle right)
bot-L (bottom left)
bot-M (bottom middle)
bot-R (bottom right)''')
move = input()
while move in usedMoves:
print('This position has already been chosen, choose another')
move = input()
usedMoves.append(move)
theBoard[move] = turn #this takes the piece (X or O) currently playing and places it in the inputted position
printBoard(theBoard)
if (theBoard['top-L'] == turn and theBoard['top-M'] == turn and theBoard['top-R'] == turn) or \
(theBoard['mid-L'] == turn and theBoard['mid-M'] == turn and theBoard['mid-R'] == turn) or \
(theBoard['bot-L'] == turn and theBoard['bot-M'] == turn and theBoard['bot-R'] == turn) or \
(theBoard['top-L'] == turn and theBoard['mid-L'] == turn and theBoard['bot-L'] == turn) or \
(theBoard['top-M'] == turn and theBoard['mid-M'] == turn and theBoard['bot-M'] == turn) or \
(theBoard['top-R'] == turn and theBoard['mid-R'] == turn and theBoard['bot-R'] == turn) or \
(theBoard['top-L'] == turn and theBoard['mid-M'] == turn and theBoard['bot-R'] == turn) or \
(theBoard['top-R'] == turn and theBoard['mid-M'] == turn and theBoard['bot-L'] == turn):
win = 1
break
if turn == 'X':
turn = 'O'
else:
turn = 'X'
win = 0
if win == 1:
print('Congratulations! ' + turn + ' wins!')
else:
print('No one wins!')
| false |
2bbf90d8645ba21f97c0e4fc635cd50be9bffe2c | milnorms/pearson_revel | /ch7/ch7p5.py | 841 | 4.15625 | 4 | '''
(Sorted?)
Write the following function that returns True if the list is already sorted in increasing order:
def isSorted(lst):
Write a test program that prompts the user to enter a list of numbers separated by a space in one line and displays whether the list is sorted or not. Here is a sample run:
Sample Run 1
Enter list: 1 1 3 4 4 5 7 9 10 30 11
The list is not sorted
Sample Run 2
Enter list: 1 1 3 4 4 5 7 9 10 30
The list is already sorted
'''
def main():
nums = getInt(input("Enter list: "))
print("The list is already sorted" if isSorted(nums) else "The list is not sorted")
def getInt(string):
score = string.split(" ")
for i in range(len(score)):
score[i] = int(score[i])
return score
def isSorted(lst):
s = sorted(lst)
if s == lst:
return True
return False
main()
| true |
97d6ffbe6671998c18f37757459a61aea61de6f0 | milnorms/pearson_revel | /ch8/ch8p4.py | 1,626 | 4.46875 | 4 | '''
(Markov matrix)
An n by n matrix is called a positive Markov matrix if each element is positive and the sum of the elements in each column is 1. Write the following function to check whether a matrix is a Markov matrix:
def isMarkovMatrix(m):
Write a test program that prompts the user to enter a 3 by 3 matrix of numbers and tests whether it is a Markov matrix. Note that the matrix is entered by rows and the numbers in each row are separated by a space in one line.
Sample Run 1
Enter a 3-by-3 matrix row by row:
0.15 0.875 0.375
0.55 0.005 0.225
0.30 0.12 0.4
It is a Markov matrix
Sample Run 2
Enter a 3-by-3 matrix row by row:
0.95 -0.875 0.375
0.65 0.005 0.225
0.30 0.22 -0.4
It is not a Markov matrix
'''
def main():
m = []
print("Enter a 3-by-3 matrix row by row:")
for i in range(3):
s = input("")
s = [float(x) for x in s.split()]
m.append(s)
s = ""
print("It is a Markov matrix" if isMarkovMatrix(m) else "It is not a Markov matrix")
def isMarkovMatrix(m):
total = 0
isMark = False
for i in range(3):
total += m[i][0]
if total == 1:
isMark = True
total = 0
if isMark:
for i in range(3):
total += m[i][1]
if total == 1:
isMark == True
total = 0
else:
isMark == False
if isMark:
for i in range(3):
total += m[i][2]
if total == 1:
isMark == True
total = 0
else:
isMark == False
return isMark
main()
| true |
d5ae42360d6c5b28032c26f94bf5570608378ae7 | milnorms/pearson_revel | /ch4/ch4p2.py | 888 | 4.3125 | 4 | '''
(Convert letter grade to number)
Write a program that prompts the user to enter a letter grade A/a, B/b, C/c, D/d, or F/f and displays its corresponding numeric value 4, 3, 2, 1, or 0.
Sample Run 1
Enter a letter grade: B
The numeric value for grade B is 3
Sample Run 2
Enter a letter grade: b
The numeric value for grade b is 3
Sample Run 3
Enter a letter grade: T
T is an invalid grade
'''
input = input("Enter a letter grade: ")
grade = input.lower()
if grade == 'a':
print("The numeric value for grade", input, "is 4")
elif grade == 'b':
print("The numeric value for grade", input, "is 3")
elif grade == 'c':
print("The numeric value for grade", input, "is 2")
elif grade == 'd':
print("The numeric value for grade", input, "is 1")
elif grade == 'f':
print("The numeric value for grade", input, "is 0")
else:
print(input, "is an invalid grade")
| true |
c54e78731fa62bc05f222e87bb91d0961b89766a | milnorms/pearson_revel | /ch2/ch2p5.py | 1,009 | 4.21875 | 4 | '''
(Financial application: calculate future investment value)
Write a program that reads in an investment amount, the annual interest rate, and the number of years, and then displays the future investment value using the following formula:
futureInvestmentAmount = investmentAmount * (1 + monthlyInterestRate) ^ numberOfMonths
For example, if you enter the amount 1000.56, an annual interest rate of 4.25%, and the number of years as 1, the future investment value is 1043.33. Here is a sample run:
Enter investment amount: 1000.56
Enter annual interest rate: 4.25
Enter number of years: 1
Accumulated value is 1043.92
'''
investmentAmount = float(input("Enter investment amount: "))
interestRate = float(input("Enter annual interest rate: "))
years = float(input("Enter number of years: "))
monthlyInterestRate = (interestRate * 0.01) / 12
numberOfMonths = years * 12
futureInvestmentAmount = investmentAmount * ((1 + monthlyInterestRate) ** numberOfMonths)
print(round(futureInvestmentAmount, 2))
| true |
f96567cd7769179e1192ddda76022832c3454a8f | Saksykov/Stepik_Python_Courses | /introduction_to_python_practicum/lesson2.2_step5.py | 533 | 4.125 | 4 | """
Простое число делится без остатка только на 1 и на само себя.
Напишите программу, которая прочитает число и выведет "prime" если число простое и
"composite" в противном случае (без кавычек).
"""
x = int(input())
j = x - 1
f = True
while j > 1:
if x % j != 0:
j -= 1
continue
else:
f = False
break
if f:
print("prime")
else:
print("composite")
| false |
94e1e2f107723e9ea3d4ea648cbd16487b69af16 | pectoraux/python_programs | /question5.py | 2,323 | 4.125 | 4 | '''
Efficiency:
----------------------------------------------
member function get_length() of class Linked_List runs in O(1)
member function get_at_position() of class Linked_List runs in O(n)
make_ll() runs in O(n)
So question5() runs in O(n)
'''
class Node(object):
def __init__(self, data):
self.data = data
self.next = None
def __str__(self):
return str(self.data)
class Linked_List(object):
"""
Linked list class with necessary functions
for the problem implemented: a printer for debugging
a .get_at_position() method to get an element at a position
a .get_length() method to get the element that is m position
away faster by doing: ll.get_at_position(ll.get_length - m)
and a .append() method to populate the linked list
"""
def __init__(self, head=None):
self.head = head
if head:
self.length = 1
else:
self.length = 0
def printer(self):
current = self.head
while current:
print current
current = current.next
def get_length(self):
return self.length
def get_at_position(self, position):
counter = 1
current = self.head
if position < 0 :
return None
while current and counter <= position:
if counter == position:
return current
current = current.next
counter += 1
return None
def append(self, new_element):
current = self.head
if self.head:
while current.next:
current = current.next
current.next = new_element
else:
self.head = new_element
self.length += 1
def question5(ll, m):
""" Takes in a linked list and a position m
Returns the element that is m element from the end
"""
ll_len = ll.get_length()
return ll.get_at_position(ll_len-m)
def make_ll(arr):
"""Takes in an array and turns it into a linked list
Useful for testing purposes
"""
my_ll = Linked_List()
for i in range(len(arr)):
my_ll.append(Node(arr[i]))
#my_ll.printer() # prints the final linked list; useful for debugging
return my_ll
def run():
# Test 1
print question5(make_ll(['elephant', 'shoes', 'basket']), 0) # Should return basket
# Test 2
print question5(make_ll(range(10)), 4) # Should return 5
# Test 3
print question5(make_ll([None, 'forward', '', '-', 'right']), 1) # Should return -
if __name__ == '__main__':
run() | true |
41ad1238055f8657136aebbfdddd50e81ac0e66b | ebrahim-j/FindMissingLab | /MissingNumber.py | 662 | 4.125 | 4 | def find_missing(list1, list2):
inputList = [] #list with extra number
checkList = [] #template list
if len(list1) > len(list2): #determines the variable (input and check)lists will be assigned to
inputList = list1
checkList = list2
else:
inputList = list2
checkList = list1
missing_num = [] #missing number to be stored in array
for i in inputList:
if i not in checkList: #if current number not in template list, that is added to missing list array
missing_num.append(i)
if len(missing_num) == 0: #if no outstanding number/value found
return 0
return missing_num.pop()
| true |
4cd52636027021227a8195e5a0a8ed31cb7753b3 | 7Aishwarya/HakerRank-Solutions | /30_Days_of_Code/day5_loops.py | 343 | 4.125 | 4 | '''Given an integer, n, print its first 10 multiples. Each multiple n x i (where 1<=i<=10) should be printed on a new line
in the form: n x i = result.'''
#!/bin/python3
import math
import os
import random
import re
import sys
if __name__ == '__main__':
n = int(input())
for i in range(10):
print(n,"x",i+1,"=",n*(i+1))
| true |
8bb2e6edbb2d703ad41e899b57cb32b228676557 | 7Aishwarya/HakerRank-Solutions | /Algorithms/beautiful_days_at_the_movies.py | 1,685 | 4.46875 | 4 | '''Lily likes to play games with integers. She has created a new game where she determines the difference between a number and
its reverse. For instance, given the number 12, its reverse is 21. Their difference is 9. The number 120 reversed is 21, and their
difference is 99.
She decides to apply her game to decision making. She will look at a numbered range of days and will only go to a movie on a
beautiful day.
Given a range of numbered days, [i...j] and a number k, determine the number of days in the range that are beautiful.
Beautiful numbers are defined as numbers where |i-reverse(i)| is evenly divisible by k. If a day's value is a beautiful
number, it is a beautiful day. Print the number of beautiful days in the range.
Function Description
Complete the beautifulDays function in the editor below. It must return the number of beautiful days in the range.
beautifulDays has the following parameter(s):
i: the starting day number
j: the ending day number
k: the divisor
'''
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the beautifulDays function below.
def beautifulDays(i, j, k):
count = 0
for x in range(i,j+1,1):
reverse = 0
temp = x
while(x > 0):
reminder = x % 10.
reverse = (reverse * 10) + reminder
x = x // 10
if((abs(temp - reverse))%k == 0):
count+=1
return count
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
ijk = input().split()
i = int(ijk[0])
j = int(ijk[1])
k = int(ijk[2])
result = beautifulDays(i, j, k)
fptr.write(str(result) + '\n')
fptr.close()
| true |
6ce7779a588924aab0caea37a70bbe7be5d93ff2 | 7Aishwarya/HakerRank-Solutions | /30_Days_of_Code/day25_running_time_and_complexity.py | 745 | 4.15625 | 4 | '''Given a number, n find if it is prime or not.
Input Format
The first line contains an integer, T, the number of test cases.
Each of the T subsequent lines contains an integer, n, to be tested for primality.
Constraints
1<=T<=30
1<=n<=2*10^9
Output Format
For each test case, print whether n is Prime or Not Prime on a new line.'''
# Enter your code here. Read input from STDIN. Print output to STDOUT
import math
n = int(input())
for i in range(n):
num = int(input())
sqrt = int(math.sqrt(num))
if num > 1:
for i in range(2,sqrt+1):
if (num % i) == 0:
print("Not prime")
break
else:
print("Prime")
else:
print("Not prime")
| true |
c0afc50c0c7194f15656f6b58464908626e4c230 | VITA-mlr/cbs_lessons | /Python/es_4-2_iterator_generator.py | 1,409 | 4.25 | 4 | """
task1:
Напишите итератор, который возвращает элементы заданного списка в обратном порядке (аналог reversed).
task2:
Перепишите решение первого задания с помощью генератора.
"""
class ListIterator:
def __init__(self, collection):
self.collection = collection
self.cursor = len(self.collection)
def __iter__(self):
return ListIterator(self.collection)
def __next__(self):
self.cursor -= 1
if self.cursor < 0:
raise StopIteration()
else:
return self.collection[self.cursor]
def task1(some_list):
"""Ітератор списку"""
my_iter = ListIterator(some_list)
print(some_list)
for el in my_iter:
print('Елемент - ', el)
def task2(some_list):
"""Генератор списку"""
index = len(some_list) - 1
print(some_list)
while index >= 0:
yield some_list[index]
index -= 1
def main():
my_list = [1, 2, 3, 4, 5]
print('ЗАВДАННЯ 1 - ІТЕРАТОР')
task1(my_list)
print('\nЗАВДАННЯ 2 - ГЕНЕРАТОР')
for el in task2(my_list):
print('Елемент - ', el)
if __name__ == "__main__":
main()
| false |
abb691603f4655d3c1a116d94b76f83655d182c3 | Jinx-Heniux/Python-2 | /maths/odd_check.py | 980 | 4.4375 | 4 | def is_odd(number: int) -> bool:
"""
Test if a number is a odd number.
:param number: the number to be checked.
:return: True if the number is odd, otherwise False.
>>> is_odd(-1)
True
>>> is_odd(-2)
False
>>> is_odd(0)
False
>>> is_odd(3)
True
>>> is_odd(4)
False
>>> all([is_odd(i) for i in range(1, 100, 2)])
True
"""
return number % 2 != 0
def is_odd_faster(number: int) -> bool:
"""
Test if a number is a odd number using bit operator.
:param number: the number to be checked.
:return: True if the number is odd, otherwise False.
>>> is_odd_faster(-1)
True
>>> is_odd_faster(-2)
False
>>> is_odd_faster(0)
False
>>> is_odd_faster(3)
True
>>> is_odd_faster(4)
False
>>> all([is_odd_faster(i) for i in range(1, 100, 2)])
True
"""
return number & 1 != 0
if __name__ == "__main__":
from doctest import testmod
testmod()
| true |
8bd8af36d1693829ebbf3e958a11b8a15fe44e0c | Jinx-Heniux/Python-2 | /sorts/quick_sort.py | 1,336 | 4.125 | 4 | """
https://en.wikipedia.org/wiki/Quicksort
"""
def quick_sort(array, left: int = 0, right: int = None):
"""
Quick sort algorithm.
:param array: the array to be sorted.
:param left: the left index of sub array.
:param right: the right index of sub array.
:return: sorted array
>>> import random
>>> array = random.sample(range(-50, 50), 10)
>>> quick_sort(array) == sorted(array)
True
>>> import string
>>> array = random.choices(string.ascii_letters + string.digits, k = 10)
>>> quick_sort(array) == sorted(array)
True
>>> array = [random.uniform(-50.0, 50.0) for i in range(10)]
>>> quick_sort(array) == sorted(array)
True
"""
if right is None:
right = len(array) - 1
if left >= right:
return
pivot = array[right] # pick last element as pivot
i = left
j = right - 1
while i <= j:
while array[i] < pivot:
i += 1
while j >= 0 and array[j] >= pivot:
j -= 1
if i < j:
array[i], array[j] = array[j], array[i]
i += 1
j -= 1
array[i], array[right] = array[right], array[i]
quick_sort(array, left, i - 1)
quick_sort(array, i + 1, right)
return array
if __name__ == "__main__":
from doctest import testmod
testmod()
| true |
82c56958204986ce03caf2d8e913b06ccf433ac5 | Jinx-Heniux/Python-2 | /searches/binary_search_recursion.py | 871 | 4.15625 | 4 | """
https://en.wikipedia.org/wiki/Binary_search_algorithm
"""
def binary_search(array, key) -> int:
"""
Binary search algorithm.
:param array: the sorted array to be searched.
:param key: the key value to be searched.
:return: index of key value if found, otherwise -1.
>>> array = list(range(10))
>>> for index, item in enumerate(array):
... assert index == binary_search(array, item)
>>> binary_search(array, 10) == -1
True
>>> binary_search(array, -1) == -1
True
"""
left = 0
right = len(array) - 1
while left <= right:
mid = (left + right) >> 1
if key == array[mid]:
return mid
elif key > array[mid]:
left = mid + 1
else:
right = mid - 1
return -1
if __name__ == "__main__":
from doctest import testmod
testmod()
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.