blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
77f5fe9c0172c1eecc723b682a3d2c82eda2918d | charliepoker/pythonJourney | /lists.py | 2,340 | 4.40625 | 4 | #list is a value that contains multiple values in an ordered sequence.
number = [23, 67, 2, 5, 69, 30] #list of values assigned to number
name = ['mike', 'jake', 'charlie', 'tim', 'dave', 'jane'] #list of values assigned to name
print(name[2] + ' is ' + str(number[5]) + ' years old.')
#list can be contained in other list
spam =[['cat', 'dog', 'bat'], [4, 80, 57, 'figo', 'ayo'], [10, 45, 100, 5, 6, 9]] #This list contains 3 lists
print(spam[1] [4])
print(spam[2] [2])
print(spam[1] [2])
#Negative indexes
animals = ['cat', 'bat', 'rat', 'elephant']
print('The ' + animals[-4] + ' is ' + 'afraid ' + ' of the ' + animals[-1] + '.')
#Getting sublist with slices
animals = ['cat', 'bat', 'rat', 'elephant', 'goat']
print(animals[1:3])
animals[1:4] = ['snake', 'fox', 'antelope']
print(animals)
name = ['mike', 'jake', 'charlie', 'tim', 'dave', 'jane']
print(name[:5]) #This is a shortcut that leaves out the first index or the begining of the list but starts the slice from 0
print(name[3:]) #This is a shortcut that leaves out the second index of the list but ends the slice at the end of the list
print(name[:]) #This is a shortcut that slices the list from the begining to the end
print(len(name)) #This gives the lenght of the list
#Changing values in the list with slices
city = ['lagos', 'abuja','kano','benin', 'jos', 'ilorin', 'ibadan', 'owerri']
city[2] = 'auchi' #This switches the value in index 2 which is kano to auchi
print(city)
city[3] = city[5] #This makes the value in index 3 same with index 5
print(city)
city[-1] = 'Bida'
print(city)
#List Concatenation and List Replication
new_list = animals + city #This adds both list together to form a new list
print(new_list)
new_list = (new_list + name)
print(new_list)
city = ['lagos', 'abuja','kano','benin', 'jos', 'ilorin', 'ibadan', 'owerri']
new_city = city * 3 #This replicates the list 3 times
print(new_city)
#Removing Values from Lists with del Statements
city = ['lagos', 'abuja','kano','benin', 'jos', 'ilorin', 'ibadan', 'owerri']
del(city[2]) # this removes the value at index 2 from the list
print(city)
#list(function)
x = ('Hello World')
list(x)
print(list(x))
| true |
0211c3fa0ff36391c2394f1ea8973d07d4555c87 | bodawalan/HackerRank-python-solution | /cdk.py | 2,845 | 4.3125 | 4 | # Q.1
#
# Write a function that takes as input a minimum and maximum integer and returns
# all multiples of 3 between those integers. For instance, if min=0 and max=9,
# the program should return (0, 3, 6, 9)
#
# A
# you can type here
def func(min, max):
for in xrange(min, max):
if (i % 3 == 0)
print
i
end
# Q.2
# Write a function to detect whether a string is a palindrome - that is,
# the string reads the same in reverse as it does forward. Samples:
# racecar, tacocat, madam, level, etc. Function should return True or False
def main():
inputStr = input("Enter a string": ")
if ispalindrome(inputStr):
print("String is Palindrome")
else:
print("String is not palindrome")
def isPalindrome(string):
if len(string) <= 1:
return True
if String[0] == String[len(string) - 1]:
return isPalindrome(string[1: len(string) - 1])
else:
return False
# Q.3
# Modify your function to work with sentences, ignoring punctuation and capitalization.
# For instance, these should be detected as palindromes:
#
# Eva, Can I Stab Bats In A Cave?
# A Man, A Plan, A Canal-Panama!
import string
def isPalindrome
whitelist = set(string.ascii_lowercase)
s = s.lower
s = ''.join(([char for char in s if char in whitelist])
return s = s[::-1]
revstring = mystring[::-1]
if (mysrtring == revstring):
print("its a palindrome")
else:
# Q.4
# if tuples are immutable, why does this work?
mytuple = (1, 2, 'abc', ['x', 'y'])
mytuple[3].append('z')
mytuple
# (1, 2, 'abc', ['x', 'y', 'z'])
# But this does not work?
mytuple[3] = ['x', 'y', 'z']
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# TypeError: 'tuple' object does not support item assignment
# Q.5
# Write a function to find the longest number of consecutive appearances of a
# character in a string
# for example: 'fzccsawetaaafb' => (a, 3)
word = "foo"
count = 1
lenght = ""
for i in range(1, len(word)): # range(1, 3)
if word[i - 1] == word[i]: # word[3] <-- key error
count += 1
else:
length += word[i - 1] + "repeats +str(count)+", "
count = 1
length += ("and" + word[i] + "repeats" + str(count))
print(length)
b
"aabbbbbbccaaa"
("b", 6) < - output
if (cur_count > count)
count = cur_count;
res = str
# Q.6
# Write a function to swap the elements of one list with another, for examples:
#
# l1 = [1,2,3]
# l2 = ['a', 'b', 'c']
# swap_elements(l1, l2)
#
# l1 is now ['a', 'b', 'c']
# l2 is now [1,2,3]
def swap_elements(11, 12)
11, 12 = 12, 11
# Jon - output here:
>> > def swap_elements(l1, l2):
...
l1, l2 = l2, l1
...
>> > l1 = [1, 2, 3]
>> > l2 = ['a', 'b', 'c']
>> >
>> > swap_elements(l1, l2)
>> > l1
[1, 2, 3]
>> > l2
['a', 'b', 'c']
import dis
def swap1():
| true |
07969f835c57729793df401fc7e367e4e6d399a6 | dodieboy/Np_class | /PROG1_python/coursemology/Mission32-CaesarCipher.py | 1,288 | 4.71875 | 5 | #Programming I
####################################
# Mission 3.2 #
# Caesar Cipher #
####################################
#Background
#==========
#The encryption of a plaintext by Caesar Cipher is:
#En(Mi) = (Mi + n) mod 26
#Write a Python program that prompts user to enter a plaintext
#and displays the encrypted result using Caesar Cipher.
#Important Notes
#===============
#1) Comment out ALL input prompts before submitting.
#2) You MUST (at least) use the following variables:
# - plaintext
# - ciphertext
#START CODING FROM HERE
#======================
#Perform Encryption of given plaintext
def caesarEncrypt(plaintext, key):
#Code to do the conversion
ciphertext = ""
for i in range(len(plaintext)):
char = plaintext[i]
# Encrypt uppercase characters in plain text
if (char.isupper()):
ciphertext += chr((ord(char) + key-65) % 26 + 65)
# Encrypt lowercase characters in plain text
else:
ciphertext += chr((ord(char) + key - 97) % 26 + 97)
print(ciphertext) #Modify to display the encrypted result
return ciphertext #Do not remove this line
#Do not remove the next line
#caesarEncrypt(plaintext,key)
caesarEncrypt('HELLOWORLDTHESECRETISOUT',5) | true |
03396cc7b38b7a779ca33d376a6ccb33720289b0 | dodieboy/Np_class | /PROG1_python/coursemology/Mission72-Matrix.py | 1,081 | 4.25 | 4 | #Programming I
#######################
# Mission 7.1 #
# MartrixMultiply #
#######################
#Background
#==========
#Tom has studied about creating 3D games and wanted
#to write a function to multiply 2 matrices.
#Define a function MaxtrixMulti() function with 2 parameters.
#Both parameters are in a matrix format.
#Important Notes
#===============
#1) Comment out ALL input prompts before submitting.
A = [[1,2,3],
[4,5,6],
[7,8,9]]
B = [[2,0,0],
[0,2,0],
[0,0,2]]
#START CODING FROM HERE
#======================
#Create your function here
def matrixmulti(A, B):
result = [[0,0,0],
[0,0,0],
[0,0,0]]
for i in range(len(A)):
# iterate through columns of Y
for j in range(len(B[0])):
# iterate through rows of Y
for k in range(len(B)):
result[i][j] += A[i][k] * B[k][j]
print(result)
return result
#Do not remove the next line
matrixmulti(A, B)
#3) For testing, print out the output
# - Comment out before submitting
| true |
c3ba57ea7ad83b5819851bafb7e88d62cd267c8d | jason-neal/Euler | /Completed Problems/Problem 5-smallest_multiple.py | 641 | 4.15625 | 4 | """Smallest multiple
Problem 5
2520 is the smallest number that can be divided by each of the numbers from 1 to
10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers
from 1 to 20?
"""
import numpy as np
def smallest_multiple(n):
"""Smallest multiple of numbers 1 thru n."""
numbers = np.arange(n) + 1
num = n
while True:
if np.all(num % numbers):
return num
else:
num += 1
assert smallest_multiple(10) == 2520
prob_num = 20
sm = smallest_multiple(prob_num)
print("Smallest multiple of 1 thru {} = {}".format(prob_num, sm))
| true |
cbc97978dbafa655d385b6741d6c046cb648cff4 | stevalang/Coding-Lessons | /SoftUni/Python Developmen/Python-Basics/4_Conditional_Statements/fruit_or_vegitable.py | 386 | 4.34375 | 4 | product_name = input()
if product_name == 'banana' or product_name == 'apple' or product_name == 'kiwi' or product_name == 'cherry' or \
product_name == 'lemon' or product_name == 'grapes':
print('fruit')
elif product_name == 'tomato' or product_name == 'cucumber' or product_name == 'pepper' or product_name == 'carrot':
print('vegetable')
else:
print('unknown')
| true |
0569f8f4243c3694a236fd8daf00171893d8666c | stevalang/Coding-Lessons | /SoftUni/Python Developmen/Python-Fundamentals/03_Basic_Syntax_Conditions_Loops/maximum_multiple.py | 397 | 4.1875 | 4 | '''
Given a Divisor and a Bound, find the largest integer N, such that:
N is divisible by divisor
N is less than or equal to bound
N is greater than 0.
Notes: The divisor and bound are only positive values. It's guaranteed that a divisor is found
'''
divisor = int(input())
bound = int(input())
max_num = 0
for i in range(1, bound+1):
if i % divisor == 0:
max_num = i
print(max_num)
| true |
5b3145219fbf8802f747d84079e0c4ca2099a4a8 | stevalang/Coding-Lessons | /SoftUni/Python Developmen/Python-Basics/4_Conditional_Statements/number_100_200.py | 587 | 4.15625 | 4 | """
Conditional Statements - Lab
Check: https://judge.softuni.bg/Contests/Practice/Index/1012#0
06. Number 100 ... 200
Condition:
Write a program that reads an integer entered by the user and checks if it is below 100,
between 100 and 200 or over 200. Print messages accordingly, as in the examples below:
Sample input and output
entrance exit entrance exit entrance exit
95 Less than 100 120 Between 100 and 200 210 Greater than 200
"""
num = int(input())
if num < 100:
print('Less than 100')
elif num <= 200:
print('Between 100 and 200')
else:
print('Greater than 200')
| true |
fc8c286f691360c9b96b4c91fa3fabeccade2aac | stevalang/Coding-Lessons | /SoftUni/Python Developmen/Python-Fundamentals/04_Lists/bread_factory.py | 2,805 | 4.3125 | 4 | """
As a young baker, you are baking the bread out of the bakery.
You have initial energy 100 and initial coins 100. You will be given a string, representing the working day events. Each event is separated with '|' (vertical bar): "event1|event2|event3…"
Each event contains event name or item and a number, separated by dash("{event/ingredient}-{number}")
If the event is "rest": you gain energy, the number in the second part. But your energy cannot exceed your initial energy (100). Print: "You gained {0} energy.".
After that, print your current energy: "Current energy: {0}.".
If the event is "order": You've earned some coins, the number in the second part. Each time you get an order, your energy decreases with 30 points.
If you have energy to complete the order, print: "You earned {0} coins.".
If your energy drops below 0, you skip the order and gain 50 energy points. Print: "You had to rest!".
In any other case you are having an ingredient, you have to buy. The second part of the event, contains the coins you have to spent and remove from your coins.
If you are not bankrupt (coins <= 0) you've bought the ingredient successfully, and you should print ("You bought {ingredient}.")
If you went bankrupt, print "Closed! Cannot afford {ingredient}." and your bakery rush is over.
If you managed to handle all events through the day, print on the next three lines:
"Day completed!", "Coins: {coins}", "Energy: {energy}".
Input / Constraints
You receive a string, representing the working day events, separated with '|' (vertical bar): " event1|event2|event3…".
Each event contains event name or ingredient and a number, separated by dash("{event/ingredient}-{number}")
Output
Print the corresponding messages, described above.
"""
events = input().split('|')
energy = 100
coins = 100
is_closed = False
for event in events:
args = event.split('-')
event_ingredient = args[0]
number = int(args[1])
if event_ingredient == 'rest':
temp = 0
if energy + number <= 100:
temp = number
energy += number
else:
temp = int(100 - energy)
energy = 100
print(f'You gained {temp} energy.')
print(f'Current energy: {energy}.')
elif event_ingredient == 'order':
if energy >= 30:
energy -= 30
coins += number
print(f'You earned {number} coins.')
else:
energy += 50
print("You had to rest!")
else:
if coins-number <= 0:
is_closed = True
break
else:
coins -= number
print(f'You bought {event_ingredient}.')
if is_closed:
print(f'Closed! Cannot afford {event_ingredient}.')
else:
print(f'Day completed!\nCoins: {coins}\nEnergy: {energy}')
| true |
b4bb635ae844e30f8fd58d64eeab5adda17726b2 | stevalang/Coding-Lessons | /SoftUni/Python Developmen/Python-Fundamentals/04_Lists/04.Search.py | 1,153 | 4.3125 | 4 | """
Lists Basics - Lab
Check your code: https://judge.softuni.bg/Contests/Practice/Index/1724#3
SUPyF2 Lists Basics Lab - 04. Search
Problem:
You will receive a number n and a word. On the next n lines you will be given some strings.
You have to add them in a list and print them.
After that you have to filter out only the strings that include the given word and print that list also.
Examples:
Input:
3
SoftUni
I study at SoftUni
I walk to work
I learn Python at SoftUni
Output:
['I study at SoftUni', 'I walk to work', 'I learn Python at SoftUni']
['I study at SoftUni', 'I learn Python at SoftUni']
Input:
4
tomatoes
I love tomatoes
I can eat tomatoes forever
I don't like apples
Yesterday I ate two tomatoes
Output:
['I love tomatoes', 'I can eat tomatoes forever', "I don't like apples", 'Yesterday I ate two tomatoes']
['I love tomatoes', 'I can eat tomatoes forever', 'Yesterday I ate two tomatoes']
"""
lines = int(input())
special_word = input()
my_list = []
special_list = []
for _ in range(lines):
word = input()
if special_word in word:
special_list.append(word)
my_list.append(word)
print(my_list)
print(special_list)
| true |
5fc56d9d02475b497d20988fbe8a244faec680e9 | stevalang/Coding-Lessons | /SoftUni/Python Developmen/Python-Basics/2_simple_calculations/Projects_Creation.py | 762 | 4.3125 | 4 | """
Simple Operations and Calculations - Lab
05. Creation Projects
Check: https://judge.softuni.bg/Contests/Compete/Index/1011#2
Write a program that calculates how many hours it will take an architect to design several
construction sites. The preparation of a project takes approximately three hours.
Entrance
2 lines are read from the console:
1. The name of the architect - text;
2. Number of projects - integer.
Exit
The following is printed on the console:
"The architect {architect's name} will need {hours needed} hours to complete {number of projects} project / s."
"""
name = input()
projects_count = int(input())
time_needed = int(projects_count*3)
print(f"The architect {name} will need {time_needed} hours to complete {projects_count} project/s.")
| true |
b0e20c859c4c65478d955ee75ec04bbf2c0a370a | stevalang/Coding-Lessons | /SoftUni/Python Developmen/Python-Fundamentals/04_Lists/number_filter.py | 1,173 | 4.1875 | 4 | """
Lists Basics - Lab
Check your code: https://judge.softuni.bg/Contests/Practice/Index/1724#4
SUPyF2 Lists Basics Lab - 05. Numbers Filter
Problem:
You will receive a single number n. On the next n lines you will receive integers.
After that you will be given one of the following commands:
• even
• odd
• negative
• positive
Filter all the numbers that fit in the category (0 counts as a positive). Finally, print the result.
Example:
Input:
5
33
19
-2
18
998
even
Output:
[19, -2, 18, 998]
Input:
3
111
-4
0
negative
Output:
[-4]
"""
n = int(input())
numbers = []
filtered = []
for i in range(n):
current_number = int(input())
numbers.append(current_number)
command = input()
if command == "even":
for number in numbers:
if number % 2 == 0:
filtered.append(number)
elif command == "odd":
for number in numbers:
if number % 2 != 0:
filtered.append(number)
elif command == "negative":
for number in numbers:
if number < 0:
filtered.append(number)
elif command == "positive":
for number in numbers:
if number >= 0:
filtered.append(number)
print(filtered)
| true |
eec96339c928ff8c2148957172c237c2cb015a2f | stevalang/Coding-Lessons | /SoftUni/Python Developmen/Python-Basics/2_simple_calculations/Fish_Tank.py | 582 | 4.1875 | 4 | # 1. Read input data and convert data types
lenght = int(input())
width = int(input())
height = int(input())
percent_stuff = float(input())
# 2. Calculating aquarium volume
acquarium_volume = lenght * width * height
#3. Convert volume (cm3) -> liters
volume_liters= acquarium_volume * 0.001
#4. Calculating litter taken from stuffs
volume_stuff = (volume_liters*percent_stuff)/100
#5. Calculating volume left
final_volume = volume_liters- volume_stuff
#4. Print and format
print(f'{final_volume:.3f}')
# a = 5
# b = 2
# result = a % b
# print(result)
# print(type(result)) | true |
73ca29ffb697d7e08b72cbc825a7a7672d989dd4 | happyandy2017/LeetCode | /Rotate Array.py | 2,287 | 4.1875 | 4 | # Rotate Array
# Go to Discuss
# Given an array, rotate the array to the right by k steps, where k is non-negative.
# Example 1:
# Input: [1,2,3,4,5,6,7] and k = 3
# Output: [5,6,7,1,2,3,4]
# Explanation:
# rotate 1 steps to the right: [7,1,2,3,4,5,6]
# rotate 2 steps to the right: [6,7,1,2,3,4,5]
# rotate 3 steps to the right: [5,6,7,1,2,3,4]
# Example 2:
# Input: [-1,-100,3,99] and k = 2
# Output: [3,99,-1,-100]
# Explanation:
# rotate 1 steps to the right: [99,-1,-100,3]
# rotate 2 steps to the right: [3,99,-1,-100]
# Note:
# Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
# Could you do it in-place with O(1) extra space?
class Solution:
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
N = len(nums)
k = k%N
if N==1 or k==0:
return
nums[:] = nums[-k:]+nums[:-k]
def rotate_2(self, nums, k):
N = len(nums)
k = k%N
if N==1 or k==0:
return
l=0 # number of swaps
i=0
j=(i+k)%N
while l<N-1:
if i == j:
i+=1
j=(i+k)%N
l+=1 # need to reduce by 1
temp = nums[i]
nums[i] = nums[j]
nums[j] = temp
j= (j+k)%N
l+=1
# for j in range(k):
# temp = nums[N-1]
# for i in range(N-2,-1, -1):
# nums[i+1]=nums[i]
# nums[0] = temp
# count = 0
# i = 0
# while count<N:
# i_next = i+k
# if i_next>=N:
# i_next = i_next%N
# temp = nums[i_next]
# nums[i_next]=nums[i]
# i=i_next+1
# else:
# temp = nums[i_next]
# nums[i_next]=nums[i]
# i=i_next
# count+=1
# return nums
import time
time1 = time.time()
nums = [1,2,3,4,5,6]
k = 6
Solution().rotate(nums, k)
print(nums)
print('time', time.time()-time1)
| true |
ab4b0424777999fbe22abb732279e9f3de3efeb3 | happyandy2017/LeetCode | /Target Sum.py | 2,048 | 4.125 | 4 | '''
Target Sum
Go to Discuss
You are given a list of non-negative integers, a1, a2, ..., an, and a target, S. Now you have 2 symbols + and -. For each integer, you should choose one from + and - as its new symbol.
Find out how many ways to assign symbols to make sum of integers equal to target S.
Example 1:
Input: nums is [1, 1, 1, 1, 1], S is 3.
Output: 5
Explanation:
-1+1+1+1+1 = 3
+1-1+1+1+1 = 3
+1+1-1+1+1 = 3
+1+1+1-1+1 = 3
+1+1+1+1-1 = 3
There are 5 ways to assign symbols to make the sum of nums be target 3.
Note:
The length of the given array is positive and will not exceed 20.
The sum of elements in the given array will not exceed 1000.
Your output answer is guaranteed to be fitted in a 32-bit integer.
'''
class Solution(object):
def findTargetSumWays(self, nums, S):
"""
:type nums: List[int]
:type S: int
:rtype: int
"""
# dynamic program
if not nums:
return 0
dict = {0:1}
for i in range(len(nums)):
# tdict = {}
import collections
tdict = collections.defaultdict(int)
for sum in dict: # 把相同的sum key的merge起来
# tdict[nums[i]+sum] = tdict.get(nums[i]+sum,0)+dict.get(sum,0)
# tdict[-nums[i]+sum] = tdict.get(-nums[i]+sum,0)+dict.get(sum,0)
tdict[sum+nums[i]] += dict[sum]
tdict[sum-nums[i]] += dict[sum]
dict = tdict
return dict.get(S,0)
# def findTargetSumWays_time_limit_exceed(self, nums, S):
# """
# :type nums: List[int]
# :type S: int
# :rtype: int
# """
# if not nums:
# return 0
# if len(nums)==1:
# if nums [0]== 0 and S == 0: # important, +-0 = 0, two ways
# return 2
# if nums[0]==S or -nums[0]==S:
# return 1
# return 0
# return self.findTargetSumWays(nums[1:], S-nums[0]) + self.findTargetSumWays(nums[1:], S+nums[0])
| true |
1e458d8bbd986b4b838f784b15ed9f6aaf5eccfc | mblue9/melb | /factorial.py | 928 | 4.1875 | 4 | import doctest
def factorial(n):
'''Given a number returns it's factorial e.g. factorial of 5 is 5*4*3*2*1
>>> factorial(0)
1
>>> factorial(1)
1
>>> factorial(3)
6
'''
if not type(n) == int:
raise Exception("Input to factorial() function must be an integer")
if n < 0:
raise Exception("Factorial for negative numbers is not defined")
total = 1
while n > 1:
total *= n
n -= 1
return total
def fibonacci(n):
'''Returns the Nth value in the Fibonacci
sequence
F(N) = F(N-1) + F(N-2)
F(0) = 0, F(1) = 1
>>> fibonacci(0)
0
>>> fibonacci(1)
1
>>> fibonacci(2)
1
>>> fibonacci(5)
5
'''
assert n >= 0
assert isinstance(n, int)
a, b = 0, 1
while n > 0:
a, b = b, a+b
n -= 1
return a
if __name__ == "__main__":
doctest.testmod()
| true |
a000ab576b9eefeb3be6565177102dea660a1b74 | TrafalgarSX/graduation_thesis_picture- | /lineChart.py | 678 | 4.4375 | 4 | import matplotlib.pyplot as pyplot
# x axis values
x = [1,2,3,4,5,6]
# corresponding y axis values
y = [2,4,1,5,2,6]
# plotting the points
pyplot.plot(x, y, color='green',linestyle='dashed', linewidth=3, marker='*',markerfacecolor='blue',markersize=12, label = "line 1")
x1 = [1,2,3]
y1 = [4,1,3]
# plotting the line 2 points
pyplot.plot(x1, y1, label = "line 2")
#setting x and y axis range
pyplot.ylim(0,9)
pyplot.xlim(0,9)
# naming the x axis
pyplot.xlabel('x -axis')
# naming the y axis
pyplot.ylabel('y -axis')
#giving a title to my graph
pyplot.title('Some cool customizations!')
#show a legend on the plot
pyplot.legend()
# function to show the plot
pyplot.show()
| true |
992e6ee0179e66863f052dce347c35e0d09b9138 | rowaxl/WAMD102 | /assignment/0525/factorial.py | 316 | 4.25 | 4 | def fact(number):
if number == 0:
return 1
if number == 1 or number == -1:
return number
if number > 0:
nextNum = number - 1
else:
nextNum = number + 1
return number * fact(nextNum)
number = int(input("Enter a number for calculate factorial: "))
print(f"{number}! = ", fact(number))
| true |
4b52d601646ac88a58de8e75d09481e65d758fa5 | seriousbee/ProgrammingCoursework | /src/main.py | 2,452 | 4.125 | 4 | def print_welcome_message():
print('Welcome to Split-it')
def print_menu_options():
menu_dict = {'About\t\t': '(A)', 'CreateProject\t': '(C)',
'Enter Votes\t': '(V)', 'Show Project\t': '(S)',
'Quit\t\t': '(Q)'}
for k, v in menu_dict.items():
print(f'{k} {v}') # not 100% what this f is but it doesn't work without it
print("Please choose an option and press <ENTER>:")
def is_int(text):
try:
int(text)
return True
except ValueError:
return False
def safe_int_input():
text = input()
if is_int(text):
return int(text)
print("Try again. Enter an integer number:")
safe_int_input()
def option_a():
print('\033[1m' + 'Option A: About Spliddit\n' + '\033[0m')
print("Hello. This is Spliddit. "
"I am an app that can help you share and distribute things with your friends and colleagues, "
"from grades to bills, to notes and good memories. "
"What would you like to split today? "
"You can decide that by personalizing me in option C.")
input("\nPress <Enter> to return to the main menu: ")
def option_c():
print('\033[1m' + 'Option C: Creating a Project' + '\033[0m')
print("Enter the project name: ")
project_name = input() # value never used
students = [] # value never used
print("Enter the number of team members:")
number = safe_int_input()
while number <= 0:
print("The number must be positive:")
number = safe_int_input()
for i in range(number):
print("\t Enter the name of team member " + str(i+1) + ": ")
student = input()
students.append(student)
input("\nPress <Enter> to return to the main menu:\n ")
def get_menu_option_from_user(attempt=0):
if attempt == 0:
print_menu_options()
choice = input()
choice = choice.upper()
if choice == "A":
option_a()
get_menu_option_from_user(0)
elif choice == "Q":
exit(0)
elif choice == "V":
get_menu_option_from_user(0)
elif choice == "S":
get_menu_option_from_user(0)
elif choice == "C":
option_c()
get_menu_option_from_user(0)
else:
print("\n Please choose only options from the menu above: ")
get_menu_option_from_user(1)
def main():
print_welcome_message()
get_menu_option_from_user()
if __name__ == '__main__':
main()
| true |
be4579851af7ea20e3ed8cfeeeb0e493426273c4 | mayankkuthar/GCI2018_Practice_1 | /name.py | 239 | 4.28125 | 4 | y = str(input(" Name "))
print("Hello {}, please to meet you!".format(y))
def reverse(s):
str = ""
for i in s:
str = i + str
return str
s = y
print ("Did you know that your name backwards is {}?".format(reverse(s))) | true |
72bbfab5a298cda46d02758aae824188c0703f8c | josan5193/CyberSecurityCapstone | /CapstoneMain.py | 859 | 4.1875 | 4 | def main():
while True:
Test1Word = input("What's your name?: ")
try:
Test1Num = int(input("Please choose one of three presidential candidates: \n 1. Donald Trump \n 2. Joe Biden \n 3. Bernie Sanders \n"))
if Test1Num >= 1 and Test1Num <= 3:
print("Congratulations," , Test1Word, ", you have voted!")
else:
print("Please choose a valid option between 1 and 3, or this session will be closed\n\n")
Test1Num = int(input("Please choose one of three presidential candidates: \n 1. Donald Trump \n 2. Joe Biden \n 3. Bernie Sanders \n"))
if Test1Num >= 1 and Test1Num <= 3:
print("Congratulations, You have voted")
else:
print("This session will close. Please ask election staff for assistance")
except ValueError:
print("Error! This is not a number. This session will close. Please ask election staff for assistance \n\n")
break
main() | true |
49d2f9a2183b3fc93c29d450ae3e84923ceefea8 | python-packages/decs | /decs/testing.py | 907 | 4.4375 | 4 | import functools
def repeat(times):
"""
Decorated function will be executed `times` times.
Warnings:
Can be applied only for function with no return value.
Otherwise the return value will be lost.
Examples:
This decorator primary purpose is to repeat execution of some test function multiple times:
import random
@repeat(10)
def test_int_is_taken():
examples = list(range(10)
assert type(random.choice(examples)) == int, 'Error!'
# No error, test is repeated 10 times.
Args:
times(int): required number of times for the function to be repeated.
Returns:
None
"""
def repeat_helper(func):
@functools.wraps(func)
def call_helper(*args):
for i in range(times):
func(*args)
return call_helper
return repeat_helper
| true |
9279ba88a2f2fd3f7f3a5e908362cb0b0449c97d | KendallWeihe/Artificial-Intelligence | /prog1/main[Conflict].py | 1,477 | 4.15625 | 4 | #Psuedocode:
#take user input of number of moves
#call moves ()
#recursively call moves() until defined number is reached
#call main function
import pdb
import numpy as np
#specifications:
#a 0 means end of tube
#1 means empty
red_tube = np.empty(6)
red_tube[:] = 2
green_tube = np.empty(5)
green_tube[:] = 3
yellow_tube = np.empty(4)
yellow_tube[:] = 4
blue_tube = np.empty(3)
blue_tube[:] = 5
white_tube = np.empty(2)
white_tube[:] = 6
black_tube = np.empty(1)
black_tube[:] = 7
pdb.set_trace()
solved_puzzle = np.empty((12,6))
solved_puzzle[12:12,10:12,8:12,6:12,4:12,2:12] = 0.0
solved_puzzle[6:12,5:10,4:8,3:6,2:4,1:2] = 1.0
pdb.set_trace()
def main():
#function is called by move() after k moves has been reached
print
def move(num_moves, num_moves_left, puzzle):
#make recursive move
#check for whether or not move has reached defined number of moves
#else make random move (out of the three)
#then recursively call move()
#finally call solver function
#after each recursive call, move() needs to check if the user wants to undo another move
#if rotate, calculate size of new arrays, generate new arrays, and fill with necessary elements
#if tube is cut in half, move balls past threshold value into new array
#if flip, reorder all arrays in reverse
print
k = input("Please enter the number of moves to shuffle the puzzle: ")
print "Number of moves = " + str(k)
moves(k,k,empty_puzzle)
| true |
cc315e7aa80c04128721d665deb4c1eadf081d8f | YaqoobAslam/Python3 | /Assignment/Count and display the number of lines not starting with alphabet 'A' present in a text file STORY2.TXT.py | 863 | 4.53125 | 5 | Write a function in to count and display the number of lines not starting with alphabet 'A' present in a text file "STORY.TXT".
Example:
If the file "STORY.TXT" contains the following lines,
The rose is red.
A girl is playing there.
There is a playground.
An aeroplane is in the sky.
Numbers are not allowed in the password.
def func():
Count = 0
fread = open('STORY2.TXT','r')
for line in fread:
lines = line
if lines.startswith('A'):
continue
Count +=1
print(lines)
print("Number of lines is:",Count)
func()
output:
The rose is red.
A girl is playing there.
There is a playground.
An aeroplane is in the sky.
Numbers are not allowed in the password.
Number of lines is: 5
----------------------------------------
The rose is red.
There is a playground.
Numbers are not allowed in the password.
Number of lines is: 3 | true |
2e54f9ee0938beb93b9caa2c5417bf60a8870e2d | pasinducmb/Python-Learning-Material | /Genarator Expressions.py | 811 | 4.1875 | 4 | # Generator Expressions
from sys import getsizeof
# Comprehension for Lists and Tuples
value = [(x + 1)**2 for x in range(10)]
print("List: ", value)
value = ((x + 1)**2 for x in range(10))
print("Tuple: ", value)
# (reason for error is due to tuples are not coprehendible objects as Lists, sets and dictionaries, therefore generator objects)
# Use Case: when infinite number of data is present which could take more memory for operating
# Comprehension for Tuples (defining generator objects)
value = ((x + 1)**2 for x in range(10))
for x in value:
print("Gen: ", x)
# Size Comparison between Lists and Gen Objects
value = ((x + 1)**2 for x in range(1000000))
print("Gen Size:", getsizeof(value), "Bytes")
value = [(x + 1)**2 for x in range(1000000)]
print("List Size:", getsizeof(value), "Bytes")
| true |
f15f1cc97586bb5fc23b23499328542f93204ea5 | wobedi/algorithms-and-data-structures | /src/implementations/sorting/quicksort.py | 1,074 | 4.15625 | 4 | from random import shuffle
from src.implementations.sorting.basic_sorts import insertion_sort
from src.implementations.helpers.partition import three_way_partition
def quicksort(arr: list) -> list:
"""Sorts arr in-place
by implementing https://en.wikipedia.org/wiki/Quicksort
"""
shuffle(arr) # shuffling in O(N) to avoid O(N2) edge case
return _quicksort(arr, lower=0, upper=len(arr)-1)
def _quicksort(arr: list, lower: int, upper: int) -> list:
"""Recursive implementation of quicksort"""
if upper <= lower:
return
if upper - lower < 10:
# Optimizing performance by using insertion sort for small sub arrays
insertion_sort(arr)
else:
lt, gt = three_way_partition(arr, lower, upper)
_quicksort(arr, lower, lt-1)
_quicksort(arr, gt+1, upper)
return arr
if __name__ == '__main__':
keys = [1, 2, 3, 10, 34, 22, 14, 21, 0]
keys_sorted = sorted(keys)
quick_sorted = quicksort(keys)
print(f'Quicksort output: {quick_sorted}')
assert quick_sorted == keys_sorted
| true |
55e3ac37f644ea67052a1c21aea38dac9b2e7b52 | EcoFiendly/CMEECourseWork | /Week2/Code/test_control_flow.py | 1,387 | 4.15625 | 4 | #!/usr/bin/env python3
"""
Some functions exemplifying the use of control statements
"""
__appname__ = '[test_control_flow.py]'
__author__ = 'Yewshen Lim (y.lim20@imperial.ac.uk)'
__version__ = '0.0.1'
__license__ = "License for this code/program"
## Imports ##
import sys # module to interface our program with the operating system
import doctest # import the doctest module
## Constants ##
## Functions ##
def even_or_odd(x=0): # if not specified, x should take value 0
"""
Find whether a number x is even or odd.
>>> even_or_odd(10)
'10 is Even!'
>>> even_or_odd(5)
'5 is Odd!'
whenever a float is provided, then the closest integer is used:
>>> even_or_odd(3.2)
'3 is Odd!'
in case of negative numbers, the positive is taken:
>>> even_or_odd(-2)
'-2 is Even!'
"""
# Define function to be tested
if x % 2 == 0: # the conditional if
return "%d is Even!" % x
return "%d is Odd!" % x
def main(argv):
"""
Prints each of the function with given argument
"""
print(even_or_odd(22))
print(even_or_odd(33))
return 0
if (__name__ == "__main__"):
status = main(sys.argv)
# sys.exit(status)
# Can suppress the block of code containing def main() and if
# (__name__ == "__main__") because you don't want/need to unit test that section
# of the output
doctest.testmod() # To run with embedded tests | true |
5c96975d02b72a1519f58eb440f497c617f64b9f | hebertmello/pythonWhizlabs | /project1.py | 581 | 4.15625 | 4 | import random
print ("Number guessing game")
number = random.randint(1, 20)
chances = 0
print("Guess a number between 1 and 20")
while(chances < 5):
guess = int(input())
if (guess == number):
print("Congratulations you won!!!")
break
elif guess < number:
print("Your guess is low and kindly select a higuer number", guess)
else:
print("Your guess is high and kindly select a lower number", guess)
chances = chances + 1
else:
if not chances < 5:
print("You lose!! The number is", number) | true |
8383a43b540f04be1f3e20a85017c9f42fe4e13c | ugant2/python-snippate | /pract/string.py | 1,664 | 4.3125 | 4 | # Write a Python function to get a string made of the first 2
# and the last 2 chars from a given a string. If the string
# length is less than 2, return instead of the empty string.
def string_end(s):
if len(s)<2:
return ' '
return len(s[0:2]) + len(s[-2:])
print(string_end('laugh out'))
# Write a Python program to change a given string to a new string
# where the first and last chars have been exchanged.
# def change_string(s):
#
# for i in s:
# d = s[0:2]
# e = s[:-2]
# c = e + d
# return c
#
# print(change_string("Austrlia"))
def change_string(s):
return s[-1:] + s[1:2] + s[-2:-1] + s[:1]
print(change_string("abcd"))
#using lambda function
r = lambda s: s[-1:] + s[1:2] + s[-2:-1] + s[:1]
print(r("this"))
print("\n")
# Write a Python program to remove the characters which have odd index values of a given string
def remove_odd_char(c):
result = " "
for i in range(len(c)):
if i%2 == 0:
result += c[i]
return result
print(remove_odd_char("bcdef"))
print("\n")
# Write a Python script that takes input from the user and
# displays that input back in upper and lower cases.
def upperLower(t):
f = input("enter string: ")
return f.upper()*2, f.lower()
#return t.upper(), t.lower()
result = upperLower(2)
print(result)
#print(upperLower("can ydou discover mystery in book..."))
#using lambda function
upperLowerCase = lambda c: (c.upper(), c.lower())
print(upperLowerCase("i shoot for the moon but i am too busy gazin stars"))
print(upperLowerCase("udai lagyo panxi(bird) ley nadi tira, dana deya dhana ghatdina vancan bhakta kabira"))
| true |
75a068175dd23bd786319ab2df60e61aee8dbfa1 | ugant2/python-snippate | /oop/inheritance Animal.py | 651 | 4.34375 | 4 |
# Inheritance provides a way to share functionality between classes.
# Imagine several classes, Cat, Dog, Rabbit and so on. Although they may
# differ in some ways (only Dog might have the method bark),
# they are likely to be similar in others (all having the attributes color and name).
class Animal:
def __init__(self, name, color):
self.name = name
self.color = color
# class Cat, Animla is a supar class
class Cat(Animal):
def purr(self):
print("Purr...")
# class Dog
class Dog(Animal):
def bark(self):
print("Woof!")
#objects
fido = Dog("Fido", "Brown")
print(fido.color, fido.name)
fido.bark() | true |
a8af418b9cff8cb6ee6da6dea287fbd6b8e9034c | mikhael-oo/honey-production-codecademy-project | /honey_production.py | 1,525 | 4.1875 | 4 | # analyze the honey production rate of the country
# import all necessary libraries
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn import linear_model
# import file into a dataframe
df = pd.read_csv("https://s3.amazonaws.com/codecademy-content/programs/data-science-path/linear_regression/honeyproduction.csv")
print(df.head())
# group into yearly average production
prod_per_year = df.groupby('year').totalprod.mean().reset_index()
# select the years
X = prod_per_year.year
X = X.values.reshape(-1, 1)
# select the yearly produce
y = prod_per_year.totalprod
# using Linear Regression to predict
regr = linear_model.LinearRegression()
regr.fit(X, y)
# getting the slope of the line
print(regr.coef_[0])
# getting the intercept of the line
print(regr.intercept_)
# get the predicted y values
y_predict = regr.predict(X)
# plot the data
plt.figure(figsize=(8,6))
plt.scatter(X, y, alpha=0.4)
plt.plot(X, y_predict)
plt.xlabel('Year')
plt.ylabel('Average Produce')
plt.title('Average Produce Per Year')
plt.show()
plt.clf()
# to predict rate of produce for coming years
# store the years into an array and rotate them
X_future = np.array(range(2013,2051))
X_future = X_future.reshape(-1, 1)
# future predictions of y_values
future_predict = regr.predict(X_future)
# plot the data
plt.plot(X_future, future_predict)
plt.title('Average Produce Per Year')
plt.xlabel('Year')
plt.ylabel('Average Produce')
plt.show()
| true |
7cabb3d44067c67d5ed50700fa3120ad2277053c | vgates/python_programs | /p010_fibonacci_series.py | 940 | 4.46875 | 4 | # Python program to print first n Fibonacci Numbers.
# The Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ...
# The sequence is characterized by the fact that every number after the
# first two is the sum of the two preceding ones.
# get the user input and store it in the variable n
# int function is used to convert the user input to integer
n = int( input("Enter the value for n: ") )
a = 0 # first fibonacci number
b = 1 # second fibonacci number
sum = 0 # sum of the two preceding ones
# Print first number, second number.
# Print should not end with a new line, instead it ends with a space
# since we need to print the sequence in the same line. Hence provided with end = " "
print( a, b, end = " ")
for i in range( 2, n ):
sum = a + b # add previous two numbers
a = b
b = sum
print(sum , end=" ")
print("") # just to print a new line when the sequence is complete | true |
4b2b1f3eb6ebadc10e0737b8affbfc0351d0e87d | vgates/python_programs | /p015_factorial.py | 1,015 | 4.34375 | 4 | # Python program to find factorial of a number
# Factorial of a number n is the multiplication of all
# integers smaller than or equal to n.
# Example: Factorial of 5 is 5x4x3x2x1 which is 120.
# Here we define a function for calculating the factorial.
# Note: Functions are the re-usable pieces of code which
# helps us to organize structure of the code.
# Python uses def keyword to start a function.
# Refer https://thepythonguru.com/python-functions/
def factorial( input_number ):
temp_factorial = 1
for i in range(1, input_number + 1):
temp_factorial = temp_factorial * i
return temp_factorial
# get the user input and store it in the variable input_number
# int function is used to convert the user input to integer
input_number = int( input("Enter the number: ") )
# call the factorial function which we have defined
calculated_factorial = factorial( input_number )
# Print
print("Factorial of {0} = {1}".format( input_number, calculated_factorial) )
| true |
fd73120ca7a5ac32608d0aec17003c45fb9198a0 | JazzyServices/jazzy | /built_ins/slices.py | 1,850 | 4.25 | 4 | # encoding=ascii
"""Demonstrate the use of a slice object in __getitem__.
If the `start` or `stop` members of a slice are strings, then look for
those strings within the phrase and make a substring using the offsets.
If `stop` is a string, include it in the returned substring.
This code is for demonstration purposes only.
It is not 100% correct.
For example, it does not support negative steps in a "natural" way.
"""
class Phrase:
"""Demonstrate custom __getitem__ taking a slice argument."""
def __init__(my, phrase: str):
"""Initialise with a string phrase."""
my.phrase = phrase
def __getitem__(my, item):
"""Get an item or a slice."""
if isinstance(item, slice):
return my._getslice(item)
return my.phrase[item]
def _getslice(my, sli):
start, stop, step = sli.start, sli.stop, sli.step
try:
# if start is a string, slice from there
if isinstance(start, str):
start = my.phrase.index(start)
# if stop is a string, slice to the end of it
if isinstance(stop, str):
stop = my.phrase.index(stop) + len(stop)
except ValueError:
return ''
return my.phrase[start:stop:step]
def main():
"""Demonstrate the Phrase class."""
phrase = Phrase('Now is the winter of our discontent.')
print(f'Integer subscription: [8]={phrase[8]} [-1]={phrase[-1]}')
print(f'Integer slicing: [7,10]={phrase[7:10]}')
print('Slicing using strings ...')
print(f"| from 'the' to 'of': ({phrase['the':'of']})")
print(f"| from 'the' to 'unfound': ({phrase['the':'unfound']})")
print(f"| upto the word 'winter': ({phrase[:'winter']})")
print(f"| from the word 'winter' onwards: ({phrase['winter':]})")
if __name__ == '__main__':
main()
| true |
12a5c1259f669055442de8ddfb7dfd6245e2bcbf | chagaleti332/HackerRank | /Practice/Python/Collections/namedtuple.py | 2,990 | 4.59375 | 5 | """
Question:
Basically, namedtuples are easy to create, lightweight object types.
They turn tuples into convenient containers for simple tasks.
With namedtuples, you don’t have to use integer indices for accessing members of
a tuple.
Example:
Code 01
>>> from collections import namedtuple
>>> Point = namedtuple('Point','x,y')
>>> pt1 = Point(1,2)
>>> pt2 = Point(3,4)
>>> dot_product = ( pt1.x * pt2.x ) +( pt1.y * pt2.y )
>>> print dot_product
11
Code 02
>>> from collections import namedtuple
>>> Car = namedtuple('Car','Price Mileage Colour Class')
>>> xyz = Car(Price = 100000, Mileage = 30, Colour = 'Cyan', Class = 'Y')
>>> print xyz
Car(Price=100000, Mileage=30, Colour='Cyan', Class='Y')
>>> print xyz.Class
Y
Task:
Dr. John Wesley has a spreadsheet containing a list of student's IDs, marks,
class and name.
Your task is to help Dr. Wesley calculate the average marks of the students.
Sum of all marks
Average = ------------------
Total students
Note:
1. Columns can be in any order. IDs, marks, class and name can be written in
any order in the spreadsheet.
2. Column names are ID, MARKS, CLASS and NAME. (The spelling and case type
of these names won't change.)
Input Format:
* The first line contains an integer n, the total number of students.
* The second line contains the names of the columns in any order.
* The next lines contains the marks, IDs, name and class, under their
respective column names.
Constraints:
* 0 <= N <= 100
Output Format:
Print the average marks of the list corrected to 2 decimal places.
Sample Input:
TESTCASE 01
5
ID MARKS NAME CLASS
1 97 Raymond 7
2 50 Steven 4
3 91 Adrian 9
4 72 Stewart 5
5 80 Peter 6
TESTCASE 02
5
MARKS CLASS NAME ID
92 2 Calum 1
82 5 Scott 2
94 2 Jason 3
55 8 Glenn 4
82 2 Fergus 5
Sample Output:
TESTCASE 01
78.00
TESTCASE 02
81.00
Explanation:
TESTCASE 01
Average = (97 + 50 + 91 + 72 + 80)/5
Can you solve this challenge in 4 lines of code or less?
NOTE: There is no penalty for solutions that are correct but have more than 4 lines.
"""
# Solution:
# Enter your code here. Read input from STDIN. Print output to STDOUT
from collections import namedtuple
if __name__ == '__main__':
no_of_students = int(input())
Student = namedtuple('Student', input().strip())
total_marks = sum([int(Student(*input().strip().split()).MARKS) for _ in
range(no_of_students)])
print('{:02f}'.format(total_marks / no_of_students))
| true |
24a0e80c3f81577f00b5b2096e4b32992914db5e | chagaleti332/HackerRank | /Practice/Python/Math/integers_come_in_all_sizes.py | 960 | 4.4375 | 4 | """
Question:
Integers in Python can be as big as the bytes in your machine's memory. There is
no limit in size as there is: 2^31 - 1(c++ int) or 2^63 - 1(C++ long long int).
As we know, the result of a^b grows really fast with increasing b.
Let's do some calculations on very large integers.
Task:
Read four numbers, a, b, c, and d, and print the result of a^b + c^d.
Input Format:
Integers a, b, c, and d are given on four separate lines, respectively.
Constraints:
* 1 <= a <= 1000
* 1 <= b <= 1000
* 1 <= c <= 1000
* 1 <= d <= 1000
Output Format:
Print the result of a^b + c^d on one line.
Sample Input:
9
29
7
27
Sample Output:
4710194409608608369201743232
Note: This result is bigger than 2^63 -1. Hence, it won't fit in the long
long int of C++ or a 64-bit integer.
"""
# Solution:
a = int(input())
b = int(input())
c = int(input())
d = int(input())
print(pow(a, b) + pow(c, d))
| true |
56049a2b6eaef72e1d4381a7f76a1d4cb9800912 | chagaleti332/HackerRank | /Practice/Python/Introduction/python_print.py | 441 | 4.4375 | 4 | """
Question:
Read an integer N.
Without using any string methods, try to print the following:
123....N
Note that "" represents the values in between.
Input Format:
The first line contains an integer N.
Output Format:
Output the answer as explained in the task.
Sample Input:
3
Sample Output:
123
"""
# Solution:
if __name__ == '__main__':
n = int(input())
for i in range(1, n + 1):
print(i, end='')
| true |
08605343a771a0837e3383972c370a03516db4aa | chagaleti332/HackerRank | /Practice/Python/Sets/set_add.py | 1,440 | 4.5625 | 5 | """
Question:
If we want to add a single element to an existing set, we can use the .add()
operation.
It adds the element to the set and returns 'None'.
Example
>>> s = set('HackerRank')
>>> s.add('H')
>>> print s
set(['a', 'c', 'e', 'H', 'k', 'n', 'r', 'R'])
>>> print s.add('HackerRank')
None
>>> print s
set(['a', 'c', 'e', 'HackerRank', 'H', 'k', 'n', 'r', 'R'])
Task:
Apply your knowledge of the .add() operation to help your friend Rupal.
Rupal has a huge collection of country stamps. She decided to count the
total number of distinct country stamps in her collection. She asked for
your help. You pick the stamps one by one from a stack of country stamps.
Find the total number of distinct country stamps.
Input Format:
The first line contains an integer N, the total number of country stamps.
The next N lines contains the name of the country where the stamp is from.
Constraints:
* 0 < N < 1000
Output Format:
Output the total number of distinct country stamps on a single line.
Sample Input:
7
UK
China
USA
France
New Zealand
UK
France
Sample Output:
5
Explanation:
UK and France repeat twice. Hence, the total number of distinct country
stamps is 5 (five).
"""
# Solution:
if __name__ == '__main__':
n = int(input())
s = set()
for _ in range(n):
s.add(input())
print(len(s))
| true |
59e25fa8a6649f0d23deaa9fe33e4df78f674c03 | chagaleti332/HackerRank | /Practice/Python/Introduction/python_loops.py | 458 | 4.1875 | 4 | """
Question:
Task
Read an integer N. For all non-negative integers i < N, print i^2. See the
sample for details.
Input Format:
The first and only line contains the integer, N.
Constraints:
* 1 <= N <= 20
Output Format:
Print N lines, one corresponding to each .
Sample Input:
5
Sample Output:
0
1
4
9
16
"""
# Solution:
if __name__ == '__main__':
n = int(input())
for i in range(n):
print(i ** 2)
| true |
2d0beaf86a1f65715dbdacdcf07aec623856b6cb | chagaleti332/HackerRank | /Practice/Python/Sets/the_captains_room.py | 1,570 | 4.15625 | 4 | """
Question:
Mr. Anant Asankhya is the manager at the INFINITE hotel. The hotel has an
infinite amount of rooms.
One fine day, a finite number of tourists come to stay at the hotel.
The tourists consist of:
→ A Captain.
→ An unknown group of families consisting of K members per group where K ≠ 1.
The Captain was given a separate room, and the rest were given one room per
group.
Mr. Anant has an unordered list of randomly arranged room entries. The list
consists of the room numbers for all of the tourists. The room numbers will
appear times per group except for the Captain's room.
Mr. Anant needs you to help him find the Captain's room number.
The total number of tourists or the total number of groups of families is not
known to you.
You only know the value of K and the room number list.
Input Format:
* The first line consists of an integer, K, the size of each group.
* The second line contains the unordered elements of the room number list.
Constraints:
* 1 < K < 1000
Output Format:
Output the Captain's room number.
Sample Input:
5
1 2 3 6 5 4 4 2 5 3 6 1 6 5 3 2 4 1 2 5 1 4 3 6 8 4 3 1 5 6 2
Sample Output:
8
Explanation:
The list of room numbers contains 31 elements. Since K is 5, there must be 6
groups of families. In the given list, all of the numbers repeat 5 times
except for room number 8.
Hence, 8 is the Captain's room number.
"""
# Solution:
k = int(input())
room_nos = list(map(int, input().strip().split()))
rooms = set(room_nos)
print((sum(rooms) * k - sum(room_nos)) // (k - 1))
| true |
4735407294bd47ed69477087a1f628d3426d0cfb | chagaleti332/HackerRank | /Practice/Python/RegexAndParsing/group_groups_groupdict.py | 2,019 | 4.4375 | 4 | """
Question:
* group()
A group() expression returns one or more subgroups of the match.
Code
>>> import re
>>> m = re.match(r'(\w+)@(\w+)\.(\w+)','username@hackerrank.com')
>>> m.group(0) # The entire match
'username@hackerrank.com'
>>> m.group(1) # The first parenthesized subgroup.
'username'
>>> m.group(2) # The second parenthesized subgroup.
'hackerrank'
>>> m.group(3) # The third parenthesized subgroup.
'com'
>>> m.group(1,2,3) # Multiple arguments give us a tuple.
('username', 'hackerrank', 'com')
* groups()
A groups() expression returns a tuple containing all the subgroups of the
match.
Code
>>> import re
>>> m = re.match(r'(\w+)@(\w+)\.(\w+)','username@hackerrank.com')
>>> m.groups()
('username', 'hackerrank', 'com')
* groupdict()
A groupdict() expression returns a dictionary containing all the named
subgroups of the match, keyed by the subgroup name.
Code
>>> m = re.match(r'(?P<user>\w+)@(?P<website>\w+)\.(?P<extension>\w+)',
'myname@hackerrank.com')
>>> m.groupdict()
{'website': 'hackerrank', 'user': 'myname', 'extension': 'com'}
Task
You are given a string S.
Your task is to find the first occurrence of an alphanumeric character in
S(read from left to right) that has consecutive repetitions.
Input Format:
A single line of input containing the string S.
Constraints:
0 < len(S) < 100
Output Format:
Print the first occurrence of the repeating character. If there are no
repeating characters, print -1.
Sample Input:
..12345678910111213141516171820212223
Sample Output:
1
Explanation:
.. is the first repeating character, but it is not alphanumeric.
1 is the first (from left to right) alphanumeric repeating character of the
string in the substring 111.
"""
# Solution:
# Enter your code here. Read input from STDIN. Print output to STDOUT
import re
string = input()
ans = re.search(r'([^\W_])\1+', string)
print(ans.group(1) if ans else -1)
| true |
6ab8e6e334434326b8d52145366e35ac535e8dd9 | chagaleti332/HackerRank | /Practice/Python/BasicDataTypes/lists.py | 1,968 | 4.34375 | 4 | """
Question:
Consider a list (list = []). You can perform the following commands:
* insert i e: Insert integer e at position i.
* print: Print the list.
* remove e: Delete the first occurrence of integer e.
* append e: Insert integer e at the end of the list.
* sort: Sort the list.
* pop: Pop the last element from the list.
* reverse: Reverse the list.
Initialize your list and read in the value of n followed by n lines of commands
where each command will be of the 7 types listed above. Iterate through each
command in order and perform the corresponding operation on your list.
Input Format:
The first line contains an integer, n, denoting the number of commands.
Each line i of the n subsequent lines contains one of the commands described
above.
Constraints:
* The elements added to the list must be integers.
Output Format:
For each command of type print, print the list on a new line.
Sample Input:
12
insert 0 5
insert 1 10
insert 0 6
print
remove 6
append 9
append 1
sort
print
pop
reverse
print
Sample Output:
[6, 5, 10]
[1, 5, 9, 10]
[9, 5, 1]
"""
# Solution:
ACTION = 0
if __name__ == '__main__':
N = int(input())
dlist = []
for _ in range(N):
command = input().strip().split()
if command[ACTION] == 'insert':
position, data = int(command[1]), int(command[2])
dlist.insert(position, data)
elif command[ACTION] == 'remove':
data = int(command[1])
dlist.remove(data)
elif command[ACTION] == 'print':
print(dlist)
elif command[ACTION] == 'reverse':
dlist.reverse()
elif command[ACTION] == 'sort':
dlist = sorted(dlist)
elif command[ACTION] == 'append':
data = int(command[1])
dlist.append(data)
elif command[ACTION] == 'pop':
dlist.pop()
| true |
162cd5c5c636f39d116bb3b928b70ce60f1bf25c | khidmike/learning | /Python/caesar.py | 849 | 4.21875 | 4 | # Simple program using a Caesar Cipher to encode / decode text strings
import sys
def main():
print("Welcome to the Caesar Cipher Encoder / Decoder")
print()
coding = str(input("What would you like to do? Type 'e' to encode / 'd' to decode: "))
if (coding != "e") and (coding != "d"):
print("I'm sorry... I don't understand what you want me to do")
sys.exit()
key = int(input("What is the key you would like to use? Type a number 1-25: "))
text = list(str(input("What is the text you would like to encode: ")))
result = []
if coding == "e":
for char in text:
result.append(chr(ord(char) + key))
elif coding == "d":
for char in text:
result.append(chr(ord(char) - key))
print("Your result is: ")
print()
print("".join(result))
main()
| true |
bf45447e0c258970584c89c445b40d7d84193812 | kmenon89/python-practice | /whileloopchallenge.py | 613 | 4.53125 | 5 | #get the line length ,angle,pen color from user and keep drawing until they give length as 0
#import turtle to draw
import turtle
# declare variables
len=1
angle=0
pcolour="black"
#use while loop
while len != 0 :
#get input from user about length angle and pen colour
len=int(input("welcome to sketch /n please enter the length of the line you want to sketch:"))
angle=int(input("please give the angle of the line to be drawn:"))
pcolour=input("please eneter the color of pen you want to use:")
turtle.color(pcolour)
turtle.right(angle)
turtle.forward(len)
| true |
679a164e1ffe6086681b2ec1c990633cadb673ba | kmenon89/python-practice | /fibonacci.py | 929 | 4.1875 | 4 | #fibinacci series
a=0
b=1
#n=int(input("please give the number of fibonacci sequence to be generated:"))
n=int(input("please give the maximum number for fibonacci sequence to be generated:"))
series=[]
series.append(a)
series.append(b)
length=len(series)-1
print(length,series[length])
while len(series)<n:#--> comment when print fibonacci for a number lesser than equal to given number
#while series[length]<=n: #-->uncomment when print fibonacci for a number lesser than equal to given number
x=len(series)
print(x)
n1=series[x-1]+series[x-2]
#if n1<=n : #--> uncomment when print fibonacci for a number lesser than equal to given number
if len(series)<n:#--> comment when print fibonacci for a number lesser than equal to given number
series.append(n1)
print(series)
length=len(series)-1
else:
break
print(series)
| true |
d2015bc58d2c72e4d91ea716ba2cc6cf05f064ec | bartkim0426/deliberate-practice | /exercises4programmers/ch03_operations/python/07_rectangle.py | 1,462 | 4.375 | 4 | '''
pseudocode
get_length_and_width
length: int = int(input("What is the length of the room in feet? "))
width: int = int(input("What is the width of the room in feet? "))
end
calculate_feet_to_meter
squre_meter: float = round(square_feet * 0.09290304, 3)
end
calculate_squre_feet
squre_feet = length * width
end
main
length, width = get_length_and_width()
squre_feet = calculate_squre_feet(length, width)
squre_meter = calculate_feet_to_meter(squre_feet)
print_out result
end
'''
SQUARE_METER = 0
def get_length_and_width() -> tuple:
'''get length and width from std input'''
length: int = int(input("What is the length of the room in feet? "))
width: int = int(input("What is the width of the room in feet? "))
return length, width
def calculate_feet_to_meter(square_feet: int) -> float:
square_meter: float = round(square_feet * 0.09290304, 3)
return square_meter
def calculate_square(length: int, width: int) -> int:
return length * width
def rectangle_squre():
'''calculate rectangle square from feet into meter'''
length, width = get_length_and_width()
square_feet = calculate_square(length, width)
global SQUARE_METER
SQUARE_METER = calculate_feet_to_meter(square_feet)
print(f'''You entered dimensions of {length} feet by {width} feet
The area is
{square_feet} square feet
{SQUARE_METER} square meters''')
if __name__ == '__main__':
rectangle_squre()
| true |
beadb79ce6c4df356833bf50da1c989b1f18bbb0 | hanyunxuan/leetcode | /766. Toeplitz Matrix.py | 884 | 4.5 | 4 | """
A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same element.
Now given an M x N matrix, return True if and only if the matrix is Toeplitz.
Example 1:
Input:
matrix = [
[1,2,3,4],
[5,1,2,3],
[9,5,1,2]
]
Output: True
Explanation:
In the above grid, the diagonals are:
"[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]".
In each diagonal all elements are the same, so the answer is True.
Example 2:
Input:
matrix = [
[1,2],
[2,2]
]
Output: False
Explanation:
The diagonal "[1, 2]" has different elements.
"""
# my solution
matrix = [
[1,2,3,4],
[5,1,2,3],
[9,5,1,2]
]
numrows=len(matrix)
numcols=len(matrix[0])
for i in range(numrows-1):
for j in range(numcols-1):
if matrix[i][j] != matrix[i+1][j+1]:
a=1
# amazing solution
all(matrix[row+1][1:] == matrix[row][:-1] for row in range(len(matrix)-1)) | true |
e77bbe516fc274f1e9cd3c8614f614ccfd4ab490 | Raushan117/Python | /014_Append_Mode.py | 827 | 4.5 | 4 | # Reference: https://automatetheboringstuff.com/chapter8/
# Writing in plaintext mode and appending in plaintext mode
# Passing a 'w' or 'a' in the second arugment of open()
# If the file does not exist, both argument will create a new file
# But remember to close them before reading the file again.
# About:
# Creating a simple program that ask user for filename (with extension)
# and then create this file and write the message to the file.
import os
filename = input('Please enter the filename: ')
information = input('What do you want to write? ')
currentDir = os.getcwd()
# Create a file with the name defined by user
# If it is the same file, you can keep writing to it :)
newFile = open(os.path.join(currentDir, filename), 'a')
newFile.write(information)
newFile.close()
print(filename + ' is created. Thanks!')
| true |
6beca592164142ea3b6381ec9185b4791ca208ad | sagsh018/Python_project | /18_Tuple_unpacking_with_python_function.py | 2,410 | 4.625 | 5 | # in this lecture we are going to learn more about function, and returning multiple items from function using tuple
# unpacking
# Suppose we want to write a function, which takes in a list of tuples having name of employee and number of hrs worked
# We have to decide who is the employee of the month based number of hours employee worked. so highest number of hours
# more chances of wining.
# notice that we need to return the name of the employee who worked the most(in short employee of the month along with
# number of hours he worked
my_list = [('vivek', 200), ('sahil', 300), ('ramya', 500)]
print(my_list)
# [('vivek', 200), ('sahil', 300), ('ramya', 500)]
def emp_of_month(my_list):
for item in my_list:
print(item)
emp_of_month(my_list)
# ('vivek', 200)
# ('sahil', 300)
# ('ramya', 500)
# Now lets tuple unpacking into consideration
def emp_of_month(my_list):
for emp, hrs in my_list:
print(f'{emp} worked for {hrs} this month')
emp_of_month(my_list)
# vivek worked for 200 this month
# sahil worked for 300 this month
# ramya worked for 500 this month
# now lets write a function who worked for maximum hours in office for the month
def emp_of_month(my_list):
hours = 0
employee = ''
for emp, hrs in my_list:
if hrs > hours:
hours = hrs
employee = emp
else:
pass
return employee, hours
no_of_emp = int(input('Please enter how many employees do you have : '))
x = 1
my_list = []
while x <= no_of_emp:
emp_name = input('Enter emp name : ')
hours_detail = int(input('Enter his hours details : '))
my_list.append((emp_name, hours_detail))
x += 1
print(f'Employees detail you have entered : {my_list}')
choice = input('Is the information entered by you correct (yes/no) : ')
if choice == 'yes':
name, hour = emp_of_month(my_list) # So here we are doing tuple unpacking with what is returned by a function
print(f'Employee of the month is {name} and he worked for {hour} hours')
else:
print('Thanks for entering the details but you choose to discontinue')
# Notice that we did tuple unpacking here inside the function definition as well as while calling it.
# but during calling function, if you are not sure how many values does function returns, then its always a better
# option to store the function value first into single variable and then explore that first.
| true |
4b31604397b17724d8a249c691a7828d0c07719c | sagsh018/Python_project | /9_Logical_Operators.py | 1,242 | 4.78125 | 5 | # In This lecture we are going to learn how to chain the comparison operators we have learnt in the previous lecture
# We can chain the comparison operator with the help of below listed logical operators
# and
# or
# not
# Suppose we want to do two comparisons
print(1 < 2)
# True
print(2 < 3)
# True
# another way of doing them in same line is
print(1 < 2 < 3)
# True
# Now this is returning true because it is checking whether 1 is less than 2 and also whether 2 is less than 3
print(1 < 2 > 3)
# False, as second condition failed
# This same thing can be done with logical operator "and"
print((1 < 2) and (2 < 3))
# True
print((1 < 2) and (2 > 3))
# False
# Also we can do the same in case of character and string with all the comparison operators
print(('h' == 'h') and (2 == 2))
# Ture
# So basically and logical operator follows below concept
# T and T = T
# T and F = F
# F and T = F
# F and F = F
# or
# ===
print((1 < 2) or (2 < 3))
# True
print((1 < 2) or (3 < 2))
# True
print((2 < 1) or (2 < 3))
# True
print((2 > 3) or (4 < 3))
# False
# or follows below rules
# T or T = T
# T or F = T
# F or T = T
# F or F = F
# not
# ====
print(1 == 1)
# True
print(not 1 == 1)
# False
# not follows below rules
# not T = F
# not F = T
| true |
acb345bad9c7a7be1c51586ca0587931d864b99b | sagsh018/Python_project | /14_List_comprehensions_in_python.py | 2,803 | 4.84375 | 5 | # List comprehensions are unique way of quickly creating list in python
# if you find yourself creating the list with for loop and append(). list comprehensions are better choice
my_list = []
print(my_list)
# [], so we have an empty list
for item in range(1, 10):
my_list.append(item)
print(my_list)
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
# another example with this method
my_list = []
for letter in 'hello':
my_list.append(letter)
print(f'created list is : {my_list}')
# created list is : ['h', 'e', 'l', 'l', 'o']
# So the better way of doing this is with the help of list comprehensions
my_string = 'something'
my_list = [letter for letter in my_string]
print(my_list)
# ['s', 'o', 'm', 'e', 't', 'h', 'i', 'n', 'g']
# So here we have basically flattened down our for loop.
# another example
my_list = [x for x in 'word']
print(my_list)
# ['w', 'o', 'r', 'd']
my_word = input('Enter the word you want list to be created for : ')
print(f'The list created for the word you entered : {[x for x in my_word]}')
# Enter the word you want list to be created for : sagar
# The list created for the word you entered : ['s', 'a', 'g', 'a', 'r']
# Also lets try to flatten the for loop for our first example
my_list = []
print(my_list)
# [], so we have an empty list
for item in range(1, 10):
my_list.append(item)
print(my_list)
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
my_list = [num for num in range(1, 10)]
print(my_list)
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
# we can even perform operations in this method
# to print double of numbers in range from 1 to 10
my_list = [num*2 for num in range(1, 10)]
print(my_list)
# [2, 4, 6, 8, 10, 12, 14, 16, 18]
# To print square of numbers in range from 1 to 10
print([num**2 for num in range(1, 10)])
# [1, 4, 9, 16, 25, 36, 49, 64, 81]
# To print only even numbers from range 1 to 10
print([num for num in range(1, 10) if num%2 == 0])
# [2, 4, 6, 8]
# To print square of even numbers
print([num**2 for num in range(1, 10) if num%2 == 0])
# [4, 16, 36, 64]
# Suppose we have temperature in Celsius and we want to convert it into Fahrenheit
Celsius = [0, 10, 20, 30, 40]
fahrenheit = [((9/5)*temp + 32) for temp in Celsius]
print(fahrenheit)
# [32.0, 50.0, 68.0, 86.0, 104.0]
# we can not only do if statements in list comprehensions but we can also do the if and ele both
# but this change the order of statement a little bit
my_list = [x if x%2 == 0 else 'Odd' for x in range(1, 10)]
print(my_list)
my_list = []
# Now lets consider the example of nested loops
for x in [1, 2, 3]:
for y in [10, 100, 1000]:
my_list.append(x*y)
print(my_list)
# [10, 100, 1000, 20, 200, 2000, 30, 300, 3000]
# Lets try to do this with list comprehension
my_list = [x*y for x in [1, 2, 3] for y in [10, 100, 1000]]
print(my_list)
[10, 100, 1000, 20, 200, 2000, 30, 300, 3000]
| true |
2e97e48539eaae2d4a43533487c5d263baa1e587 | sagsh018/Python_project | /12_While_loop_in_python.py | 1,948 | 4.4375 | 4 | # While loop will continue to execute a block of code while some condition remains true
# Syntax
# ===============================
# while some_boolean_condition:
# do something
# ===============================
# We can also combine while statement with the else statement
# ===============================
# while some_boolean_condition:
# do something
# else:
# So something else
# ===============================
# example
# =======
x = 0
while x < 5:
print(f'Value of x {x+1}th time is : {x}')
x += 1
else:
print(f'{x+1}th time x is not less than 5')
# Value of x 1th time is : 0
# Value of x 2th time is : 1
# Value of x 3th time is : 2
# Value of x 4th time is : 3
# Value of x 5th time is : 4
# 6th time x is not less than 5
# break, continue, pass
# ======================
# break : breaks out of the current closest enclosing loop
# continue : Goes to the top of the closest enclosing loop
# pass: does absolutely nothing
# pass
# ====
new_list = [1, 2, 3]
for item in new_list:
pass
# This will do nothing but it will not throw error because python do expect us to write something and we can't leave
# that blank. So this is a use of pass keyword. We often use it while declaring the functions. when we don't want
# to define whats goes inside the function immediately
# continue
# =========
for letter in 'sammy':
print(letter)
# s
# a
# m
# m
# y
# Suppose we don't want to print letter a in sammy, then we will use continue here
for letter in 'Sammy':
if letter == 'a':
continue
print(letter)
# S
# m
# m
# y
# break
# ======
# suppose we want to print letters of word sammy until letter a occurs
for letter in 'sammy':
if letter == 'a':
break
print(letter)
# s
# break is more useful with while loop. lets see the example of while loop along with break statement
x = 0
while x < 5:
if x == 2:
break
print(x)
x += 1
# 0
# 1
| true |
b67420e180277e8abd7908d95a410427a30373ea | homanate/python-projects | /fibonacci.py | 711 | 4.21875 | 4 | '''Function to return the first 1000 values of the fibonacci sequence using memoization'''
fibonacci_cache = {}
def fibonacci(n):
# check input is a positive int
if type(n) != int:
raise TypeError("n must be a positive int")
if n < 1:
raise ValueError("n must be a positive int")
# check for cached value, if found then return
if n in fibonacci_cache:
return fibonacci_cache[n]
# compute n
if n == 1:
value = 1
elif n == 2:
value = 2
elif n > 2:
value = fibonacci(n-1) + fibonacci(n-2)
# cache value and return
fibonacci_cache[n] = value
return value
for n in range(1, 1001):
print(n, ":", fibonacci(n))
| true |
a1c4e25c5608a1097f71d22db51a3b51aabcafaa | RadchenkoVlada/tasks_book | /python_for_everybody/task9_2.py | 1,098 | 4.3125 | 4 | """
Exercise 2:
Write a program that categorizes each mail message by which day of the week the commit was done.
To do this look for lines that start with “From”, then look for the third word and keep a running count of each of
the days of the week. At the end of the program print out the contents of your dictionary (order does not matter).
Sample Line:
From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
Sample Execution:
python dow.py
Enter a file name: mbox.txt
{'Fri': 20, 'Thu': 6, 'Sat': 1}
"""
def find_a_day(filename):
with open(filename, "r") as file:
dictionary = {}
# firstNlines = file.readlines()[0:100]
for line in file:
if line[:5] == "From ":
word_list = line.split()
day = word_list[2]
if day not in dictionary:
dictionary[day] = dictionary.get(day, 1)
else:
dictionary[day] = dictionary.get(day) + 1
return dictionary
if __name__ == '__main__':
# filename = input("Enter a file name: ")
print(find_a_day("mbox.txt"))
| true |
804ec370c29b1d0cafdae1cf1a2615abf4b3f766 | RadchenkoVlada/tasks_book | /python_for_everybody/task10_2.py | 1,521 | 4.3125 | 4 | """
Exercise 2:
This program counts the distribution of the hour of the day for each of the messages. You can pull the hour
from the “From” line by finding the time string and then splitting that string into parts using the colon character.
Once you have accumulated the counts for each hour, print out the counts, one per line, sorted by hour as shown below.
Sample Execution:
python timeofday.py
Enter a file name: mbox.txt
04 3
06 1
07 1
09 2
10 3
11 6
14 1
15 2
16 4
17 2
18 1
19 1
"""
def time_of_day(filename):
with open(filename, "r") as file:
dictionary = {}
for line in file:
if line[:5] == "From ":
word_list = line.split()
exact_time = word_list[5]
# s.find(), s.rfind(). They return the indices of the first and last occurrence of the required
# substring.
# If the substring is not found, the method returns the value -1.
hour = exact_time[:exact_time.find(":")]
if hour not in dictionary:
dictionary[hour] = dictionary.get(hour, 1)
else:
dictionary[hour] = dictionary.get(hour) + 1
t = list()
for key, val in dictionary.items():
t.append((key, val))
t.sort()
for key, val in t:
print(key, val)
if __name__ == '__main__':
filename = input("Enter a file name: ")
print(time_of_day(filename))
# print(time_of_day("data/mbox.txt")) | true |
86de60fccaa7393daa94e67f1e0e8c25e59f8e30 | RadchenkoVlada/tasks_book | /python_for_everybody/task7_2.py | 2,907 | 4.46875 | 4 | """
Exercise 2: Write a program to prompt for a file name, and then read through the file and look for lines of the form:
X-DSPAM-Confidence:0.8475
When you encounter a line that starts with “X-DSPAM-Confidence:”
pull apart the line to extract the floating-point number on the line.
Count these lines and then compute the total of the spam confidence values from these lines.
When you reach the end of the file, print out the average spam confidence.
Enter the file name: mbox.txt
Average spam confidence: 0.894128046745
Enter the file name: mbox.txt
Average spam confidence: 0.750718518519
Test your file on the mbox.txt and mbox_long.txt files.
Exercise 3: Sometimes when programmers get bored or want to have a bit of fun, they add a harmless Easter Egg to their
program Modify the program that prompts the user for the file name so that it prints a funny message when the user
types in the exact file name “na na boo boo”. The program should behave normally for all other files which exist and
don’t exist. Here is a sample execution of the program:
python egg.py
Enter the file name: mbox.txt
There were 1797 subject lines in mbox.txt
python egg.py
Enter the file name: missing.tyxt
File cannot be opened: missing.tyxt
python egg.py
Enter the file name: na na boo boo
NA NA BOO BOO TO YOU - You have been punk'd!
"""
def opening_file(name_file):
# how
if name_file == "na na boo boo": # a harmless Easter Egg
print("NA NA BOO BOO TO YOU - You have been punk'd!")
try:
with open(name_file, "r") as file:
count = 0
total_sum = 0
average = 0
for line in file:
line = line.rstrip()
if not line.startswith('X-DSPAM-Confidence:'):
continue
atpos = line.find(":")
after_pos = line[atpos + 1:]
number = float(after_pos) # can be this situation X-DSPAM-Confidence: 0.8475jj
total_sum += number
count += 1
average = total_sum / count
print("There is a match string", number)
print("Average spam confidence: ", average)
except FileNotFoundError:
print('File {0}'.format(name_file), "cannot be opened")
except ValueError:
print("Incorrect float value.")
except Exception as exception:
print('File {0}'.format(name_file))
print(exception)
if __name__ == '__main__':
# name_file = input("Enter a file name: ")
opening_file("mbox.txt")
"""
Correct answer:
Enter the file name: mbox.txt
Average spam confidence: 0.7507185185185187 ANSWER IN MY PROGRAM
Average spam confidence: 0.750718518519 ANSWER IN BOOK
Enter the file name: mbox_long.txt
Average spam confidence: 0.894128046745 ANSWER IN BOOK
Average spam confidence: 0.8941280467445736 ANSWER IN MY PROGRAM
"""
| true |
342ec86d210a77162b489c42d788703070c8a694 | nd955/CodingPractice | /HighestProductOfThree.py | 858 | 4.15625 | 4 | import math
def get_highest_product_of_three(input_integers):
highest_product_of_3 = 0
highest_product_of_2 = 0
highest_number = 0
lowest_product_of_2 = 0
lowest_number = 0
for i in range(len(input_integers)):
highest_product_of_3 = max(highest_product_of_3, highest_product_of_2 * input_integers[i])
highest_product_of_2 = max(highest_product_of_2, highest_number * input_integers[i])
highest_number = max(highest_number, input_integers[i])
lowest_product_of_2 = max(lowest_product_of_2, lowest_number * input_integers[i])
lowest_number = min(lowest_number, input_integers[i])
highest_product_of_3 = max(lowest_product_of_2 * highest_number, highest_product_of_3)
return highest_product_of_3
print(get_highest_product_of_three([1,1,-8,1,10,2,5,6,-7,-7])) | true |
486501ac24a31929fb1f621562a4f610de01c13c | green-fox-academy/fehersanyi | /python/dataStructures/l3.py | 533 | 4.125 | 4 | # Create a function called 'create_new_verbs()' which takes a list of verbs and a string as parameters
# The string shouldf be a preverb
# The function appends every verb to the preverb and returns the list of the new verbs
verbs = ["megy", "ver", "kapcsol", "rak", "nez"]
preverb = "be"
def create_new_verbs(preverb, verbs):
new_list = []
for words in verbs:
new_list.append(preverb + words)
return new_list
print(create_new_verbs(preverb, verbs))
# The output should be: "bemegy", "bever", "bekapcsol", "berak", "benez" | true |
5ec90b5061479057ab0be74166f7662897056973 | KyeCook/PythonStudyMaterials | /LyndaStudy/LearningPython/Chapter 3/time_delta_objects.py | 1,347 | 4.34375 | 4 | ######
#
#
# Introduction to time delta objects and how to use them
#
#
######
from datetime import date
from datetime import datetime
from datetime import time
from datetime import timedelta
def main():
# Constructs basic time delta and prints
print(timedelta(days=365, hours=5, minutes=1))
# print date
print("Date now is " + str(datetime.now()))
# print date in one year by adding 365days on with timedelta
print("Date in one year will be " + str(datetime.now() + timedelta(days=365)))
# Use timedelta that has more than one argument
print("Date in two weeks and 3 days will be : " + str(datetime.now() + timedelta(weeks=2, days=3)))
# Calculate time one week ago using timedelta and format
t = datetime.now() - timedelta(weeks=1)
s = t.strftime("%A %B %d, %Y")
print("One week ago it was " + s)
# ## Calculate How long it is until April fools day
today = date.today()
afd = date(today.year, 4, 1)
# Compare dates to see if it has already been.
# Use replace functin if it has
if(afd < today):
print("April fools day has already passed %d days ago" % ((today-afd).days))
afd = afd.replace(year=today.year+1)
time_to_afd = abs(afd - today)
print(time_to_afd.days, " days until next April Fools Day")
if __name__ == '__main__':
main() | true |
c73bbcb19f8fefe0c8ac9a03af30f84878398d34 | rafianathallah/modularizationsforum | /modnumber10.py | 395 | 4.125 | 4 | def pangramchecker(str):
alphabet = "abcdefghijklmnopqrstuvwxyz"
for characters in alphabet:
if characters not in str.lower():
return False
return True
sentence = str(input("Enter a sentence: "))
if(pangramchecker(sentence) == True):
print("This sentence is a pangram.")
else:
print("This sentence is not a pangram.")
| true |
e9c023d8afffb2b4d28954c7bc2ff4311c3e1a94 | Ryan149/Bioinformatics-Repository | /bioinformatics/coding/month.py | 705 | 4.15625 | 4 | name={}
name[0]="January"
name[1]="February"
name[2]="March"
name[3]="April"
name[4]="May"
name[5]="June"
name[6]="July"
name[7]="August"
name[8]="September"
name[9]="October"
name[10]="November"
name[11]="December"
def daysInMonth(month):
days = 30
if (month < 7):
if (month % 2 == 0):
days = 31
if (month == 1):
days = 28
else:
if (month % 2 == 1):
days = 31
return days
daysInYear=0
for i in range(0,12):
print "There are",daysInMonth(i),"days in",name[i]
daysInYear=daysInYear+daysInMonth(i)
print "There are",daysInYear,"days in a non-leap year"
| true |
87e82f31d1624d627eed4c122307fc3762165e75 | EdBali/Python-Datetime-module | /dates.py | 1,626 | 4.3125 | 4 | import datetime
import pytz
#-----------------SUMMARRY OF DATETIME module------------
#-------------The datetime module has 4 classes:
# datetime.date ---(year,month,date)
# datetime.time ---(hour,minute,second,microsecond)
# datetime.datetime ---(year,month,date,hour,minute,second,microsecond)
# datetime.timedelta ---this deals with duration in days,month,years,hour,minute,second,microsecond
#printing the current date
today = datetime.date.today()
print(today)
#printing my birthday
birthday = datetime.date(2000,12,18)
print(birthday)
#calculating number of days since birth
days_since_birth = (today - birthday).days
print(days_since_birth)
#Adding and subtracting days using timedelta
ten_days = datetime.timedelta(days = 10)
print(today + ten_days)
#How to get specifc day,month,weekday
print(datetime.date.today().month)
# print(datetime.date.today().day)
# print(datetime.date.today().weekday)
#Adding 10hours to current time
ten_hours = datetime.timedelta(hours = 10)
print(datetime.datetime.now() + ten_hours)
#Working with time zones..You have to pip install "pytz" module, then import it
datetime_day = datetime.datetime.now(tz = pytz.UTC)
datetime_pacific = datetime_day.astimezone(pytz.timezone('US/Pacific'))
print(datetime_pacific)
#Printing list of available timezones
# for tz in pytz.all_timezones:
# print(tz)
#String Formatting Dates
print(datetime_pacific.strftime('%B %d, %Y'))
#Turning a normal String date to a datetime object
datetime_object = datetime.datetime.strptime('March 09, 2010','%B %d, %Y')
print(datetime_object)
#NB: look for "MAYA" for easier manipulation of dates | true |
a1d69d9a43163882862a5460605a20086fc8f334 | marcemq/csdrill | /strings/substrInStr.py | 665 | 4.125 | 4 | # Check if a substring characters are contained in another string
# Example
# INPUT: T = ABCa, S = BDAECAa
# OUTPUT: ABCa IN BDAECAa
import sys
from utils import _setArgs
def checkSubstrInStr(substr, mystr):
frec = {key:0 for key in substr}
for key in substr:
frec[key] += 1
counter = len(frec)
for si in mystr:
if si in frec:
frec[si] -= 1
if frec[si] == 0:
counter -= 1
if counter == 0:
print("{} IN {}".format(substr, mystr))
else:
print("{} NOT IN {}".format(substr, mystr))
if __name__ == "__main__":
args = _setArgs()
checkSubstrInStr(args.T, args.S)
| true |
2a3c4c11d5fbcb16d69d2c18ebc3c0ef30d0b352 | PsychoPizzaFromMars/exercises | /intparser/intparser.py | 1,951 | 4.40625 | 4 | '''In this kata we want to convert a string into an integer. The strings simply represent the numbers in words.
Examples:
- "one" => 1
- "twenty" => 20
- "two hundred forty-six" => 246
- "seven hundred eighty-three thousand nine hundred and nineteen" => 783919
Additional Notes:
- The minimum number is "zero" (inclusively)
- The maximum number, which must be supported is 1 million (inclusively)
- The "and" in e.g. "one hundred and twenty-four" is optional, in some cases it's present and in others it's not
- All tested numbers are valid, you don't need to validate them '''
def parse_int(string):
target_number = 0
cur_number = 0
num_dict = {
'one': 1,
'two': 2,
'three': 3,
'four': 4,
'five': 5,
'six': 6,
'seven': 7,
'eight': 8,
'nine': 9,
'ten': 10,
'eleven': 11,
'twelve': 12,
'thirteen': 13,
'fourteen': 14,
'fifteen': 15,
'sixteen': 16,
'seventeen': 17,
'eighteen': 18,
'nineteen': 19,
'twenty': 20,
'thirty': 30,
'forty': 40,
'fifty': 50,
'sixty': 60,
'seventy': 70,
'eighty': 80,
'ninety': 90,
'hundred': 100,
'thousand': 1000,
'million': 1000000,
}
string = string.replace('-', ' ').replace(' and ', ' ').split()
for word in string:
if word == 'thousand' or word == 'million':
cur_number *= num_dict[word]
target_number += cur_number
cur_number = 0
elif word == 'hundred':
cur_number *= num_dict[word]
elif word == 'and':
pass
else:
cur_number += num_dict[word]
target_number += cur_number
return target_number
if __name__ == "__main__":
print(parse_int('seven hundred eighty-three thousand nine hundred and nineteen'))
| true |
80d2008455dc937de197802177241472e75c8f1a | Afnaan-Ahmed/GuessingGame-Python | /guessingGame.py | 1,036 | 4.4375 | 4 | import random
#Generate a random number and store it in a variable.
secret_number = random.randint(1,10)
#Initially, set the guess counter to zero, we can add to it later!
guess_count = 0
#set a limit on how many guesses the user can make.
guess_limit = 3
print('Guess a number between 1 and 10.')
#Do this so the program terminates after the set amount of guesses.
while guess_count < guess_limit:
guess = int(input('Guess: '))
#Ask for input and increment guess count by 1 so that our program doesn't loop infinately.
guess_count += 1
#Define the rules and conditions of the game.
if guess == secret_number:
print('Yay, you guessed right!, You Won!')
break
#Break it so it doesn't continue after the user wins the game.
elif guess < secret_number:
print("Your guess is too low.")
elif guess > secret_number:
print('Your guess is too high.')
else:
print("Invalid input! Terminating the program.")
else:
print('You hit the guess limit! You lose.') | true |
5dbb4db96d384b13f027ca6adba424dae8f8b7a0 | vishnupsingh523/python-learning-programs | /gratestofThree.py | 543 | 4.375 | 4 | # this program is to find the greatest of three numbers:
def maxofThree():
# taking the input of three numbers
x = int(input("A : "));
y = int(input("B : "));
z = int(input("C : "));
#performing the conditions here for finding the greatest
if x>y:
if x>z:
print(x," is the greatest")
else:
print(z," is the greatest")
elif y>z:
print(y, " is the greatest")
else:
print(z, " is the gretest")
# calling the maxofThree function here:
maxofThree()
| true |
3349311b8347f6eac17c3dfb9b87da5816f57e0c | eestey/PRG105-16.4-Using-a-function-instead-of-a-modifier | /16.4 Using a function instead of a modifier.py | 945 | 4.1875 | 4 | import copy
class Time(object):
""" represents the time of day.
attributes: hour, minute, second"""
time = Time()
time.hour = 8
time.minute = 25
time.second = 30
def increment(time, seconds):
print ("Original time was: %.2d:%.2d:%.2d"
% (time.hour, time.minute, time.second))
new_time = copy.deepcopy(time)
new_time.second += seconds
if new_time.second > 59:
quotient, remainder = divmod(new_time.second, 60)
new_time.minute += quotient
new_time.second = remainder
if new_time.minute > 59:
quotient, remainder = divmod(new_time.minute, 60)
new_time.hour += quotient
new_time.minute = remainder
if new_time.hour > 12:
new_time.hour -= 12
print "Plus %g seconds" % (seconds)
print ("New time is: %.2d:%.2d:%.2d"
% (new_time.hour, new_time.minute, new_time.second))
increment(time, 234)
| true |
302bee99dec0d511bda305ec8ba4bdc6fa028138 | Rossnkama/AdaLesson | /linear-regression.py | 1,181 | 4.25 | 4 | # Importing our libraries
import numpy as np
import matplotlib.pyplot as plt
# Our datasets
x_data = [1.0, 2.0, 3.0]
y_data = [2.0, 4.0, 6.0]
# Forward propagation in our computational graph
def feed_forward(x):
return x * w
# Loss function
def calculate_loss(x, y):
return (feed_forward(x) - y)**2
# To plot an error graph later
all_weights = []
all_mses = [] # Mean squared errors
# To loop though floats
for w in np.arange(0.0, 4.1, 0.1):
print('W=', w) # Show the weight
sum_of_all_loss = 0
for x, y in zip(x_data, y_data):
hypothesis_x = feed_forward(x) # This is our predicted y
loss = calculate_loss(x, y)
sum_of_all_loss += loss
print("x:", x)
print("y:", y)
print("Our hypothesis of x (y):", hypothesis_x)
print("Our loss/error squared for this weight {}:".format(w), loss)
print("")
print("MSE:", loss/3); print("")
print("-------------------------\n")
all_weights.append(w)
all_mses.append(loss/3)
# Plotting graph of how weights effect the loss
plt.title("Loss vs Weights")
plt.plot(all_weights, all_mses)
plt.ylabel('Loss')
plt.xlabel('Weights')
plt.show() | true |
9621fb0236eaf16068f246c7bc199679c51c24d2 | Snakanter/FunStuff | /rps.py | 1,832 | 4.1875 | 4 | #!/usr/bin/env python3
"""
File: rps.py
Name:
A rock-paper-scissors game against the CPU
Concepts covered: Random, IO, if/else, printing
"""
import random
import sys
import os
def main():
# Code here
print("READY FOR A GAME OF ROCK, PAPER, SCISSORS!?")
PlayerChoice = input("Choose between options by typing first letter. (R = Rock. P = Paper. S = Scissors.) ")
while ( PlayerChoice != "R" and PlayerChoice != "S" and PlayerChoice != "P" ):
PlayerChoice = input("Choose between options by typing first letter. (R = Rock. P = Paper. S = Scissors.) ")
choice = ai_guess(PlayerChoice)
checkWin(PlayerChoice, choice)
def ai_guess(PlayerChoice):
# Code here
#1 = rock 2 = paper 3 = scissors
choice = random.randint(1,3)
return choice
def checkWin(PlayerChoice, choice):
# Code here
if (PlayerChoice == "R") and (choice == 1):
print("It's a tie!")
elif (PlayerChoice == "R") and (choice == 2):
print("You lose!")
elif (PlayerChoice == "R") and (choice == 3):
print("You win!")
elif (PlayerChoice) == ("P") and (choice) == (1):
print("You win!")
elif (PlayerChoice) == ("P") and (choice) == (2):
print("It's a tie!")
elif (PlayerChoice) == ("P") and (choice) == (3):
print("You lose!")
elif (PlayerChoice) == ("S") and (choice) == (1):
print('You lose!')
elif (PlayerChoice) == ("S") and (choice) == (2):
print('You win!')
elif (PlayerChoice) == ("S") and (choice) == (3):
print("It's a tie!")
else:
print("")
if __name__ == "__main__":
main()
while True:
awnser = input("Would you like to try again?")
if awnser == "Yes":
os.system("cls")
main()
else:
break
| true |
52a19ec7a20ac94d87dd8d26a9492df110792804 | hsqStephenZhang/Fluent-python | /对象引用-可变性-垃圾回收/8.4函数的参数作为引用时2.py | 2,010 | 4.375 | 4 | """
不要使用可变类型作为函数的参数的默认值
"""
class HauntedBus(object):
def __init__(self, passengers=[]): # python会提醒,不要使用mutable value
self.passengers = passengers
def pick(self, name):
self.passengers.append(name)
def drop(self, name):
try:
self.passengers.remove(name)
except ValueError:
print("student not in the bus")
class TwilightBus(object):
def __init__(self, passengers=None): # python会提醒,不要使用mutable value
if passengers is None:
self.passengers = []
else:
self.passengers = list(passengers)
def pick(self, name):
self.passengers.append(name)
def drop(self, name):
try:
self.passengers.remove(name)
except ValueError:
print("student not in the bus")
def show1():
bus1 = HauntedBus(['Alice', 'Bill'])
bus1.pick('charlie')
bus1.drop("Alice")
bus2 = HauntedBus()
bus2.pick('Carrie')
bus3 = HauntedBus()
print(bus3.passengers)
bus3.pick('Dave')
print(bus2.passengers)
print(bus2.passengers is bus3.passengers)
"""
这里出现了灵异事件:bus3中的乘客出现在了bus2中,bus2中的乘客出现在了bus3中
这是因为没有指定初始乘客的bus会共享一个乘客列表
默认值是函数对象的属性,如果其是可变对象,则修改了之后对之后的所有的初始化默认值都会影响
"""
def show2():
team = list("abcde")
bus = TwilightBus(team)
"""
这里TwilightBus中的passengers共享了team这个list,应当使用team的副本
也就是将self.passengers=passengers 修改为 self.passengers=list(passengers)
这样该类中操作的就是team的副本,而其中的元素又是不可变的类型,所以不会对原参数影响
"""
bus.drop('a')
bus.drop('b')
print(team)
if __name__ == '__main__':
# show1()
show2()
| true |
7cc3efabd755c0aba8f2e650dfcf5a043b89b5c1 | baki6983/Python-Basics-to-Advanced | /Collections/Tuple.py | 328 | 4.46875 | 4 | #tuples are ordered and unchangable
fruitsTuples=("apple","banana","cherry")
print(fruitsTuples)
print(fruitsTuples[1])
# if you try to assign value to fruitsTuples[1] , it will change because its Unchangeable
# With DEL method you can completely List , but you cant item in the list
for i in fruitsTuples:
print(i)
| true |
6705d4095c282200d0c3f2ca1c7edfb15cdc7009 | akshayreddy/yahtzee | /yahtzee.py | 2,427 | 4.25 | 4 | '''
.) Programs creats a list of dices
.) ProbailityInfo is used to keep track of the positions of dices
which will be used to re rolled in future
.) probability contais the list of probanilities
'''
from decimal import Decimal
from random import randint
import sys
j,k=0,0
dices,ProbabilityInfo,probaility=[],[],[]
for i in range(3):
dices.append(int(sys.argv[i+1]))
def roll_one(x):
return (6-x)/float(6)
def roll_two(x,y):
return ((6-x)/float(6))*((6-y)/float(6))
def roll_three(x,y,z):
return (6-x)/float(6)*(6-y)/float(6)*(6-z)/float(6)
if dices[0]==dices[1]==dices[2]:
print "Its a yahtzee!!\nNo dice needs to be re-rolled\nScore:25"
exit()
else:
for i in range(3):
if dices[i]==dices[(i+1)%3]: #If two dices have same value
k=1
ProbabilityInfo.append([(i+2)%3])
probaility.append(roll_one(dices[(i+2)%3]))
ProbabilityInfo.append([(i+1)%3,(i+2)%3])
probaility.append(roll_two(dices[(i+1)%3],dices[(i+2)%3]))
ProbabilityInfo.append([i,(i+1)%3])
probaility.append(roll_two(dices[i],dices[(i+1)%3]))
ProbabilityInfo.append([i,(i+1)%3,(i+2)%3])
probaility.append(roll_three(dices[i],dices[(i+1)%3],dices[(i+2)%3]))
if k!=1:
for i in range(7):
if i<3:
ProbabilityInfo.append([i])
probaility.append(roll_one(dices[(i)]))
elif i<6:
ProbabilityInfo.append([j,(j+1)%3])
probaility.append(roll_two(dices[j],dices[(j+1)%3]))
j=j+1
else:
ProbabilityInfo.append([0,1,2])
probaility.append(roll_three(dices[0],dices[1],dices[2]))
for i in range(len(ProbabilityInfo)):
print "Position=%s Probability=%f"%(ProbabilityInfo[i],probaility[i])
MaxProbablityPosition=probaility.index(max(probaility))
if max(probaility)>0.33333333: # Setting a Threshold for probability
print "\n%d dice can be re-rolled\n"%len(ProbabilityInfo[MaxProbablityPosition])
for i in ProbabilityInfo[MaxProbablityPosition]:
print "dice number %d" % (i+1)
for i in ProbabilityInfo[MaxProbablityPosition]:
dices[i]=randint(0,6)
print "New Roll:%s"%(dices)
if dices[0]==dices[1]==dices[2]:
print "Its a yahtzee!!\nNo dice needs to be rolled\nScore:25"
else:
print "Score:%d" % (dices[0]+dices[1]+dices[2])
else:
print "\nRe rolling not required, less gain probability\n"
print "Score:%d" % (dices[0]+dices[1]+dices[2])
| true |
09fd2d4e77c3bb2ce2401f583a567c6351aaf2d7 | veryobinna/assessment | /D2_assessment/SOLID/good example/liskov_substitution.py | 1,345 | 4.125 | 4 | '''
Objects in a program should be replaceable with instances of their
base types without altering the correctness of that program.
I.e, subclass should be replaceable with its parent class
As we can see in the bad example, where a violation
of LSP may lead to an unexpected behaviour of sub-types. In our
example, "is-a" relation can not directly applied to `Person` and
`Prisoner`. The cause is that these two classes "behave" differently.
How to fix it? Maybe a better naming will do the trick:
'''
class FreeMan(object):
def __init__(self, position):
self.position = position
def walk_North(self, dist):
self.position[1] += dist
def walk_East(self, dist):
self.position[0] += dist
# "is-a" relationship no longer holds since a `Prisoner` is not a `FreeMan`.
class Prisoner(object):
PRISON_LOCATION = (3, 3)
def __init__(self):
self.position = type(self).PRISON_LOCATION
def main():
prisoner = Prisoner()
print "The prisoner trying to walk to north by 10 and east by -3."
try:
prisoner.walk_North(10)
prisoner.walk_East(-3)
except:
pass
print "The location of the prison: {}".format(prisoner.PRISON_LOCATION)
print "The current position of the prisoner: {}".format(prisoner.position)
if __name__ == "__main__":
main()
| true |
eeb4417e9f419a311fb639aeada768728c113f28 | tekichan/teach_kids_python | /lesson5/circle_pattern.py | 897 | 4.34375 | 4 | from turtle import *
bgcolor("green") # Define Background Color
pencolor("red") # Define the color of Pen, i.e our pattern's color
pensize(10) # Define the size of Pen, i.e. the width of our pattern's line
radius = 100 # Define the radius of each circle
turning_angle = 36 # Define how much the next circle turns away from the previous one.
# A counter of totally how much the angle is turned. It starts with zero.
total_turned_angle = 0
while total_turned_angle < 360:
# While loop, when the total angle is less than 360, i.e a round.
circle(radius) # Draw a circle
# Turn right after you finish a circle, to prepare the new position of the next circle.
right(turning_angle)
# Accumulate the turning angle into the counter
total_turned_angle = total_turned_angle + turning_angle
exitonclick() # Exit when you click the screen | true |
15e49688c27e8237138889efa46963ffa4775c91 | kenifranz/pylab | /popped.py | 309 | 4.28125 | 4 | # Imagine that the motorcycles in the list are stored in chronological order according to when we owned them.
# Write a pythonic program to simulate such a situation.
motorcycles = ['honda', 'yamaha','suzuki']
last_owned = motorcycles.pop()
print("The last motorcycle I last owned was "+ last_owned.title())
| true |
17f39a18c96ac3f6a3bb1646da4d01875b1889e6 | JaredColon-Rivera/The-Self-Taught-Programmer | /.Chapter-3/Challenge_4.py | 233 | 4.375 | 4 | x = 10
if x <= 10:
print("The number is less than or equal to 10!")
elif x > 10 and x <= 25:
print("The number is greater than equal to 10 but it is less than or equal to 25!")
elif x > 25:
print("The number is greater than 25!") | true |
d6bd643d0da7cfb11fd22a0d0b346171fba82b24 | sureshbvn/leetcode | /recursion/subset_sum.py | 952 | 4.25 | 4 | # Count number of subsets the will sum up to given target sum.
def subsets(subset, targetSum):
# The helper recursive function. Instead of passing a slate(subset), we are
# passing the remaining sum that we are interested in. This will reduce the
# overall complexity of problem from (2^n)*n to (2^n).
def helper(sum, index):
# Base condition. Only when we are at a leaf node, the subset is
# completely formed.
if index == len(subset):
# If sum reaches zero, this is equivalent to subset sum.
# In the slate world, we will have actual subset at this stage.
if sum == 0:
return 1
return 0
if sum < 0:
return 0
return helper(sum-subset[index], index+1) + helper(sum, index+1)
return helper(targetSum, 0)
count = subsets([1,2,3,4], 6)
print("The total number of subsets with target sum", count)
| true |
5d0d3522cee1193cb0765c366e7d5d73a583aab2 | pravinv1998/python_codeWithH | /newpac/read write file.py | 339 | 4.15625 | 4 |
def read_file(filename):
'''
'This function use only for read content
from file and display on command line'
'''
file_content = open(filename)
read_data = file_content.read()
file_content.close()
return read_data
n=read_file("name.txt")
print(n)
print(read_file.__doc__)
# read the content from file
| true |
bc4906e63fbb7278109151edfd73f7d06cc38630 | abalulu9/Sorting-Algorithms | /SelectionSort.py | 701 | 4.125 | 4 | # Implementation of the selection sorting algorithm
# Selection sort takes the smallest element of the vector, removes it and adds it to the end of the sorted vector
# Takes in a list of numbers and return a sorted list
def selectionSort(vector, ascending = True):
sortedVector = []
# While there are still elements in the vector
while len(vector) > 0:
# Find the smallest element in the vector
index = 0
for i in range(len(vector)):
if (vector[i] < vector[index] and ascending) or (vector[i] > vector[index] and not ascending):
index = i
# Remove the smallest element and add it to the end of the sorted vector
sortedVector.append(vector.pop(index))
return sortedVector
| true |
2f28f3c4f6c93913345c688e688662eb228879ed | stanislav-shulha/Python-Automate-the-Boring-Stuff | /Chapter 6/printTable.py | 997 | 4.46875 | 4 | #! python3
# printTable.py - Displays the contents of a list of lists of strings in a table format right justified
#List containing list of strings
#rows are downward
#columns are upward
tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
#Prints the list containing list containing strings
#table is the passed list
#numRows is the number of rows in table
#numCols is the number of columns in the table
def print_Table(table, numRows, numCols):
#For loop to get the widths for each column
#Widths stored in colWidths
max = 0
for list in tableData:
for item in list:
if len(item) > max:
max = len(item)
#Code used in a previous program (Chapter 4 - GridPicture) to do the display portion
line = ''
for r in range(numRows):
for c in range(numCols):
line += table[c][r].rjust(max)
print(line)
line = ''
#Test case
print_Table(tableData, len(tableData[0]), len(tableData)) | true |
96a3ec7334436703a69c3d4bd396eb3f99ca5bf2 | stanislav-shulha/Python-Automate-the-Boring-Stuff | /Chapter 4/CommaList.py | 733 | 4.59375 | 5 | #Sample program to display a list of values in comma separated format
#Function to print a given list in a comma separated format
#Takes a list to be printed in a comma separated format
def comma_List(passedList):
#Message to be printed to the console
message = ''
if len(passedList) == 0:
print('Empty List')
elif len(passedList) == 1:
print(passedList[0])
else:
#Loop through the list and add each element except for the last one to the message
for i in range(len(passedList) - 1):
message += passedList[i] + ', '
message += 'and ' + passedList[-1]
print(message)
#Testing cases
test = ['apples', 'bananas', 'tofu', 'cats']
comma_List(test)
test2 = []
comma_List(test2)
test3 = ['one']
comma_List(test3) | true |
2b7df14561403960fe975298193f7863d79d2987 | charlesumesi/ComplexNumbers | /ComplexNumbers_Multiply.py | 1,049 | 4.3125 | 4 | # -*- coding: utf-8 -*-
"""
Created on 16 Feb 2020
Name: ComplexNumbers_Multiply.py
Purpose: Can multiply an infinite number of complex numbers
@author: Charles Umesi (charlesumesi)
"""
import cmath
def multiply_complex():
# Compile one list of all numbers and complex numbers to be multiplied
a = int(input('How many numbers and complex numbers are you multiplying? : '))
b = "Enter one real and its corresponding imaginary part in the format R,I\n(for absent real or imaginary part, enter '0', as in R,0 or 0,I) : "
c = [list(input(b)) for _ in [0]*a]
# Tidy the list by converting to string and reconverting back to a list
d = []
for i in c:
e = ''.join(i)
d.append(e)
# Use concatenation to convert each item in the list to string complex
f = []
for i in d:
g = 'complex(' + i + ')'
f.append(g)
del(c, d)
# Convert the edited list to string proper and evaluate
return eval('*'.join(f))
print(multiply_complex())
| true |
007f176e9d38b1d07543cda8113ae468d31daa28 | andresjjn/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/4-print_square.py | 779 | 4.375 | 4 | #!/usr/bin/python3
""" Module Print square
This document have one module that prints a square with the character #.
Example:
>>> print_square(4)
####
####
####
####
"""
def print_square(size):
"""Add module.
Args:
size (int): The size length of the square.
Reises:
TypeError:
- If size is not an integer.
- If size is a float and is less than 0
ValueError:
-If size is less than 0.
"""
if type(size) == int:
if size >= 0:
pass
else:
raise ValueError("size must be >= 0")
else:
raise TypeError("size must be an integer")
for i in range(size):
for j in range(size):
print("#", end="")
print("")
| true |
e23a809a3a920c566aa857d70f684fc787381bbb | GbemiAyejuni/BubbleSort | /bubble sort.py | 828 | 4.28125 | 4 | sort_list = [] # empty list to store numbers to be sorted
list_size = int(input("Enter the size of list: ")) # variable to store size of list indicated by the user
for i in range(0, list_size):
number = int(input("Enter digit: "))
sort_list.append(number) # adds each number the user gives to sort_list
print("Unsorted List: ", sort_list)
for i in range(0, len(sort_list) - 1):
swapped = False # swapped initialized as false
for j in range(0, len(sort_list) - 1):
if sort_list[j] > sort_list[j + 1]:
sort_list[j], sort_list[j + 1] = sort_list[j + 1], sort_list[j]
swapped = True # sets swapped to true if swapping of numbers occurs in the iteration
if not swapped:
break
print("Sorted List: ", sort_list)
input('Press Enter to Exit...')
| true |
d9a69fbda9ed1346f9475dd255278948ae5038de | arifams/py_coursera_basic_ | /for_test2.py | 352 | 4.40625 | 4 | print("before, this is the total number")
numbers = 3,41,15,73,9,12,7,81,2,16
for number in numbers:
print(number)
print("now python try to find the largest number")
largest_so_far = 0
for number in numbers:
if number > largest_so_far:
largest_so_far = number
print(largest_so_far, number)
print("Now the current largest is", largest_so_far)
| true |
7b9e12083faf0278926f41cc4c60562e24332697 | lasupernova/book_inventory | /kg_to_PoundsOrOunces.py | 1,806 | 4.125 | 4 | from tkinter import *
#create window-object
window = Tk()
#create and add 1st-row widgets
#create label
Label(window, text="Kg").grid(row=0, column=0, columnspan=2)
#create function to pass to button as command
def kg_calculator():
# get kg value from e1
kg = e1_value.get()
# convert kg into desired units
gram = float(kg)*1000
lbs = float(kg)*2.20462
oz = float(kg)*35.274
#output calculated units into respective fields upon clicking b1
t1.delete("1.0", END) # Deletes the content of the Text box from start to END
t1.insert(END, f"{int(gram)}") # Fill in the text box with the value of gram variable
t2.delete("1.0", END)
t2.insert(END, f'{lbs:.2f}')
t3.delete("1.0", END)
t3.insert(END, f'{oz:.2f}')
#get text variable to pass to textvariable-parameter
e1_value=StringVar()
#create and add entry-widget
e1=Entry(window, textvariable=e1_value)
e1.grid(row=0, column=2, columnspan=2)
#create button-widget
b1 = Button(window, text="Convert", command=kg_calculator) #NOTE: do NOT pass () after function-name, as command is only referencing the function
#add button to specific window-Object location
b1.grid(row=0, column=4, columnspan=2)
#create and add second-row widgets
#create label
Label(window, text="g", justify=CENTER).grid(row=1, column=0)
#create and add text-widget1
t1=Text(window,height=1, width=20)
t1.grid(row=1,column=1)
#create label
Label(window, text="lb", justify=CENTER).grid(row=1, column=2)
#create and add text-widget2
t2=Text(window,height=1, width=20)
t2.grid(row=1,column=3)
#create label
Label(window, text="oz.", justify=CENTER).grid(row=1, column=4)
#create and add text-widget3
t3=Text(window,height=1, width=20)
t3.grid(row=1,column=5)
#shoudl always be at the end of Tkinter-code
window.mainloop() | true |
6e8d17c385229344a5ba7cfddfdc9679de7e09eb | jelaiadriell16/PythonProjects | /pset2-1.py | 736 | 4.1875 | 4 | print("Paying the Minimum\n")
balance = int(raw_input("Balance: "))
annualInterestRate = float(raw_input("Annual Interest Rate: "))
monthlyPaymentRate = float(raw_input("Monthly Payment Rate: "))
monIntRate = annualInterestRate/12.0
month = 1
totalPaid = 0
while month <= 12:
minPayment = monthlyPaymentRate * balance
monthBalance = balance - minPayment
remBalance = monthBalance + (monIntRate * monthBalance)
print("Month: %d" % month)
print("Minimum monthly payment: "), round(minPayment, 2)
print("Remaining balance: "), round(remBalance, 2)
balance = remBalance
month += 1
totalPaid += minPayment
print "Total paid: ", round(totalPaid, 2)
print "Remaining balance: ", round(balance, 2) | true |
ba3b85ec95dc22ecb4c91ada9c2f61512e5359ea | Gabe-flomo/Filtr | /GUI/test/tutorial_1.py | 1,950 | 4.34375 | 4 | from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow
import sys
''' tutorial 1: Basic gui setup'''
# when working with PyQt, the first thing we need to do when creating an app
# or a GUI is to define an application.
# we'll define a function named window that does this for us
def window():
# this is where we always have to start off
# passing in sys.argv sets up the configuration for the application
# so that it knows what OS its running on
app = QApplication(sys.argv)
# next we have to create some kind of widget/window that were actually going
# to show in our application (you can use QMainWindow or QWidget)
win = QMainWindow()
# set the size and title of our window by calling the setGeametry() method
# the arguments are the x position, y position, width, and height
# the x,y positions are where on your screen do you want the window to appear
# the width and height is the size of the window
xpos = 200
ypos = 200
width = 300
height = 300
win.setGeometry(xpos, ypos, width, height)
# next were going to set a window title which is what you will see in the
# status bar of the application.
win.setWindowTitle("Filtr")
# Displaying something in the window
# in this case its just going to be a basic label
# by passing in the window to the .QLabel() method were telling
# the label where we want it to appear, which is on the window.
label = QtWidgets.QLabel(win)
# this is how we make the label say something
label.setText("A Label")
# now we can tell the label to appear in the window by using the move() method
xlabel = 50
ylabel = 50
label.move(xlabel,ylabel)
# now to show the window we have to use the .show() method along with
# another line that basically makes sure that we exit when we close the window
win.show()
sys.exit(app.exec_())
window()
| true |
75f4e3cd2ccfe294c9940f3cc7332c3626dcb139 | Muhammad-Yousef/Data-Structures-and-Algorithms | /Stack/LinkedList-Based/Stack.py | 1,303 | 4.21875 | 4 | #Establishing Node
class Node:
def __init__(self):
self.data = None
self.Next = None
#Establishing The Stack
class Stack:
#Initialization
def __init__(self):
self.head = None
self.size = 0
#Check whether the Stack is Empty or not
def isEmpty(self):
return self.head == None
#Display The Stack
def display(self):
if self.isEmpty():
print("Stack is Empty!")
return
currentNode = self.head
while currentNode != None:
print("[{}]".format(currentNode.data))
currentNode = currentNode.Next
print()
#Peek
def peek(self):
if self.isEmpty():
print("Stack is Empty!")
return
print("{}".format(self.head.data))
print()
#Pushing
def push(self, x):
newNode = Node()
newNode.data = x
newNode.Next = self.head
self.head = newNode
self.size += 1
#Popping
def pop(self):
if self.isEmpty():
print("Stack is Empty!")
value = -1
else:
currentNode = self.head
self.head = currentNode.Next
value = currentNode.data
self.size -= 1
return value
| true |
43f674a715ad3f044bc2a5b406dc3b5edabe1323 | DoozyX/AI2016-2017 | /labs/lab1/p3/TableThirdRoot.py | 838 | 4.4375 | 4 | # -*- coding: utf-8 -*-
"""
Table of third root Problem 3
Create a table with third root so that the solution is a dictionary where the key is the integer and the value is the third root of the integer.
The keys should be numbers whose third root is also an integer between two values m and n.
or a given input, print out the third root if it is already calculated in the dictionary.
If the dictionary doesn't contain the value print out that there is no data.
After that print out the sorted list of the key-value pairs from the dictionary.
"""
if __name__ == "__main__":
m = input()
n = input()
x = input()
# your code here
tablica = {}
for i in range(m, n+1):
tablica[i*i*i] = i
if x in tablica:
print(tablica[x])
else:
print("nema podatoci")
print(sorted(tablica.items()))
| true |
dcdbd68cea46053d4c116d19d5ed64f0d26eca1f | obaodelana/cs50x | /pset6/mario/more/mario.py | 581 | 4.21875 | 4 | height = input("Height: ")
# Make sure height is a number ranging from 1 to 8
while (not height.isdigit() or int(height) not in range(1, 9)):
height = input("Height: ")
# Make range a number
height = int(height)
def PrintHashLine(num):
# Print height - num spaces
print(" " * int(height - num), end="")
# Print num amount of hashes
print("#" * num, end="")
# Print two spaces
print(" ", end="")
# Print num amount of hashes
print("#" * num, end="")
# Print a new line
print("")
for i in range(1, height + 1):
PrintHashLine(i) | true |
014130aa0b43faecfbb0737cb47bf66bbf6bd318 | carriekuhlman/calculator-2 | /calculator.py | 2,425 | 4.25 | 4 | """CLI application for a prefix-notation calculator."""
from arithmetic import (add, subtract, multiply, divide, square, cube,
power, mod, )
# loop for an input string
# if q --> quit
# otherwise: tokenize it
# look at first token
# do equation/math for whatever it corresponds to
# return as a float number
while True:
input_string = input("Write an equation > ")
tokens = input_string.split(' ')
valid_tokens = {"+": 3, "-": 3, "*": 3, "/": 3, "square": 2, "cube": 2, "pow": 3, "mod": 3}
if input_string == "q":
break
# elif tokens[0] not in valid_tokens:
# print("Invalid input")
elif len(tokens) != valid_tokens[tokens[0]]:
print("Invalid input")
# elif tokens[0] in valid_tokens:
# for i in range(1,len(tokens)):
# try:
# int(tokens[i])
# except:
# print("Input not valid.")
# break
for i in range(len(tokens)):
if i == 0:
if tokens[0] not in valid_tokens:
print("Invalid input.")
break
else:
try:
int(tokens[i])
except:
print("Input not valid")
break
else:
#create valid tokens list
#iterate through tokens (using range of len)
#if tokens[0] is not in our operator list
#print error message
#else:
#try to convert the passed string to integer
#exception would be a print statement with an error message
if tokens[0] == "+":
answer = (add(int(tokens[1]), int(tokens[2])))
elif tokens[0] == "-":
answer = (subtract(int(tokens[1]), int(tokens[2])))
elif tokens[0] == "*":
answer = (multiply(int(tokens[1]), int(tokens[2])))
elif tokens[0] == "/":
answer = (divide(int(tokens[1]), int(tokens[2])))
elif tokens[0] == "square":
answer = (square(int(tokens[1])))
elif tokens[0] == "cube":
answer = (cube(int(tokens[1])))
elif tokens[0] == "pow":
answer = (power(int(tokens[1]), int(tokens[2])))
elif tokens[0] == "mod":
answer = (mod(int(tokens[1]), int(tokens[2])))
print(float(answer))
| true |
61d8cb65ed02a9dbd905897290709080c49ba886 | benjiaming/leetcode | /validate_binary_search_tree.py | 1,596 | 4.15625 | 4 | """
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right subtrees must also be binary search trees.
Example 1:
2
/ \
1 3
Input: [2,1,3]
Output: true
Example 2:
5
/ \
1 4
/ \
3 6
Input: [5,1,4,null,null,3,6]
Output: false
Explanation: The root node's value is 5 but its right child's value is 4.
"""
#%%
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
return self.checkBST(root)
def checkBST(self, node, lower=float('-inf'), upper=float('inf')):
if not node:
return True
if node.val <= lower or node.val >= upper:
return False
if not self.checkBST(node.left, lower, node.val):
return False
if not self.checkBST(node.right, node.val, upper):
return False
return True
solution = Solution()
# 2
# / \
# 1 3
tree = TreeNode(2)
tree.left = TreeNode(1)
tree.right = TreeNode(3)
print(solution.isValidBST(tree)) # True
# 5
# / \
# 1 4
# / \
# 3 6
tree = TreeNode(5)
tree.left = TreeNode(1)
tree.right = TreeNode(4)
tree.right.left = TreeNode(3)
tree.right.right = TreeNode(6)
print(solution.isValidBST(tree)) # False
#%%
| true |
f7c50862b43c8c0386195cd4b01419c0ac6f7b21 | benjiaming/leetcode | /find_duplicate_subtrees.py | 1,636 | 4.125 | 4 | """
Given a binary tree, return all duplicate subtrees. For each kind of duplicate subtrees, you only need to return the root node of any one of them.
Two trees are duplicate if they have the same structure with same node values.
Example 1:
1
/ \
2 3
/ / \
4 2 4
/
4
The following are two duplicate subtrees:
2
/
4
and
4
Therefore, you need to return above trees' root in the form of a list.
"""
#%%
# Definition for a binary tree node.
from collections import Counter
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def __str__(self):
return str(self.val)
def __repr__(self):
return str(self.val)
class Solution(object):
def findDuplicateSubtrees(self, root):
result = []
freq = Counter()
def preorder_traversal(node):
if not node:
return '#'
path = [str(node.val)]
path.append(preorder_traversal(node.left))
path.append(preorder_traversal(node.right))
serialized = ','.join(path)
freq[serialized] += 1
if freq[serialized] == 2:
result.append(node)
return serialized
preorder_traversal(root)
return result
root = TreeNode(1)
root.left = TreeNode(2)
root.left.left = TreeNode(4)
root.right = TreeNode(3)
root.right.left = TreeNode(2)
root.right.left.left = TreeNode(4)
root.right.right = TreeNode(4)
solution = Solution()
print(solution.findDuplicateSubtrees(root))
| true |
f2d07b36bb42c0d8b1ec205cb3fa338d18719363 | benjiaming/leetcode | /rotate_image.py | 1,571 | 4.1875 | 4 | #!/bin/env python3
"""
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Note:
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
Example 1:
Given input matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],
rotate the input matrix in-place such that it becomes:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
Example 2:
Given input matrix =
[
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
],
rotate the input matrix in-place such that it becomes:
[
[15,13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7,10,11]
]
"""
#%%
from typing import List
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
Runs in O(n^2).
"""
lm = len(matrix)
if not lm or lm != len(matrix[0]):
return
for r in range(lm//2):
first = r
last = lm - 1 - r
for i in range(first, last):
offset = i - first
top = matrix[first][i]
matrix[first][i] = matrix[last-offset][first]
matrix[last-offset][first] = matrix[last][last-offset]
matrix[last][last-offset] = matrix[i][last]
matrix[i][last] = top
solution = Solution()
input = [
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
]
solution.rotate(input)
print(input)
#%%
| true |
b048988bbaa1a55c3010042e642d232d7e1e4698 | SDSS-Computing-Studies/004c-while-loops-hungrybeagle-2 | /task2.py | 520 | 4.21875 | 4 | #! python3
"""
Have the user enter a username and password.
Repeat this until both the username and password match the
following:
Remember to use input().strip() to input str type variables
username: admin
password: 12345
(2 marks)
inputs:
str (username)
str (password)
outputs:
Access granted
Access denied
example:
Enter username: fred
Enter password: password
Access denied
Enter username: admin
Enter password: password
Access denied
Enter username: admin
Enter password: 12345
Access granted
""" | true |
7779633f0c8bf9a73c3eafcc06e21beed0200332 | Nivedita01/Learning-Python- | /swapTwoInputs.py | 967 | 4.28125 | 4 | def swap_with_addsub_operators(x,y):
# Note: This method does not work with float or strings
x = x + y
y = x - y
x = x - y
print("After: " +str(x)+ " " +str(y))
def swap_with_muldiv_operators(x,y):
# Note: This method does not work with zero as one of the numbers nor with float
x = x * y
y = x / y
x = x / y
print("After: " +str(x)+ " " +str(y))
def swap_with_builtin_method(x,y):
# Note: This method works for string, float and integers
x,y = y,x
print("After: " +x+ " " +y)
x = raw_input("Enter first input: ")
y = raw_input("Enter second input: ")
print("Before: " +x+ " " +y)
swap_with_addsub_operators(int(x), int(y))
swap_with_muldiv_operators(int(x), int(y))
swap_with_builtin_method(x, y)
| true |
43927a3adcc76846309985c0e460d64849de0fa7 | Nivedita01/Learning-Python- | /guess_game.py | 560 | 4.21875 | 4 | guess_word = "hello"
guess = ""
out_of_attempts = False
guess_count = 0
guess_limit = 3
#checking if user entered word is equal to actual word and is not out of guesses number
while(guess != guess_word and not(out_of_attempts)):
#checking if guess count is less than guess limit
if(guess_count < guess_limit):
guess = raw_input("Enter guess word: ")
guess_count += 1
else:
out_of_attempts = True
if out_of_attempts:
print "Sorry! You couldn't guess"
else:
print "You win!"
| true |
12f9dbff51caec4d245d00d5d6cc71d0c3c88b5f | rdumaguin/CodingDojoCompilation | /Python-Oct-2017/PythonFundamentals/Lists_to_Dict.py | 1,020 | 4.21875 | 4 | name = ["Anna", "Eli", "Pariece", "Brendan", "Amy", "Shane", "Oscar"]
favorite_animal = ["horse", "cat", "spider", "giraffe", "ticks", "dolphins", "llamas"]
def zipLists(x, y):
zipped = zip(x, y)
# print zipped
newDict = dict(zipped)
print newDict
return newDict
zipLists(name, favorite_animal)
# Create a function that takes in two lists and creates a single dictionary where the first list contains keys and the second values. Assume the lists will be of equal length.
#
# Your first function will take in two lists containing some strings. Here are two example lists:
#
# name = ["Anna", "Eli", "Pariece", "Brendan", "Amy", "Shane", "Oscar"]
# favorite_animal = ["horse", "cat", "spider", "giraffe", "ticks", "dolphins", "llamas"]
# Here's some help starting your function.
#
# def make_dict(arr1, arr2):
# new_dict = {}
# # your code here
# return new_dict
# Hacker Challenge:
# If the lists are of unequal length, the longer list should be used for the keys, the shorter for the values.
| true |
503355cdd49fa7399ed1062a112b8de55f1c0654 | tme5/PythonCodes | /Daily Coding Problem/PyScripts/Program_0033.py | 926 | 4.25 | 4 | '''
This problem was asked by Microsoft.
Compute the running median of a sequence of numbers. That is, given a stream of numbers, print out the median of the list so far on each new element.
Recall that the median of an even-numbered list is the average of the two middle numbers.
For example, given the sequence [2, 1, 5, 7, 2, 0, 5], your algorithm should print out:
2
1.5
2
3.5
2
2
2
Created on 03-Jul-2019
@author: Lenovo
'''
def median(arr):
temp_arr=[]
for i in arr:
temp_arr.append(i)
temp_arr.sort()
if len(temp_arr)==1:
print(temp_arr[0])
elif len(temp_arr)%2==0:
mid=round(len(temp_arr)/2)
print((temp_arr[mid]+temp_arr[mid-1])/2)
else:
mid=round(len(temp_arr)/2)-1
print(temp_arr[mid])
def main():
median([2, 1, 5, 7, 2, 0, 5])
if __name__ == '__main__':
main() | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.