blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
65418f750afea14168ea6f8095b9bf1234b722a8 | KiranGowda10/Add-2-Linked-Lists---LeetCode | /add_2_num.py | 832 | 4.125 | 4 |
class Node:
def __init__(self, data = None):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = Node()
def append(self, data):
new_node = Node(data)
current_node = self.head
while current_node.next is not None:
current_node = current_node.next
current_node.next = new_node
def display(self):
elements1 = []
current_node = self.head
while current_node.next is not None:
current_node = current_node.next
elements1.append(current_node.data)
add1 = LinkedList()
add1.append(1)
add1.append(2)
add1.append(3)
print(add1.display())
add2 = LinkedList()
add2.append(4)
add2.append(5)
add2.append(6)
print(add2.display())
| true |
25a39a23d66108f8909741e94c7e9e290479c044 | fatmazehraCiftci/GlobalAIHubPythonCourse | /Homeworks/homework2.py | 482 | 4.1875 | 4 | """
Create a list and swap the second half of the list with the first half of the list and
print this list on the screen
"""
def DivideandSwap(list):
length=len(list)
list1=[]
list2=[]
for i in range(int(length/2)):
list1.append(list[i])
remainder=length-int(length/2)
for i in range(remainder):
list2.append(list[i-remainder])
list=list2+list1
print(list)
list=[1,2,3,4,5,6]
DivideandSwap(list) | true |
3766e43d653c9e92a2fdb946a34de44c0e43905c | shivamagrawal3900/Python-crash-course | /chapter5-if_statements.py | 1,249 | 4.1875 | 4 | cars = ['Audi', 'BMW', 'Jaguar', 'LandRover']
for car in cars:
if car == 'Jaguar':
print(car.upper())
else:
print(car)
# == is case sensitive
print(cars[1]=='bmw')
# > False
# !=
print(cars[1]!='Audi')
# > True
# Numerical Comparisions
# ==, !=, <, >, <=, >=
# Checking multiple values
# 'and' and 'or' operations. NOTE: '&' and '|' does not work
print(cars[0]=='Audi' and cars[1] == 'BMW')
# >True
print(cars[2]=='Jaguar' or cars[3]=='Jaguar')
# >True
# First 'and' operations takes place then or
print(cars[2]=='Jaguar' and cars[3]=='Jaguar' or cars[0]=='Audi' and cars[1] == 'Audi')
# >False
# To check if the value is in list, use 'in' keyword
print('Jaguar' in cars)
# >True
# To check if the value is not in the list, use 'not in' keyword
print('Tata' not in cars)
# >True
# IF STATEMENTS
# NOTE: assignment in if won't work, i.e. if a=2 will give an error
# If - elif - else statements
value=15
if value%15 == 0:
print('buzzfizz')
elif value%3 == 0:
print('buzz')
elif value%5 == 0:
print('fizz')
else:
print('none')
# To check if list is empty
toppings = []
if toppings:
print('toppings are: '+str(toppings))
else:
print('no toppings')
# >no toppings
# For pEP 8 styling, use singe space both sides of operator | true |
09ea43cd396693c775912dd83794f43c38de8ee5 | deepikaasharma/Parallel-Lists-Challenge | /main.py | 1,333 | 4.125 | 4 | """nums_a = [1, 3, 5]
nums_b = [2, 4, 6]
res = 0
for a, b in zip(nums_a, nums_b):
res += a * b"""
"""Write a function called enum_sum which takes a list of numbers and returns the sum of the numbers multiplied by their corresponding index incremented by one.
Ex: enum_sum([2, 4, 6]) -> (index 0 + 1)*2 + (index 1 + 1)*4 + (index 2 + 1)*6 -> 1*2 + 2*4 + 3*6 -> 28
num_list = []
def enum_sum(num_list):
num_sum = 0
for idx, elem in enumerate(num_list):
num_sum += (idx+1)*elem
return num_sum
print(enum_sum([2,4,6]))
"""
"""Implement the function dbl_seq_sum which takes two lists of positive integers and computes the summation
∑k=1(−1)**k⋅(ak+bk/ 1+ak⋅bk)
""enum = len(list1)
for a,b in zip(enum list1, list2):
sum += ((-1)**k)* ((a+b)/(1+(a*b)))
return sum""
Where ak
and bk refer to the k-th elements in the two given lists. Notice that there is no upper bound on the summation. This just means "sum over all the elements". Assume that both lists will be the same length, and take note of the starting index of the summation."""
nums_a = []
nums_b = []
def dbl_seq_sum(nums_a, nums_b):
sum_ = 0
enum = range(1, len(nums_a)+1)
for k, a_k, b_k in zip(enum, nums_a, nums_b):
sum_ += ((-1)**k)* ((a_k+b_k)/(1+(a_k*b_k)))
return sum_
print(dbl_seq_sum([1,2,3],[3,4,5])) | true |
8976ba885b018f928284de9128f6b2ce4725c4dc | BibhuPrasadPadhy/Python-for-Data-Science | /Python Basics/100_Python_Programs/Question2.py | 501 | 4.4375 | 4 | ##Write a program which can compute the factorial of a given numbers.
##The results should be printed in a comma-separated sequence on a single line.
##Suppose the following input is supplied to the program:
##8
##Then, the output should be:
##40320
##
##Hints:
##In case of input data being supplied to the question, it should be assumed to be a console input.
def factorial(num):
if num == 0:
return 1
else:
return num*factorial(num-1)
print(factorial(5))
| true |
d68c9cf85a4f6a2cb377a94c2c124a55feccd66c | pmk2109/Week0 | /Code2/dict_exercise.py | 1,513 | 4.28125 | 4 | from collections import defaultdict
def dict_to_str(d):
'''
INPUT: dict
OUTPUT: str
Return a str containing each key and value in dict d. Keys and values are
separated by a colon and a space. Each key-value pair is separated by a new
line.
For example:
a: 1
b: 2
For nice pythonic code, use iteritems!
Note: it's possible to do this in 1 line using list comprehensions and the
join method.
'''
return "\n".join(["{}: {}".format(k,v) for k,v in d.iteritems()])
def dict_to_str_sorted(d):
'''
INPUT: dict
OUTPUT: str
Return a str containing each key and value in dict d. Keys and values are
separated by a colon and a space. Each key-value pair is sorted in ascending order by key.
This is sorted version of dict_to_str().
Note: This one is also doable in one line!
'''
return "\n".join(list(["{}: {}".format(k,v) for k,v in sorted(d.iteritems())]))
def dict_difference(d1, d2):
'''
INPUT: dict, dict
OUTPUT: dict
Combine the two dictionaries, d1 and d2 as follows. The keys are the union of the keys
from each dictionary. If the keys are in both dictionaries then the values should be the
absolute value of the difference between the two values. If a value is only in one dictionary, the
value should be the absolute value of that value.
'''
d3_dict = {}
for key in (set(d1) | set(d2)):
d3_dict[key] = abs(d1.get(key,0) - d2.get(key,0)))
return d3_dict
| true |
a63908c918a6b0cbd35b98485fc79683c3923138 | joy-joy/pcc | /ch03/exercise_3_8.py | 1,075 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 17 21:17:17 2018
@author: joy
"""
# Seeing the World
visit_list = ["Machu Picchu", "Phuket", "Bali",
"Grand Canyon", "Santorini", "Dubai",
"New York City", "Paris", "London", "Sydney"]
print("\nVisit List:")
print(visit_list)
print("\nSorted List:")
print(sorted(visit_list))
print("\nOriginal List still preserved:")
print(visit_list)
print("\nReverse List:")
print(sorted(visit_list, reverse=True))
# Using the reverse() method on original list:
visit_list.reverse()
print("\nOrder has changed in the Original List:")
print(visit_list)
# Using the reverse() method to revert back to the original list:
visit_list.reverse()
print("\nOrder back to that of the Original List:")
print(visit_list)
# Using the sort() method to sort it (permanent change):
visit_list.sort()
print('\nSorted List using "sort()":')
print(visit_list)
# Using the sort() method to reverse sort it:
visit_list.sort(reverse = True)
print('\nReverse Sorted List using "sort()":')
print(visit_list)
| true |
7705715e8e7b21cfbc6b0b3c32d44f9463333c80 | janbalaz/ds | /selection_sort.py | 1,048 | 4.28125 | 4 | from typing import List
def find_smallest(i: int, arr: List[int]) -> int:
"""
Finds the smallest element in array starting after `i`.
:param i: index of the current minimum
:param arr: array of integers
:return: position of the smallest element
"""
smallest = i
for j in range(i + 1, len(arr)):
if arr[j] < arr[smallest]:
smallest = j
return smallest
def swap_elements(i: int, j: int, arr: List[int]) -> None:
"""
Swaps the elements in array.
:param i: position i
:param j: position j
:param arr: array of integers
"""
arr[i], arr[j] = arr[j], arr[i]
def selection_sort(arr: List[int]):
"""
Returns sorted array using selection sort.
Places sorted values on the left side of the array
by swapping the smallest element with current position.
:param arr: array of integers
:return: sorted array of integers
"""
for i in range(len(arr) - 1):
j = find_smallest(i, arr)
swap_elements(i, j, arr)
return arr
| true |
72385e51495ed17597e19bd13f49992ef96df332 | karlmanalo/cs-module-project-recursive-sorting | /src/searching/searching.py | 1,243 | 4.5 | 4 | # TO-DO: Implement a recursive implementation of binary search
def binary_search(arr, target, start, end):
# Handling empty arrays
if len(arr) == 0:
return -1
# Setting midpoint
midpoint = (start + end) // 2
if target == arr[midpoint]:
return midpoint
# Recursion if target is not found at midpoint
# If target is less than the midpoint, search from the beginning
# of the array to one element before the midpoint (subtract 1 from
# the index because we've already compared the target to the midpoint's
# value in the beginning of this if statement)
elif target < arr[midpoint]:
return binary_search(arr, target, start, midpoint - 1)
# If target is greater than the midpoint, search from the midpoint
# (plus one) to the end of the array
else:
return binary_search(arr, target, midpoint + 1, end)
# STRETCH: implement an order-agnostic binary search
# This version of binary search should correctly find
# the target regardless of whether the input array is
# sorted in ascending order or in descending order
# You can implement this function either recursively
# or iteratively
# def agnostic_binary_search(arr, target):
# Your code here
| true |
fbb99279410300d18b04e4206e9c9b043a4c0866 | egbea123/Math | /Test_REMOTE_389.py | 281 | 4.1875 | 4 | #!/usr/bin/env python
def main ():
num1 = 10.5
num2 = 6.3
# Subtract two numbers
sum = float(num1) - float(num2)
# Display the result
print('The sum of {0} and {1} is {2}',num1, num2, sum )
#division of two numbers
result = 10.5 / 6.3
print ("Result :",result) | true |
e0334e857bed3460736a05791dcd7469ac2fdeab | jakelorah/highschoolprojects | /Senior(2018-2019)/Python/Chapter 2/P2.8.py | 781 | 4.25 | 4 | #Name: Jake Lorah
#Date: 09/14/2018
#Program Number: P2.8
#Program Description: This program finds the area and perimeter of the rectangle, and the length of the diagonal
#Declaring the sides of a rectangle
Side1 = 24
Side2 = 13
Side3 = 24
Side4 = 13
print("The 4 sides of the rectangle are 24 inches, 13 inches, 24 inches, and 13 inches.")
print()
#Finding the area
Area = Side1 * Side2
print("The area of the rectangle is", Area, "inches squared.")
print()
#Finding the perimeter
Perimeter = Side1 + Side2 + Side3 + Side4
print("The perimeter of the rectangle is", Perimeter, "inches.")
print()
#Finding the length of the diagonal
Diagonal = ((Side1 * Side3) + (Side2 * Side4))**(1/2)
print("The length of the diagonal is", Diagonal, "inches.")
| true |
cdf0b54074aa96db6c30c21d0aaf9026ca250317 | jakelorah/highschoolprojects | /Senior(2018-2019)/Python/Tkinter GUI/3by3grid _ Window Project/7.Button_Event_handler.py | 815 | 4.125 | 4 | #Name: Jake Lorah
#Date: 11/26/2018
#Program Number: 7.Button_Event_handler
#Program Description: This program adds a button event handler.
from tkinter import *
window = Tk()
window.title("Welcome To Computer Science 4")
window.geometry('1100x500')
addtext= Label(window, text="Hello How are you today", font=("Arial Bold", 70))
addtext.grid(column=0, row=0)
count = 0
def clicked():
global count
old = '1000x500'
addtext.configure(text="Button was Clicked!!")
window.geometry(old)
count = count + 1
if count % 2 == 0:
window.geometry('1100x500')
addtext.configure(text = "Hello How are you today")
addbutton = Button(window, text="Click me", bg="black", fg="red", command=clicked)
addbutton.grid(column=0, row=2)
window.mainloop()
| true |
afec42e00509bc8ae26cf9f73bde35d5b47d2ee7 | jakelorah/highschoolprojects | /Senior(2018-2019)/Python/Chapter 4/average.py | 317 | 4.15625 | 4 | #Find the average
total = 0.0
count = 0
inputStr = input("Enter value: ")
while inputStr != "" :
value = float(inputStr)
total = total + value
count = count + 1
inputStr = input("Enter value: ")
if count > 0 :
average = total / count
else :
average = 0.0
print (average)
| true |
939412528610843959ee52b2b4fbd620083c5cb9 | T-D-Wasowski/Small-Projects | /Turtle Artist/Prototype.py | 473 | 4.15625 | 4 | import random
import turtle
turtle.stamp()
moveAmount = int(input("Enter the amount of moves \
you would like your Turtle Artist to make: "))
for i in range(moveAmount):
turtle.right(random.randint(1,51)) #<-- For circles.
turtle.forward(random.randint(1,101))
turtle.stamp() #Do you collect stamps?
input("Press any button to exit.")
#Turtle bounce off the edge mechanic.
#Input preference, square, circle, etc.
#Print/Save image.
| true |
bd940f09734b661d4902b0f304f1d38d1530fa44 | MichaelAlonso/MyCSSI2019Lab | /WeLearn/M3-Python/L1-Python_Intro/hello.py | 1,107 | 4.21875 | 4 | print("Hello world!")
print("Bye world!")
num1 = int(raw_input("Enter number #1: "))
num2 = int(raw_input("Enter number #2: "))
total = num1 + num2
print("The sum is " + str(total))
num = int(raw_input("Enter a number: "))
if num > 0:
print("That's a positive number!")
print("Do cherries come from cherry blossom trees!")
elif num < 0:
print("That's a negative number!")
print("Hello I am able to read this message again in my mind!")
else:
print("Zero is neither positive nor negative")
string = "hello there"
for letter in string:
print(letter.upper())
for i in range(5):
print(i)
x = 1
while x <= 5:
print(x)
x = x + 1
my_name = "Bob"
friend1 = "Alice"
friend2 = "John"
friend3 = "Mallory"
print(
"My name is %s and my friends are %s, %s, and %s" %
(my_name, friend1, friend2, friend3)
)
def greetAgent():
print("Bond. James Bond.")
def greetAgent(first_name, last_name):
print("%s. %s %s." % (last_name, first_name, last_name))
def createAgentGreeting(first_name, last_name):
return "%s. %s %s." % (last_name, first_name, last_name)
| true |
ab631a8f16be070bb556ed662c1af5931cd9cbe7 | vishalagg/Using_pandas | /bar_plot.py | 1,829 | 4.625 | 5 | import matplotlib.pyplot as plt
'''
In line charts, we simply pass the the x_values,y_values to plt.plot() and rest of wprk is done by the function itself. In case of bar graph, we have to take care of three things:
1.position of bars(ie. starting position of each bar)
2.position of axis labels.
3.width of the bars.
'''
'''
We can generate a vertical bar plot using either pyplot.bar() or Axes.bar(). prefebly, use Axes.bar() so we can extensively customize the bar plot more easily. We can use pyplot.subplots() to first generate a single subplot and return both the Figure and Axes object.
eg:******
fig, ax = plt.subplots()
^above eqn is equivalent to:
fig = plt.figure(1,1,1)
ax = fig.add_subplot()
'''
'''
To pass all three parameters mentioned in 1st paragraph, we can pass like:
ax.bar(bar_positions, bar_heights, width)
here:
bar_positions(left) and bar_heights = Both are lists.
width = specifys the width of each bar,generally float o int.
'''
'''
Ticks,labels,rotation:
By default, matplotlib sets the x-axis tick labels to the integer values the bars spanned on the x-axis (from 0 to 6). We only need tick labels on the x-axis where the bars are positioned. We can use Axes.set_xticks() to change the positions of the ticks to [1, 2, 3, 4, 5]:
tick_positions = range(1,6)
ax.set_xticks(tick_positions)
Then, we can use Axes.set_xticklabels() to specify the tick labels:
col = ['bar1','bar2','bar3','bar4','bar5']
ax.set_xticklabels(num_cols,rotation=90)
'''
'''
***similarly we can create HORIZONTAL BAR using:
ax.barh(bar_positions(bottom), bar_widths,width) instead of ax.bar()
We use Axes.set_yticks() to set the y-axis tick positions to [1, 2, 3, 4, 5] and Axes.set_yticklabels() to set the tick labels to the column names
''' | true |
3cb86970951a4c592edf191fb44af65aca41e321 | rachelprisock/python_hard_way | /ex3.py | 1,014 | 4.21875 | 4 | from __future__ import division
print "I will now count my chickens:"
# PEMDAS so 30 / 6 = 5 and 25 + 5 = 30
print "Hens", 25 + 30 / 6
# 25 * 3 = 75, 75 % 4 = 3, so 100 - 3 = 97
print "Roosters", 100 - 25 * 3 % 4
print "Now I will count the eggs:"
# 4 % 2 = 0, 1 / 4 (no floats with /) = 0
# so 3 + 2 + 1 - 5 + 0 - 0 + 6 = 7
print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
print "Is it true that 3 + 2 < 5 - 7?"
# 5 < -2 False.
print 3 + 2 < 5 - 7
print "What is 3 + 2?", 3 + 2
print "What is 5 - 7?", 5 - 7
print "Oh, that's why it's False."
print "How about some more."
print "Is is greater?", 5 > -2
print "Is it greater or equal?", 5 >= -2
print "Is it less or equal?", 5 <= -2
# NOTE: this difference in division between Python 2 and 3.
# If I ran this file using Python 3 I would get floating
# point integers instead of only whole numbers
# In python 2 it's best to import division from the future version
# otherwise you can use float() or just multiply the number with a float, ex:
# 1/(2 * 1.0) = 0.5
| true |
34a8d045b8b194670396993143d998ff0ffc8605 | Kyle-Everett10/cp_1404_pracs | /practical_3/oddName.py | 562 | 4.125 | 4 | """Kyle"""
def main():
name = input("Enter your name here: ")
while name == "":
print("Not a valid name")
name = input("Enter your name here: ")
frequency = int(input("How frequent do you want the names to be taken?: "))
print(extract_characters(name, frequency))
def extract_characters(name, frequency):
characters = []
for character in range(0, len(name), frequency):
characters.append(name[character])
extracted_characters = " ".join(characters)
return extracted_characters
main()
print("Done")
| true |
5536d5bf0689156156e257522381bc2122351be7 | thinpyai/python-assignments | /python_small_exercises/sum_matix_crosses.py | 745 | 4.28125 | 4 | def sum_all_cross(matrix):
"""
Sum all cross direction of matrix.
matrix: input integer value in list.
"""
sum = sum_cross(matrix)
reversed_matrix = list(reversed(matrix))
sum += sum_cross(reversed_matrix)
return sum
def sum_cross(matrix):
"""
Sum matrix in one cross direction.
matrix: input integer value in list.
"""
target_index = 0
sum = 0
for row in matrix:
sum += row[target_index]
target_index +=1
return sum
if __name__=='__main__':
"""
Calculate two cross direction of matrix.
e.g. (1+5+9) + (3+5+7)
"""
matrix = [
[1,2,3],
[4,5,6],
[7,8,9]
]
result = sum_all_cross(matrix)
print(result) | true |
de9325d80d1942fec3c7298d01dedc2bd4b864d5 | thinpyai/python-assignments | /python_small_exercises/flatten.py | 1,566 | 4.375 | 4 | # Approximate 1 ~ 1.5h
# For this exercise you will create a global flatten method. The method takes in any number of arguments and flattens them into a single array. If any of the arguments passed in are an array then the individual objects within the array will be flattened so that they exist at the same level as the other arguments. Any nested arrays, no matter how deep, should be flattened into the single array result.
# The following are examples of how this function would be used and what the expected results would be:
# flatten(1, [2, 3], 4, 5, [6, [7]]) # returns [1, 2, 3, 4, 5, 6, 7]
# flatten('a', ['b', 2], 3, None, [[4], ['c']]) # returns ['a', 'b', 2, 3, None, 4, 'c']
def flatten(*argv, flatten_list = None):
if flatten_list is None:
flatten_list = []
for var in argv:
if isinstance(var, list):
flatten(*var, flatten_list = flatten_list)
continue
flatten_list.append(var)
return flatten_list
def flatten_2(*a):
r = []
for x in a:
if isinstance(x, list):
r.extend(flatten(*x))
else:
r.append(x)
return r
def flatten_3(*args):
return [x for a in args for x in (flatten(*a) if isinstance(a, list) else [a])]
def main():
print(flatten()) # []
print(flatten(1,2,3)) # [1,2,3]
print(flatten([1,2],[3,4,5],[6,[7],[[8]]])) # [1,2,3,4,5,6,7,8]
print(flatten(1,2,['9',[],[]],None)) # [1,2,'9',None]
print(flatten(['hello',2,['text',[4,5]]],[[]],'[list]')) # ['hello',2,'text',4,5,'[list]']
if __name__ == "__main__":
main() | true |
f4291c2cc1fb648f6cb11ceb8dd5de3fb8d078ed | CarlosArro2001/Little-Book-of-Programming-Problems-Python-Edition | /cards.py | 1,100 | 4.375 | 4 | #...
#Aim : Write a program that will generate a random playing cards , when the return return is pressed.
# Rather than generate a random number from 1 to 52 . Create two random numbers - one for the suit and one for the card.
#Author : Carlos Raniel Ariate Arro
#Date : 09-09-2019
#...
#imports
import random
#Array for the suits
suits = ["Hearts","Spades","Clubs","Diamonds"]
#Array for the numbers
numbers = ["Ace","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","King","Queen","Jack"]
#press enter to output a random card
input()
#two variables for storing the randomly generated , one for the suit and one for the numbers
randSuit = random.choice(suits)
randNum = random.choice(numbers)
cardName = randSuit + " of " + randNum
if cardName != randSuit + " of " + "King" or cardName != randSuit + " of " + "Queen" or cardName != randSuit + " of " + "Jack" :
print(cardName)
else:
randSuit = random.choice(Suits)
randNum = random.choice(numbers)
cardName = randSuit + " of " + randNum
#Extension - put it into a loop. | true |
266b63afbc2a3739423616db5fc2dd395c6977f5 | shiyuan1118/Leetcode-in-Python | /Leetcode in Python/double index/merge sorted array(88).py | 585 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri May 8 13:09:50 2020
@author: baoshiyuan
"""
#Merge Sorted Array
class Solution:
def merge(nums1, m, nums2, n):
while m>0 and n>0:
if nums2[n-1]>nums1[m-1]:
nums1[m+n-1]=nums2[n-1]
n=n-1
else:
nums1[m-1],nums1[m+n-1]=nums2[n-1],nums1[m-1]
m=m-1
if m==0 and n>0:
nums1[:n]=nums2[:n]##if the length of nums2 is greater than nums1,then put the rest of nums2 in the front of merger | true |
c7a9f186a03d699cfb4c205e0d4012f637d9963b | carden-code/python | /stepik/third_digit.py | 356 | 4.15625 | 4 | # A natural number n is given, (n> 99). Write a program that determines its third (from the beginning) digit.
#
# Input data format
# The input to the program is one natural number, consisting of at least three digits.
#
# Output data format
# The program should display its third (from the beginning) digit.
num = input()
digit = int(num[2])
print(digit)
| true |
74446a287ad4ff8721c0a882051cd13971e88ba4 | carden-code/python | /stepik/removing_a_fragment.py | 504 | 4.1875 | 4 | # The input to the program is a line of text in which the letter "h" occurs at least twice.
# Write a program that removes the first and
# last occurrences of the letter "h" from this string, as well as any characters in between.
#
# Input data format
# The input to the program is a line of text.
#
# Output data format
# The program should display the text in accordance with the condition of the problem.
string = input()
elem = 'h'
print(string[:string.find(elem)] + string[string.rfind(elem) + 1:])
| true |
69b16d9c547d2c153d686af7d849138a64ca1bd1 | carden-code/python | /stepik/simple_cipher.py | 424 | 4.3125 | 4 | # The input to the program is a line of text.
# Write a program that translates each of its characters into their corresponding code
# from the Unicode character table.
#
# Input data format
# The input to the program is a line of text.
#
# Output data format
# The program should output the code values of the string characters separated by one space character.
string = input()
for c in string:
print(ord(c), end=' ')
| true |
69fd35f3faed85dd3ccc5a9a5c1fd5943b52623f | carden-code/python | /stepik/replace_me_completely.py | 360 | 4.21875 | 4 | # The input to the program is a line of text.
# Write a program that replaces all occurrences of the number 1 with the word "one".
#
# Input data format
# The input to the program is a line of text.
#
# Output data format
# The program should display the text in accordance with the condition of the problem.
string = input()
print(string.replace('1', 'one'))
| true |
e0268220615c83737c7a823fd3195ed76188ab85 | carden-code/python | /stepik/word_count.py | 468 | 4.40625 | 4 | # The input to the program is a line of text consisting of words separated by exactly one space.
# Write a program that counts the number of words in it.
#
# Input data format
# The input to the program is a line of text.
#
# Output data format
# The program should output the word count.
#
# Note 1. A line of text does not contain leading or trailing spaces.
#
# Note 2. Use the count method to solve the problem.
string = input()
s = ' '
print(string.count(s) + 1)
| true |
6be2286fe9476c8ee964976e14b3de72d4228609 | carden-code/python | /stepik/fractional_part.py | 342 | 4.375 | 4 | # A positive real number is given. Output its fractional part.
#
# Input data format
# The input to the program is a positive real number.
#
# Output data format
# The program should output the fractional part of the number in accordance with the condition of the problem.
num = float(input())
fractional = num - (int(num))
print(fractional)
| true |
10ccf77bd405de979d859da5f0d2489cecfb845e | carden-code/python | /stepik/prime_numbers.py | 583 | 4.1875 | 4 | # The input to the program is two natural numbers a and b (a < b).
# Write a program that finds all prime numbers from a to b, inclusive.
#
# Input data format
# The program receives two numbers as input, each on a separate line.
#
# Output data format
# The program should print all prime numbers from a to b inclusive, each on a separate line.
a = int(input())
b = int(input())
total = 0
for i in range(a, b + 1):
for j in range(1, b + 1):
if i % j == 0:
total += 1
if total < 3 and i > 1:
print(i)
total = 0
else:
total = 0
| true |
98c21ee3a49b5420d1f74200a2b2c097c5c49a7a | carden-code/python | /stepik/same_numbers.py | 483 | 4.15625 | 4 | # A natural number is given. Write a program that determines if a specified number consists of the same digits.
#
# Input data format
# One natural number is fed into the program.
#
# Output data format
# The program should print "YES" if the number consists of the same digits and "NO" otherwise.
num = int(input())
last_num = num % 10
flag = True
while num != 0:
if last_num != num % 10:
flag = False
num = num // 10
if flag:
print('YES')
else:
print('NO')
| true |
bd2ee920b3b63169a741adedb5fc6c37fad8931f | carden-code/python | /stepik/diagram.py | 469 | 4.21875 | 4 | # The input to the program is a string of text containing integers.
# Write a program that plots a bar chart for given numbers.
#
# Input data format
# The input to the program is a text string containing integers separated by a space character.
#
# Output data format
# The program should output a bar chart.
# Sample Input 1:
#
# 1 2 3 4 5
# Sample Output 1:
#
# +
# ++
# +++
# ++++
# +++++
string = input()
sym = '+'
for i in string.split():
print(sym * int(i))
| true |
d74b3a0f209a35e82e1061370ea268d36cb3f1b4 | carden-code/python | /stepik/reverse_number.py | 558 | 4.53125 | 5 | # Write a program that reads one number from the keyboard and prints the inverse of it.
# If at the same time the number entered from the keyboard is zero,
# then output "The reverse number does not exist" (without quotes).
#
# Input data format
# The input to the program is one real number.
#
# Output data format
# The program should output a real number opposite to the given one,
# or the text in accordance with the condition of the problem.
num = float(input())
if num == 0:
print('The reverse number does not exist')
else:
print(num**-1 / 1)
| true |
8c678c8d77d22a603a84c0434d459197f6eadf6f | carden-code/python | /stepik/number_of_members.py | 630 | 4.375 | 4 | # The program receives a sequence of words as input, each word on a separate line.
# The end of the sequence is one of three words: "stop", "enough", "sufficiently" (in small letters, no quotes).
# Write a program that prints the total number of members in a given sequence.
#
# Input data format
# The program receives a sequence of words as input, each word on a separate line.
#
# Output data format
# The program should output the total number of members in the given sequence.
counter = 0
text = input()
while text != 'stop' and text != 'enough' and text != 'sufficiently':
counter += 1
text = input()
print(counter)
| true |
b06660bcc21e0142f6cdb78adb357b8df1953fb5 | carden-code/python | /stepik/characters_in_range.py | 500 | 4.3125 | 4 | # The input to the program is two numbers a and b.
# Write a program that, for each code value in the range a through b (inclusive),
# outputs its corresponding character from the Unicode character table.
#
# Input data format
# The input to the program is two natural numbers, each on a separate line.
#
# Output data format
# The program should display the text in accordance with the condition of the problem.
a = int(input())
b = int(input())
for i in range(a, b + 1):
print(chr(i), end=' ')
| true |
84342c5f534b935c231e13a9836c4af83e840fe2 | carden-code/python | /stepik/sum_of_digits.py | 218 | 4.125 | 4 | # Write a function print_digit_sum () that takes a single integer num and prints the sum of its digits.
def print_digit_sum(_num):
print(sum([int(i) for i in str(_num)]))
num = int(input())
print_digit_sum(num)
| true |
0291ba0bf851212409f7ac5f928153ba0fda249f | carden-code/python | /stepik/line_by_line_output.py | 347 | 4.4375 | 4 | # The input to the program is a line of text. Write a program that displays the words of the entered line in a column.
#
# Input data format
# The input to the program is a line of text.
#
# Output data format
# The program should display the text in accordance with the condition of the problem.
string = input()
print(*string.split(), sep='\n')
| true |
f3e5e2a96224b5ad2133b5683b8803a654141797 | carden-code/python | /stepik/sum_num_while.py | 497 | 4.28125 | 4 | # The program is fed a sequence of integers, each number on a separate line.
# The end of the sequence is any negative number.
# Write a program that outputs the sum of all the members of a given sequence.
#
# Input data format
# The program is fed with a sequence of numbers, each number on a separate line.
#
# Output data format
# The program should display the sum of the members of the given sequence.
total = 0
i = int(input())
while i >= 0:
total += i
i = int(input())
print(total)
| true |
ce3399dcdfc212a588de430f21cb81735264b258 | Mario-D93/habit_tracker | /t_backend.py | 1,885 | 4.21875 | 4 | import sqlite3
class Database():
'''
The Database object contains functions to handle operations such as adding,
viewing, searching, updating, & deleting values from the sqlite3 database
The object takes one argument: name of sqlite3 database
Class is imported to the frontend script (t_fronted.py)
'''
def __init__(self,db):
'''
Database Class Constractor to initialize the object and
connect to the database if exists.
IF not, new database will be created and will contain columns:
id, work, wake_up, training, bedtime, sleep
'''
self.conn=sqlite3.connect(db)
self.curs=self.conn.cursor()
self.curs.execute("CREATE TABLE IF NOT EXISTS trackerdata(id INTEGER PRIMARY KEY, dt TEXT, work INTEGER, wake_up INTEGER,\
training TEXT, bedtime INTEGER, sleep INTEGER)")
self.conn.commit()
def insert(self,dt,work,wake_up,training,bedtime,sleep):
self.curs.execute("INSERT INTO trackerdata VALUES(NULL,?,?,?,?,?,?)",(dt,work,wake_up,training,bedtime,sleep))
self.conn.commit()
def view_all(self):
self.curs.execute("SELECT * FROM trackerdata")
view_all=self.curs.fetchall()
return view_all
def search(self,dt="",work="",wake_up="",training="",bedtime="",sleep=""):
self.curs.execute("SELECT * FROM trackerdata WHERE dt=? OR work=? OR wake_up=? OR training=? OR bedtime=? OR sleep=?",\
(dt,work,wake_up,training,bedtime,sleep))
view_all=self.curs.fetchall()
return view_all
def delete(self,id):
self.curs.execute("DELETE FROM trackerdata WHERE id=?",(id,))
self.conn.commit()
def update(self,id,dt,work,wake_up,training,bedtime,sleep):
self.curs.execute("UPDATE trackerdata SET dt=?,work=?,wake_up=?,\
training=?,bedtime=?,sleep=? WHERE id=?",(dt,work,wake_up,\
training,bedtime,sleep,id))
self.conn.commit()
def __del__(self):
#function closes the connection with the sqlite3 database
self.conn.close() | true |
89fafeb66a04184fb1f8fe490ecde074c68ae4bc | 0n1udra/Learning | /Python/Python_Problems/Rosalind-master/Algorithmic_009_BFS.py | 1,705 | 4.21875 | 4 | #!/usr/bin/env python
'''
A solution to a ROSALIND problem from the Algorithmic Heights problem area.
Algorithmic Heights focuses on teaching algorithms and data structures commonly used in computer science.
Problem Title: Breadth-First Search
Rosalind ID: BFS
Algorithmic Heights #: 012
URL: http://rosalind.info/problems/bfs/
'''
from collections import defaultdict
def minimum_dist_bfs(n, edges):
'''Performs a BFS to get the minimum distance to all nodes starting at node 1.'''
# Build the graph.
graph = defaultdict(list)
for n1, n2 in edges:
graph[n1].append(n2)
# BFS to find the minimum distance to each node from node 1.
min_dist = [0] + [-1]*(n-1)
remaining = set(xrange(2, n+1))
queue = [1]
while queue:
current = queue.pop(0)
for node in graph[current]:
if node in remaining:
queue.append(node)
remaining.discard(node)
# Rosalind starts indices at 1 instead of 0.
min_dist[node-1] = min_dist[current-1] + 1
return min_dist
def main():
'''Main call. Reads, runs, and saves problem specific data.'''
# Read the input data.
with open('data/algorithmic/rosalind_bfs.txt') as input_data:
n = map(int, input_data.readline().strip().split())[0]
edges = [map(int, line.strip().split()) for line in input_data]
# Get the minimum distances.
min_dist = map(str, minimum_dist_bfs(n, edges))
# Print and save the answer.
print ' '.join(min_dist)
with open('output/algorithmic/Algorithmic_009_BFS.txt', 'w') as output_data:
output_data.write(' '.join(min_dist))
if __name__ == '__main__':
main()
| true |
7bc496f3183da034730fad98d0b6bc26b27573c2 | 0n1udra/Learning | /Python/Python_Problems/Rosalind-master/001_DNA.py | 934 | 4.1875 | 4 | #!/usr/bin/env python
'''
A solution to a ROSALIND bioinformatics problem.
Problem Title: Counting DNA Nucleotides
Rosalind ID: DNA
Rosalind #: 001
URL: http://rosalind.info/problems/dna/
'''
from collections import Counter
def base_count_dna(dna):
'''Returns the count of each base appearing in the given DNA sequence.'''
base_count = Counter(dna)
return [base_count[base] for base in 'ACGT']
def main():
'''Main call. Parses, runs, and saves problem specific data.'''
# Read the input data.
with open('data/rosalind_dna.txt') as input_data:
dna = input_data.read().strip()
# Get the count of each base appearing in the DNA sequence.
base_count = map(str, base_count_dna(dna))
# Print and save the answer.
print ' '.join(base_count)
with open('output/001_DNA.txt', 'w') as output_data:
output_data.write(' '.join(base_count))
if __name__ == '__main__':
main()
| true |
c8508b6bba66b1052ca57cc2b9b31af313f805da | 0n1udra/Learning | /Python/Python_Problems/Interview_Problems-master/python/logarithm.py | 732 | 4.1875 | 4 | '''
Compute Logarithm
x: a positive integer
b: a positive integer; b >= 2
returns: log_b(x), or, the logarithm of x relative to a base b.
Assumes: It should only return integer value and solution is recursive.
'''
def myLog(x, b):
if x < b:
return 0
else:
return myLog(x/b, b) + 1
if __name__ == '__main__':
# Test section
implementations = [myLog]
for impl in implementations:
print "trying %s" % impl
print " f(1, 2) == 0: %s" % (impl(1,2) == 0)
print " f(2, 2) == 1: %s" % (impl(2,2) == 1)
print " f(16, 2) == 4: %s" % (impl(16,2) == 4)
print " f(15, 3) == 2: %s" % (impl(15,3) == 2)
print " f(15, 4) == 1: %s" % (impl(15,4) == 1)
| true |
6fb3874538b010fa6367cfd1ef6ed6fd392e91c3 | TheJoeCollier/cpsc128 | /code/python2/tmpcnvrt.py | 1,242 | 4.5 | 4 | ###########################################################
## tmpcnvrt.py -- allows the user to convert a temperature
## in Fahrenheit to Celsius or vice versa.
##
## CPSC 128 Example program: a simple usage of 'if' statement
##
## S. Bulut Spring 2018-19
## Tim Topper, Winter 2013
###########################################################
print "This program converts temperatures from Fahrenheit to Celsius,"
print "or from Celsius to Fahrenheit."
print "Choose"
print "1 to convert Fahrenheit to Celsius"
print "2 to convert Celsius to Fahrenheit"
choice = input( "Your choice? " )
if choice == 1:
print "This program converts temperatures from Fahrenheit to Celsius."
temp_in_f = input( "Enter a temperature in Fahrenheit (e.g. 10) and press Enter: " )
temp_in_c = (temp_in_f - 32) * 5 / 9
print temp_in_f, " degrees Fahrenheit = ", temp_in_c, " degrees Celsius."
elif choice == 2:
print "This program converts temperatures from Celsius to Fahrenheit ."
temp_in_c= input( "Enter a temperature in Celsius (e.g. 10) and press Enter: " )
temp_in_f = temp_in_c * 9 / 5 + 32
print temp_in_c, " degrees Celsius = ", temp_in_f, " degrees Fahrenheit."
else:
print "Error: Your choice not recognized!"
| true |
0048afa92e4b1d09b35e2d7ae5c1dbe074f0b60e | shraddhaagrawal563/learning_python | /numpy_itemsize.py | 705 | 4.28125 | 4 | # -*- coding: utf-8 -*-
#https://www.tutorialspoint.com/numpy/numpy_array_attributes.htm
import numpy as np
x = np.array([1,2,3,4,5])
print ("item size" , x.itemsize) #prints size of an individual element
x = np.array([1,2,3,4,5,4.2,3.6])
print ("item size" , x.itemsize) #converts every element to the largest of size
x = np.array([1,2,3,4,5,3.3,"str"])
print ("item size" , x.itemsize)
x = np.array(["a","b", 4.5]) #adding size of each type
print ("item size" , x.itemsize)
''' only similar datatypes element can be put
inside an numpy array.. the above thing is not practised'''
print("\nnumpy flags")
x = np.array([1,2,3,4,5])
print ("item size" , x.flags) #gives the complete state of array | true |
1e0b7b0aed95cfb2db8b1f382bd898fef6c5e595 | hyetigran/Sorting | /src/recursive_sorting/recursive_sorting.py | 1,465 | 4.125 | 4 | # TO-DO: complete the helpe function below to merge 2 sorted arrays
def merge(arr, arrA, arrB):
# TO-DO
left_counter = 0
right_counter = 0
sorted_counter = 0
while left_counter < len(arrA) and right_counter < len(arrB):
if arrA[left_counter] < arrB[right_counter]:
arr[sorted_counter] = arrA[left_counter]
left_counter += 1
else:
arr[sorted_counter] = arrB[right_counter]
right_counter += 1
sorted_counter += 1
while left_counter < len(arrA):
arr[sorted_counter] = arrA[left_counter]
left_counter += 1
sorted_counter += 1
while right_counter < len(arrB):
arr[sorted_counter] = arrB[right_counter]
right_counter += 1
sorted_counter += 1
return arr
# TO-DO: implement the Merge Sort function below USING RECURSION
def merge_sort(arr):
if len(arr) > 1:
left_arr = arr[:len(arr)//2]
right_arr = arr[len(arr)//2:]
merge_sort(left_arr)
merge_sort(right_arr)
merge(arr, left_arr, right_arr)
return arr
# STRETCH: implement an in-place merge sort algorithm
def merge_in_place(arr, start, mid, end):
# TO-DO
return arr
def merge_sort_in_place(arr, l, r):
# TO-DO
return arr
# STRETCH: implement the Timsort function below
# hint: check out https://github.com/python/cpython/blob/master/Objects/listsort.txt
def timsort(arr):
return arr
| true |
5b4b1cea5e01a539d288bde1bbc1ae264434f962 | farooqbutt548/Python-Path-Repo | /strings.py | 1,303 | 4.34375 | 4 | # Strings
# Simple String
'''string1 = ' this is 1st string, '
string2 = "this is 2nd string"
print(type(string1))
connect_string = string1+ " "+string2
print(connect_string)
# print("errer"+3) erreor
print('this is not error'+' ' + str(3))
print('this will print 3 times'*3 )'''
# f-string, string-formatting
'''f_name = 'farooq'
l_name = 'butt'
print(f'hello {f_name} {l_name} how are you.')
# string input via split method()
name, age,degree = input('enter your name, age & degree comma separated : ').split(',')
print(f'hello {name} your age is {age} & degree is {degree}.')
# string indexing
name_index = 'farooq butt'
print(name_index[1]) #2nd number char will print from left
print(name_index[-1]) #last char will print
print(name_index[2:6:1]) # string slicing [start:ending:step]
print(name_index[ : :-1]) # reverse string'''
# string exercice
# name in reversed order
'''name = input('enter your naem : ') ; print(name[::-1])'''
# string methods
'''word = 'abCdefgHijKlmnOpqRsTuvwXyz'
print(len(word)) # leangth of word
print(word.lower()) # for lower letters
print(word.upper()) # for upper letters
print(word.count('b')) # for count a letter in word
print(word.title()) # for first letter capital
print(word.center(80)) # for aligning text '''
| true |
8b8f9374e4084d763f3b4195f5be59c95deeea50 | Khepanha/Python_Bootcamp | /week01/ex/e07_calcul.py | 287 | 4.125 | 4 | total = 0
while True:
number = input("Enter a number: \n>> ")
if number == "exit":
break
else:
try:
number = int(number)
total += number
print("TOTAL: ",total)
except:
print("TOTAL: ",total)
| true |
faa5907d95f8ab25764f7dd6b0a05ef44f5e7f9b | rp764/untitled4 | /Python Object Orientation /OrientationCode.py | 1,348 | 4.40625 | 4 | # OBJECT ORIENTED PROGRAMMING
# INHERITANCE EXAMPLE CODE
class Polygon:
width_ = None
height_ = None
def set_values(self, width, height):
self.width_ = width
self.height_ = height
class Rectangle(Polygon):
def area(self):
return self.width_ * self.height_
class Triangle(Polygon):
def area(self):
return self.width_ * self.height_ / 2
# ENCAPSULATION EXAMPLE CODE
class Car:
def __init__(self, speed, color):
self.__speed = speed
self.__color = color
def set_speed(self, value):
self.__speed = value
def get_speed(self):
return self.__speed
def get_color(self):
return self.__color
def set_color(self, value):
self.__color = value
audi = Car(200, 'red')
honda = Car(250, 'white')
audi.set_speed(400)
# ABSTRACT EXAMPLE CODE
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self): pass
@abstractmethod
def perimeter(self): pass
class Square(Shape, ABC):
def __init__(self, side):
self.__side = side
def area(self):
return self.__side * self.__side
def perimeter(self):
return 4 * self.__side
# POLYMORPHISM EXAMPLE CODE OVERWRITING VARIABLE
class Parent:
name = "Bob"
class Child(Parent):
pass
obj = Child()
| true |
1a057628c822895bf6e506846fb5fc7de0e10184 | giovannyortegon/holbertonschool-machine_learning | /supervised_learning/0x07-cnn/1-pool_forward.py | 1,717 | 4.125 | 4 | #!/usr/bin/env python3
""" Pooling """
import numpy as np
def pool_forward(A_prev, kernel_shape, stride=(1, 1), mode='max'):
""" pool - performs pooling on images
Args:
A_prev is a numpy.ndarray of shape (m, h_prev, w_prev, c_prev)
containing the output of the previous layer.
m is the number of examples
h_prev is the height of the previous layer
w_prev is the width of the previous layer
c_prev is the number of channels in the previous layer
kernel_shape is a tuple of (kh, kw) containing the size of
the kernel for the pooling.
kh is the kernel height
kw is the kernel width
stride is a tuple of (sh, sw) containing the strides for the pooling
sh is the stride for the height.
sw is the stride for the width.
mode is a string containing either max or avg, indicating whether
to perform maximum or average pooling, respectively.
Returns:
the output of the pooling layer.
"""
m, h_prev, w_prev, c_prev = A_prev.shape
kh, kw = kernel_shape
sh, sw = stride
pool_h = int((h_prev - kh) / sh) + 1
pool_w = int((w_prev - kw) / sw) + 1
pool = np.zeros((m, pool_h, pool_w, c_prev))
for i in range(pool_h):
for j in range(pool_w):
slide_img = A_prev[:, i * sh:i * sh + kh,
j * sw:j * sw + kw]
if mode == 'max':
pool[:, i, j] = np.max(np.max(slide_img, axis=1), axis=1)
elif mode == 'avg':
pool[:, i, j] = np.mean(np.mean(slide_img, axis=1), axis=1)
return pool
| true |
e97603a1bf321aaede95c36998fe3c780b94ef84 | giovannyortegon/holbertonschool-machine_learning | /math/0x00-linear_algebra/3-flip_me_over.py | 551 | 4.25 | 4 | #!/usr/bin/env python3
""" the transpose of a 2D matrix """
matrix_shape = __import__("2-size_me_please").matrix_shape
def matrix_transpose(matrix):
""" matrix_transpose - the transpose of a 2D matrix
mat1: Input first matrix
mat2: Input second matrix
Return: New matrix
"""
m_length = matrix_shape(matrix)
new_matrix = [[0 for i in range(m_length[0])] for j in range(m_length[1])]
for i in range(m_length[0]):
for j in range(0, m_length[1]):
new_matrix[j][i] = matrix[i][j]
return new_matrix
| true |
192d8c2fa81b0f8469deb319622e8962d4e1273a | EachenKuang/LeetCode | /code/202#Happy Number.py | 2,457 | 4.125 | 4 | # First of all, it is easy to argue that starting from a number I, if some value - say a - appears again during the process after k steps, the initial number I cannot be a happy number. Because a will continuously become a after every k steps.
# Therefore, as long as we can show that there is a loop after running the process continuously, the number is not a happy number.
# There is another detail not clarified yet: For any non-happy number, will it definitely end up with a loop during the process? This is important, because it is possible for a non-happy number to follow the process endlessly while having no loop.
# To show that a non-happy number will definitely generate a loop, we only need to show that for any non-happy number, all outcomes during the process are bounded by some large but finite integer N. If all outcomes can only be in a finite set (2,N], and since there are infinitely many outcomes for a non-happy number, there has to be at least one duplicate, meaning a loop!
# Suppose after a couple of processes, we end up with a large outcome O1 with D digits where D is kind of large, say D>=4, i.e., O1 > 999 (If we cannot even reach such a large outcome, it means all outcomes are bounded by 999 ==> loop exists). We can easily see that after processing O1, the new outcome O2 can be at most 9^2*D < 100D, meaning that O2 can have at most 2+d(D) digits, where d(D) is the number of digits D have. It is obvious that 2+d(D) < D. We can further argue that O1 is the maximum (or boundary) of all outcomes afterwards. This can be shown by contradictory: Suppose after some steps, we reach another large number O3 > O1. This means we process on some number W <= 999 that yields O3. However, this cannot happen because the outcome of W can be at most 9^2*3 < 300 < O1.
# https://leetcode.com/problems/happy-number/description/
class Solution(object):
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
def calculateSum(n):
sum = 0
while(n):
tmp = n % 10
sum += tmp * tmp
n //= 10
return sum;
slow = fast = n;
while True:
slow = calculateSum(slow);
fast = calculateSum(fast);
fast = calculateSum(fast);
if slow==fast:
break
if slow == 1:
return True
else:
return False; | true |
4c599c9f902ed403eb88fa39b61657003917751d | Billoncho/EncoderDecoder | /EncoderDecoder.py | 1,469 | 4.5625 | 5 | # EncoderDecoder.py
# Billy Ridgeway
# Encode or decode your messages by shifting the ASCII characters.
message = input("Enter a message to encode or decode: ") # Prompt the user for a message to encode/decode.
message = message.upper() # Convert the string of letters to upper case.
output = "" # Sets output to an empty string.
for letter in message: # A loop to convert each letter in the message.
if letter.isupper(): # Checks to see if the letter is already in upper case.
value = ord(letter) + 13 # Converts the letter to it's corresponding ASCII number.
letter = chr(value) # Converts an ASCII number to a letter.
if not letter.isupper(): # This loop runs to ensure that the ASCII number hasn't shifted too far and gone past 'Z'.
value -= 26 # This subtracts 26 from the number to ensure it's in the range from 'A' to 'Z'.
letter = chr(value) # Converts the ASCII value to a letter.
output += letter # Add the letter to the output string.
print("Output message: ", output) # Prints the encoded/decoded message to the screen.
| true |
66ca9d86e2fc88d1402c31fbc1078c4cf9b262b3 | Sophon96/2021-software-general-homework | /lesson_2_1.py | 1,443 | 4.21875 | 4 | # A student has taken 3 tests in a class, and wants to know their current grade
# (which is only calculated by these tests).
# Ask the user to input all three of the test scores for the student, one by one.
# The program should then calculate the average test score (average is adding all three
# test scores together then dividing by 3), and then print the student's letter grade
# (as well as the average score as a number).
if __name__ == '__main__':
import decimal
import sys
import statistics
endings = ['st', 'nd', 'rd']
scores = []
for i in range(3):
try:
scores.append(decimal.Decimal(input(f"Please input your {i+1}{endings[i]} score: ")))
except decimal.InvalidOperation:
print("The score must be a valid Decimal!", file=sys.stderr)
exit(1)
avg = statistics.mean(scores)
lgs = {decimal.Decimal(65): 'F',
decimal.Decimal(66): 'D',
decimal.Decimal(69): 'D+',
decimal.Decimal(72): 'C-',
decimal.Decimal(76): 'C',
decimal.Decimal(79): 'C+',
decimal.Decimal(82): 'B-',
decimal.Decimal(86): 'B',
decimal.Decimal(89): 'B+',
decimal.Decimal(92): 'A-',
decimal.Decimal(96): 'A',
decimal.Decimal(100): 'A+'}
for k in lgs:
if avg < k:
break
print(f"Your average score is {avg}, which is a {lgs[k]}")
| true |
a2a18544685a691a7b072d14b04f7b2f1e6ddca7 | SebastianoFazzino/Python-for-Everybody-Specialization-by-University-of-Michigan | /Word_coutnter_using_dictionaries.py | 461 | 4.125 | 4 | #how to find the most common word in a text:
openfile = input("Enter file name: ")
file = open(openfile)
counts = dict()
for line in file:
words = line.split()
for word in words:
counts[word] = counts.get(word,0) + 1
bigcount = None
bigword = None
for word, count in counts.items():
if bigcount is None or count > bigcount:
bigword = word
bigcount = count
print(bigword,bigcount)
| true |
5cd45a7e4fee6f5440f4126b64ae8e80730e9ae9 | SebastianoFazzino/Python-for-Everybody-Specialization-by-University-of-Michigan | /Conditional Statements.py | 907 | 4.25 | 4 | #Calculating the score
score = input("Enter Score: ")
try:
score = float(score)
if score > 0.0 and score < 0.6:
print ("F")
elif score >= 0.6 and score <= 0.69:
print("D")
elif score >= 0.7 and score <= 0.79:
print ("C")
elif score >= 0.8 and score <= 0.89:
print("B")
elif score >=0.9 and score <=1.0:
print("A")
else:
print("Score value must be between 0.0 and 1.0")
except:
print("wrong input!")
#calculating the pay
hrs = input("Enter Hours:")
hr_rate = input("Enter Pay Rate:")
try:
hrs = float(hrs)
hr_rate = float(hr_rate)
except:
print("Please enter numeric input!")
quit()
extratime = hrs - 40
if hrs > 40:
pay = 40 * hr_rate + extratime * 15.75
elif hrs > 1 and hrs <= 40:
pay = hrs * hr_rate
print(pay)
| true |
e3e14d6b50222fddaea52f6a1a9012daf1654cdb | NakonechnyiMykhail/PyGameStart | /lesson26/repeat.py | 505 | 4.1875 | 4 | # functions without args without return
# 0. import random # library
# 1. create a function with name "randomizer"
# 2. create a varieble with name "data" = 'your text at 6-10 words'
# or "lorem ipsum..."
# 3. select var "data" with text and with random method print
# with for-loop 20 times only ONE character
data = 'Antidisestablishmentarianism'
# randint() Returns a random number between the given range
# choice() Returns a random element from the given sequence
# functions with args
| true |
e128dc2672cbf6b6b4dee1c1537884ffcc9dc86a | ridhim-art/practice_list2.py | /tuple_set_dictionary/example_contacts.py | 707 | 4.1875 | 4 | #program where user can add contacta for contact book
contacts = {'help': 100}
print('your temp contact book')
while True:
name = input("=> enter contact name :")
if name:
if name in contacts:
print('=> contact found')
print(f'=> {name} :{contacts[name]}')
else:
print('=> contact not found')
update = input('>> do you want to add the contact(y/n)?')
if update.lower() == 'y':
number = input(f'>> enter contact number for {name}')
contacts[name] = number
print(f'=> contact updated for {name}')
else:
print('closing contact book')
break
| true |
d9e76d1f7a25dfa8d4e160ce4a1f89fcd8eaf704 | subbuinti/python_practice | /loopControlSystem/HallowDaimond.py | 865 | 4.25 | 4 | # Python 3 program to print a hallow diamond pattern given N number of rows
alphabets = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q',
'R', 'S', 'T', 'U','V', 'W', 'X', 'Y', 'Z']
# Diamond array
diamond = []
rows = -1
# Prompt user to enter number of rows
while rows < 1 or rows > 26:
rows = int(input())
for i in range(0, rows):
# Add letters to the diamond
diamond.append("")
for j in range(0, rows - i):
diamond[i] += " "
diamond[i] += alphabets[i];
if alphabets[i] != 'A':
# Put spaces between letters
for j in range(0, 2 * i - 1):
diamond[i] += " "
diamond[i] += alphabets[i]
# Print the first part of the diamond
print(diamond[i])
# Print the second part of the diamond
for i in reversed(range(0, rows - 1)):
print(diamond[i]) | true |
915ca9bbea032f07b0adc06a94f3409c6d7e3bad | lokeshsharma596/Base_Code | /Pyhton/Lambda_Map_Filter.py | 2,346 | 4.375 | 4 | # Lambda Function
# any no of arguments but only one statement
# single line ,anoymous,no def,no return
# example-1
def sum(a, b, c): return a+b+c
print(sum(4, 5, 1))
add=lambda a,b,c: a+b+c
print(add(4, 5, 1))
# example-2
cube=lambda n:n**3
print(cube(4))
# Map Function
# Atleast Two arguments :function and an iterable
# Iterable(list,string,dictionary,set,tuple)
# runs the lambda for each value in iterable and return a map object which,
# can be converted into any data structure
# example-1
nums = [1, 2, 3, 4, 5]
def sq(n):
return n*n
square = list(map(sq, nums))
print(square)
# example-2
nums = [1, 2, 3, 4, 5]
square = list(map(lambda x: x**x, nums))
print(square)
# example-3
people = ["lokesh", "sharma", "python", "developer"]
up = list(map(lambda x: x.upper(), people))
print(up)
# example-4
names = [
{'first': 'lokesh', 'last': 'sharma'},
{'first': 'ravi', 'last': 'sharma'},
{'first': 'jiu', 'last': 'sharma'}
]
first_names = list(map(lambda x: x['first'], names))
print(first_names)
# Filter
# There is a lambda for each value in iterable
# return only values which are true to lambda
# example-1
names = ['anthony', 'penny', 'austing', 'boy', 'amio']
a = list(filter(lambda x: x[0] == 'a', names))
print(a)
# example-2
#filter inactive users
users = [
{"username": 'samuel', "tweets": ["i love cake", "i am good"]},
{"username": 'andy', "tweets": []},
{"username": 'kumal', "tweets": ["India", "Python"]},
{"username": 'sam', "tweets": []},
{"username": 'lokesh', "tweets": ["i am good"]},
]
inactive_users = list(filter(lambda a:not a['tweets'], users))
print(inactive_users)
#example-3
#filter inactive users with just username in uppercase
inactive_users=list(map(lambda x: x["username"].upper(),
filter(lambda a:not a['tweets'], users)))
print(inactive_users)
#example-4
#return a new list with the string "your name is" + name
# but only if length of name is less than five
names=['lokesh','lassie','bob','to']
new=list(map(lambda name:f"your name is {name}",
filter(lambda x:len(x)>4,names)))
print(new)
#List Comprehension
# for example 2
inactive_users=[user for user in users if not user["tweets"]]
print(inactive_users)
# for example 3
inactive_users=[user["username"].upper() for user in users if not user["tweets"]]
print(inactive_users) | true |
b201d29f539242f9295b7826df8cd4834b173a02 | gillc0045/CTI110 | /Module3/CTI110_M3HW2_bodyMassIndex_gillc0045.py | 502 | 4.4375 | 4 | # Write a program to calculate a person's body mass index (BMI).
# 12 Jun 2017
# CTI 110 - M3HW2 -- Body Mass Index
# Calvin Gill
weight = float(input("Enter the person's weight (pounds): "))
height = float(input("Enter the person's height (inches): "))
bmi = weight*(703/height**2)
print("The person's BMI value is ",bmi)
if bmi > 25:
print('The person is overweight')
elif bmi < 18.5:
print('The person is underweight')
else:
print('The person is at optimal weight')
| true |
f74f8032c81b88479718b6bd9e861f1bb04c77c1 | HussainWaseem/Learning-Python-for-Data-Analysis | /NewtonRaphson.py | 1,625 | 4.1875 | 4 | ''' Newton Raphson '''
# Exhaustive Enum = In this we were using guesses but we were going all the way from beginning to end.
# And we were only looking for correct or wrong answers. No approximation.
# Approximation = It was an improvement over Exhaustive Enum in a way that now we can make more correct guesses
# and can give an approximate answers to those which are not representable.
# But due to correctness, we have to take a very small epsilon and steps.
# No. of guesses we made was in the order of answer/steps, it took a lot of time.
# Bisection Search = It was a massive improvement over both of the above in terms of speed.
# We were approximating as well as making smart guesses.
# We were at each guess looking for the correct search bound by leaving half of the range.
# Newton Raphson Method = Well it tells us that if we improve our guesses in each iteration ,we might reach our
# goal much earlier, even earlier than bisection search.
# we were using Approximation, but our steps were not in the order of epsilon**2.
# But we were making guesses which were more smart and calculated.
''' Square root using Newton Paphson Method '''
x = int(input("Give your Integer : "))
answer = x/2
epsilon = 0.01
guess = 0
while abs(answer**2 - x) >= epsilon:
answer = answer - ((answer**2)-x)/(2*answer) # this is newton's betterement method of guess for Sq Root.
guess += 1
print("Number of guesses made:",guess)
print("Approximate Sq root is:",answer)
# If I remove this betterment of guess method, and set the answer to increment of epsilon and run this program.
# then this program will run too slow!!
| true |
026139b2e0beed35054a503d4c308c5450e6684b | HussainWaseem/Learning-Python-for-Data-Analysis | /FractionsToBinary.py | 1,695 | 4.3125 | 4 | ''' Fractions to Binary '''
# Method ->> Fractions -> decimals using 2**x multiplication -> Then converting decimal to binary.
# -> Then dividing the resultant binary by 2**x (Or right shift x times) to get the outcome.
num = float(input("Give your fraction : ")) # we have to take a float.
x = 0
if num < 0:
num = abs(num)
isNeg = True
elif num > 0:
isPos = True
if num == 0:
isZero = True
while (num - int(num) != 0): # Checking if my num is not a whole number keep multiplying it with power of 2.
num = num * (2**x)
x += 1
print(num) # printing the number too to see what whole number we get at the end of loop.
result = 0
mylist = [] # We take an empty list.
while num > 0:
result = int((num%2)) # we take int, because num was in float. But we want remainders/bits in either 0/1.
print(result) # Printing the binaries too.
mylist.append(str(result)) # creating a string list (Why?). But all the bits are from back to front order
# Since modulo gives bits from back to front.
num = num // 2
mylist.reverse() # reversing the list to get correct binary order.
result = "".join(mylist) # we had to use join() thats why we took string list. (Answer to Why!)
result = int(result) # Now the result was in string taken out from join(). So we convert it into int.
result = result * (10**-x) # Now finally right shifting it the number of times we multiplied by pow of 2.
if isNeg == True:
print("Binary is",-result)
elif isPos == True:
print("Binary is",result)
elif isZero == True:
result = 0
print("Binary is",result)
| true |
346c05201be6379aea4801d2ad28d3b495258b4a | HussainWaseem/Learning-Python-for-Data-Analysis | /Tuples.py | 2,673 | 4.40625 | 4 | ''' Tuples '''
# Immutables.
# defining tuples = With braces or without braces
t = (1,2,'l',True)
print(t)
g = 1,2,'l',False
print(g)
# Tuples are Squences (just like Strings and lists) = So they have 6 properties = len(),indexing,slicing, concatenation,
# iterable and membership test (in and not in)
# Range object is also sequence but it doesnot follow concatenation.
print(t[3])
print(t[1:2]) # prints (2,) This comma denotes that it is a tuple and not just an int object.
print(t[:])
# Assignment doesnot works for tuples. You can't change tuples
t = (1,)
h = 1,
print(t,h)
''' Iteration over Tuples and Nested Tuples '''
''' Write a Program that gets data in the form of nested tuples. Each nested tuple has an integer at index 0 and string
at index 1.
Gather all the numbers in one new tuple and strings in another new tuple.
Return maxnumber, minnumber and number of unique words. '''
def getData(t):
num = ()
words = ()
for i in t:
num = num + (i[0],) # num is a tuple. (i[0],) is a singleton tuple. We concatenate.
if i[1] not in words: # taking only unique words
words = words + (i[1],)
min_number = min(num)
max_number = max(num)
unique_words = len(words)
return (min_number,max_number,unique_words)
data = ((1,"Hello"),(2,"World"),(15,"Hello"))
print(getData(data))
#----------------------------------------------------------------------------------------
x = (1, 2, (3, 'John', 4),'hi')
# Whenever you slice something out of a tuple, the resultant is always tuple.
# Unlike indexing, where the resultant may be any other type.'
y = x[0:-1]
z = x[0:1]
print(y)
print(z)
print(type(y),type(z))
# Also you can multi index a string inside a tuple/list and can access its individual Character.
print(x[-1][-1])
print(type(x[-1][-1]))
#-----------------------------------------------------------------------------------
''' Write a procedure called oddTuples, which takes a tuple as input, and returns a new tuple as output,
where every other element of the input tuple is copied, starting with the first one.
So if test is the tuple ('I', 'am', 'a', 'test', 'tuple'),
then evaluating oddTuples on this input would return the tuple ('I', 'a', 'tuple'). '''
def oddTuples(t):
t_new = ()
count = 0
for i in t:
if count % 2 == 0: # Here I do for even because indexing starts from 0. Odd elements are indexed even.
t_new = t_new + (t[count],) # concatenation of strings.
else:
pass
count +=1
return t_new
test = ('I', 'am', 'a', 'test', 'tuple')
print(oddTuples(test))
| true |
85bdb20c063b623b3ba8b576096318804c70b212 | sakar123/Python-Assignments | /Question24.py | 261 | 4.3125 | 4 | """24. Write a Python program to clone or copy a list."""
def clone_list(given_list):
new_list = []
for i in given_list:
new_list.append(i)
return new_list
print(clone_list([1, 2, 3, 4, 5]))
print(clone_list([(1, 2), ('hello', 'ji')]))
| true |
cc02f947a004d1c929d2a1ca6a79808909ed7d02 | sakar123/Python-Assignments | /Question37.py | 410 | 4.1875 | 4 | """37. Write a Python program to multiply all the items in a dictionary."""
def prod_dicts(dict1):
list_of_values = dict1.values()
product_of_values = 1
for i in list_of_values:
product_of_values = i * product_of_values
return product_of_values
print(prod_dicts({1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12: 144, 13: 169, 14: 196, 15: 225}))
| true |
69c3484772644518a3245f6a925858232fa066ab | ngongongongo/Python-for-beginners | /Chapter 1 - Python Basics/1.8-Practice.py | 2,669 | 4.4375 | 4 | #1.8 Practice
#----------------------------------------
#Question 1
#Prompt the computer to print from 1 to 10 using loop
#Ask user if he/she wants to do it again using loop
#Question 2
#Write a rock-paper-scissor game
#The winning condition is either the player or the computer win 3 times first
#Hint: import random
#----------------------------------------
#Solution 1
print("Question 1\n")
answers = 'y'
while answers == 'y':
for i in range(1,11):
print (i)
i += 1
answers = input("Do you want to do it again (y/n): ").lower()
#Solution 2
import random
loop = 'y'
playerScore = computerScore = 0
playerChoice = computerChoice =0
playerDecision = computerDecision = 'INVALID ENTRY'
print("\nQuestion 2\n")
while loop == 'y': #play multiple games
playerScore = computerScore = 0
print ("\nGame Score is now ", playerScore, " Player, ", computerScore, " Computer") #Scores Tracker
while playerScore < 3 and computerScore < 3:
print("\n1 is ROCK, 2 is PAPER, or 3 is SCISSOR")
playerChoice = int(input("PLease choose an option: ")) #Get inputs from the user
computerChoice = random.randrange(1,4) #Generate a random decision for the computer
while playerDecision == "INVALID ENTRY":
if playerChoice == 1: #Convert player's decisions
playerDecision = "ROCK"
elif playerChoice == 2:
playerDecision = "PAPER"
elif playerChoice == 3:
playerDecision = "SCISSOR"
else:
playerDecision = "INVALID ENTRY"
if computerChoice == 1: #Convert computer's decisions
computerDecision = "ROCK"
elif computerChoice == 2:
computerDecision = "PAPER"
else:
computerDecision = "SCISSOR"
print ("\nPlayer chose ", playerDecision)
print ("Computer chose ", computerDecision)
if (computerChoice % 3) + 1 == playerChoice: #Win - Lose conditions
print("Player wins")
playerScore += 1
elif (playerChoice % 3) + 1 == computerChoice:
print("Computer wins")
computerScore += 1
else: print ("Draw")
print ("\nGame Score is now ", playerScore, " Player, ", computerScore, " Computer") #Scores Tracker
if playerScore == 3:
print("Player wins with 3 scores")
else:
print("Computer wins with 3 scores")
loop = input("\nDo you want to play another game: ").lower() | true |
0c5c216e024271752c5cf2cebddfa5d2e70d846c | jingyi-stats/-python- | /python_syntax.py | 865 | 4.1875 | 4 | # Python syntax 语法
# print absolute value of an integer
a = 100
if a >= 0:
print(a)
else:
print(-a)
# print if the input age is adult or not
year = input("Please enter your birth year: ")
print(2020 - int(year))
a = int(2020 - int(year))
if a >= 18:
print("Adult")
else:
print("underage")
# print what to do next
condition = input("What can I help you with?")
if condition == "hungry":
print("Please eat.")
elif condition == "tired":
print("Get some rest.")
elif condition == "sick":
print("Go to a doctor.")
elif condition == "chill":
print("Go to study.")
else:
print("Sorry, I don\'t understand \"your condition\".")
print('I\'m learning\nPython.')
print('\\\n\\')
print('\\\t\\')
print(r'\\\t\\')
print('''line1
line2
line3''')
# -*- coding: utf-8 -*-
print(r'''hello,\n
world''')
True
False
3 > 2
3 > 5
| true |
b0866402b38328d8070e078a7acef16b8e9fb7eb | Dhiraj-tech/Python-Lab-Exercise | /greater,smallest and odd number among them in list (user input in a list).py | 400 | 4.21875 | 4 | #WAP to take a user input of a list consist of ten numbers and find (1)greater no among the list (2)smaller no among the list (3) list of a odd number
list=[]
odd=0
for i in range(10):
num=int(input("enter a number"))
list.append(num)
print("minimum no among them:",min(list))
print("maximum no among them:",max(list))
odd=[num for num in list if num%2==1]
print("odd no among them is:",odd) | true |
b96f2252a44943ccef0b5cd6950479cf67241857 | Dhiraj-tech/Python-Lab-Exercise | /(4) define a function and show the multiples of 3 and 5.py | 231 | 4.34375 | 4 | #write a function that returns a sum of multiples of 3 and 5 between 0 and limit(parameter)
def function():
for i in range(21):
sum=0
if i%3==0 or i%5==0:
sum=sum+i
print (sum)
function() | true |
a443b4acf86964757b39b1b912c93259629ca1b4 | ButtonWalker/Crash_Course | /4_Exercise2.py | 455 | 4.125 | 4 | for value in range(1, 21):
print(value)
numbers = []
for value in range(1,1001):
numbers = value
print(numbers)
digits = range(1, 1000001)
print(min(digits))
print(max(digits))
print(sum(digits))
# odd numbers
for value in range(1,21,2):
print(value)
for value in range(3, 30, 3):
print(value)
cubes = []
for value in range(1, 11):
cubes.append(value**3)
print(cubes)
cubes = [value**3 for value in range(1,11)]
print(cubes) | true |
74bff2e14dc504862c597880f6aeec91e3406fde | abhikot1996/Python-Python-All-In-One-Mastery-From-Beginner-to-AdvanceEasy-Way- | /Python-Python-All-In-One-Mastery-From-Beginner-to-AdvanceEasy-Way-/PracticeWebExersicesProgram.py | 965 | 4.21875 | 4 | # 1) Program to print twinkle twinkle little star poem
#print("""Twinkle, twinkle, little star,\n\t
#How I wonder what you are!\n
#\t\tUp above the world so high,\n
#\t\tLike a diamond in the sky.\n
#Twinkle, twinkle, little star,\n
#\tHow I wonder what you are!)
#""")
# 2) Program to print version of python installed on system
# import sys
# print("Python version")
# print (sys.version)
# print("Version info.")
# print (sys.version_info)
# 3) Program to print current date and time
# import datetime
# now = datetime.datetime.now()
# print ("Current date and time : ")
# print (now.strftime("%Y-%m-%d %H:%M:%S"))
# 4) Program to print Area of circle
# radius = float(input("Enter radius:"))
# print(3.14*radius**2)
# 5) Write a Python program which accepts the user's first and last name and
# print them in reverse order with a space between them
# fname =input("Enter first name: ")
# lname = input("Enter last name: ")
# print(lname + " " + fname)
| true |
fc243f4ddc5a2da7b2385e7a09a2780f1f964d2a | carmelobuglisi/programming-basics | /projects/m1/005-units-of-time-again/solutions/pietrorosano/solution_005-againUnitsOfTime.py | 998 | 4.40625 | 4 | # In this exercise you will reverse the process described in Exercise 24. Develop a program that begins by reading a number of seconds from the user. Then your program should display the equivalent amount of time in the form D:HH:MM:SS, where D, HH, MM, and SS represent days, hours, minutes and seconds respectively. The hours, minutes and seconds should all be formatted so that they occupy exactly two digits. Use your research skills determine what additional character needs to be included in the format specifier so that leading zeros are used instead of leading spaces when a number is formatted to a particular width.
print("\nSTART PROGRAM")
print("------------------")
print("\nDays")
days = int(input())
print("\nHours")
hours = int(input())
print("\nMinutes")
minutes = int(input())
print("\nSeconds")
seconds = int(input())
print("\nTime...")
# print(str(days)+":"+str(hours)+":"+str(minutes)+":"+str(seconds))
print("{:02d}:{:02d}:{:02d}:{:02d}".format(days, hours, minutes, seconds)) | true |
90f62a8ec5f6cee9e9d88f5bfb8f36599ca33616 | a3X3k/Competitive-programing-hacktoberfest-2021 | /CodeWars/Calculating with Functions.py | 1,540 | 4.34375 | 4 | '''
5 kyu Calculating with Functions
https://www.codewars.com/kata/525f3eda17c7cd9f9e000b39/train/python
This time we want to write calculations using functions and get the results. Let's have a look at some examples:
seven(times(five())) # must return 35
four(plus(nine())) # must return 13
eight(minus(three())) # must return 5
six(divided_by(two())) # must return 3
Requirements:
There must be a function for each number from 0 ("zero") to 9 ("nine")
There must be a function for each of the following mathematical operations: plus, minus, times, dividedBy (divided_by in Ruby and Python)
Each calculation consist of exactly one operation and two numbers
The most outer function represents the left operand, the most inner function represents the right operand
Divison should be integer division. For example, this should return 2, not 2.666666...:
eight(divided_by(three()))
'''
def zero(f = None): return 0 if not f else f(0)
def one(f = None): return 1 if not f else f(1)
def two(f = None): return 2 if not f else f(2)
def three(f = None): return 3 if not f else f(3)
def four(f = None): return 4 if not f else f(4)
def five(f = None): return 5 if not f else f(5)
def six(f = None): return 6 if not f else f(6)
def seven(f = None): return 7 if not f else f(7)
def eight(f = None): return 8 if not f else f(8)
def nine(f = None): return 9 if not f else f(9)
def plus(y): return lambda x: x+y
def minus(y): return lambda x: x-y
def times(y): return lambda x: x*y
def divided_by(y): return lambda x: int(x/y) | true |
481537d5d715298b4f112158bf257dd23967c5d5 | a3X3k/Competitive-programing-hacktoberfest-2021 | /CodeWars/Build Tower.py | 939 | 4.125 | 4 | '''
6 kyu Build Tower
https://www.codewars.com/kata/576757b1df89ecf5bd00073b/train/python
Build Tower
Build Tower by the following given argument:
number of floors (integer and always greater than 0).
Tower block is represented as *
Python: return a list;
JavaScript: returns an Array;
C#: returns a string[];
PHP: returns an array;
C++: returns a vector<string>;
Haskell: returns a [String];
Ruby: returns an Array;
Lua: returns a Table;
Have fun!
for example, a tower of 3 floors looks like below
[
' * ',
' *** ',
'*****'
]
and a tower of 6 floors looks like below
[
' * ',
' *** ',
' ***** ',
' ******* ',
' ********* ',
'***********'
]
Go challenge Build Tower Advanced once you have finished this :)
https://www.codewars.com/kata/57675f3dedc6f728ee000256
'''
def tower_builder(n):
return [("*" * (i*2-1)).center(n*2-1) for i in range(1, n+1)] | true |
cb1a541b30cec2a374ec146c53fcab3b074fbfdd | Jsmalriat/python_projects | /dice_roll_gen/dice_roll.py | 2,683 | 4.25 | 4 | # __author__ = Jonah Malriat
# __contact__ = tuf73590@gmail.com
# __date__ = 10/11/2019
# __descript__ = This program takes user-input to determine the amount of times two dice are rolled.
# The program then adds these two dice rolls for every time they were rolled and outputs how many
# times each number 2 - 12 was rolled and the percentage it was rolled. It then compares this percentage
# to the probability and finds the difference between the two values.
import random
def greeting():
print('=> Welcome to the random dice-roll generator!')
def num_iterations():
iter = input('=> How many times would you like to roll the dice? ')
return iter
def first_roll():
first_roll = random.randint(1, 6)
return first_roll
def second_roll():
second_roll = random.randint(1, 6)
return second_roll
def roller(iter):
roll_list = []
for i in range(0, iter):
roll_list.append(first_roll() + second_roll())
return roll_list
def num_of_value(roll_list, num):
x = 0
for i in roll_list:
if i == num:
x += 1
return x
def perc_of_value(roll_list, num):
y = 0
x = num_of_value(roll_list, num)
for i in roll_list:
y += 1
x /= y
x *= 100
return round(x, 2)
def expected_prob(num):
if num == 2:
x = (1 / 36) * 100
elif num == 3:
x = (1 / 18) * 100
elif num == 4:
x = (1 / 12) * 100
elif num == 5:
x = (1 / 9) * 100
elif num == 6:
x = (5 / 36) * 100
elif num == 7:
x = (1 / 6) * 100
elif num == 8:
x = (5 / 36) * 100
elif num == 9:
x = (1 / 9) * 100
elif num == 10:
x = (1 / 12) * 100
elif num == 11:
x = (1 / 18) * 100
elif num == 12:
x = (1 / 36) * 100
return round(x, 2)
def diff_in_prob(roll_list, x):
x = abs(perc_of_value(roll_list, x) - expected_prob(x))
return round(x, 2)
def print_iter(iter):
print(f"Number of iterations = {iter}")
def print_key(a, b, c, d, e):
print('{:^14}'.format(a), '{:^14}'.format(b), '{:^14}'.format(c), '{:^14}'.format(d), '{:^14}'.format(e))
def print_table(a, b, c, d, e):
print('{:^14}'.format(a), '{:^14}'.format(b), '{:^14}'.format(f"{c}%"), '{:^14}'.format(f"{d}%"), '{:^14}'.format(f"{e}%"))
def table_maker(roll_list):
x = 1
while x < 12:
x += 1
print_table(f"{x}", num_of_value(roll_list, x), perc_of_value(roll_list, x), expected_prob(x), diff_in_prob(roll_list, x))
def main():
greeting()
iter = int(num_iterations())
roll_list = roller(iter)
print_iter(iter)
print_key('Number', 'Times Rolled', 'Percentage', 'Expected', 'Difference')
table_maker(roll_list)
if __name__ == '__main__':
main() | true |
d9630b46886066ea9c30426a08e2edb4f4c41bd3 | tomekregulski/python-practice | /logic/bouncer.py | 276 | 4.125 | 4 | age = input("How old are you: ")
if age:
age = int(age)
if age >= 21:
print("You are good to enter and you can drink!")
elif age >= 18:
print("You can entger, but you need a wristband!")
else:
print("Sorry, you can't come in :(")
else:
print("Please enter an age!") | true |
29e7b459ca79807dc28ea3919a14347de30e5a34 | vanceb/STEM_Python_Crypto | /Session3/decrypt.py | 1,127 | 4.15625 | 4 | ##############################
# Caesar Cypher - Decrypt
##############################
# Define the alphabet that we are going to encode
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
# Define variables to hold our message, the key and the translated message
message = 'This is secret'
key = 20
translated = ''
# Change the key to enable decryption
key = len(LETTERS) - key
# Convert the message to uppercase
message = message.upper()
# Repetatively do something for every symbol in the message
for symbol in message:
# See if the current symbol is in the alphabet we defined earlier
if symbol in LETTERS:
# if it is then we get a number that represents its position
num = LETTERS.find(symbol)
# change the number based on the key
num = (num + key) % len(LETTERS)
# get the letter from the changed number
translated = translated + LETTERS[num]
else:
# the symbol is not in the alphabet so just add it unchanged
translated = translated + symbol
# we have now been through every letter in the message so we can print the translated version
print(translated)
| true |
5eb82c0b75ecd9125a10149ac70f7e9facbbf5c8 | carlhinderer/python-exercises | /reddit-beginner-exercises/ex03.py | 1,357 | 4.59375 | 5 | # Exercise 3
#
#
# [PROJECT] Pythagorean Triples Checker
#
# BACKGROUND INFORMATION
#
# If you do not know how basic right triangles work, read this article on wikipedia.
#
# MAIN GOAL
#
# Create a program that allows the user to input the sides of any triangle, and then return whether the triangle is a Pythagorean
# Triple or not.
#
# SUBGOALS
#
# If your program requires users to input the sides in a specific order, change the coding so the user can type in the sides
# in any order. Remember, the hypotenuse (c) is always the longest side.
#
# Loop the program so the user can use it more than once without having to restart the program.
def triplechecker():
a, b, c = promptforsides()
triple = checkfortriple(a, b, c)
printresult(triple)
def promptforsides():
a = promptforside()
b = promptforside()
c = promptforside()
return (a, b, c)
def promptforside():
side = None
while type(side) is not int:
try:
side = input('Enter the length of a side: ')
side = int(side)
except ValueError:
print('The side lengths must be integers.')
return side
def checkfortriple(a, b, c):
if a > c: a, c = c, a
if b > c: b, c = c, b
return (a ** 2 + b ** 2 == c ** 2)
def printresult(triple):
if triple:
print("Yes, it's a Pythagorean Triple!")
else:
print("Nope, it's not a Pythagorean Triple.")
triplechecker() | true |
81b6f41cf4da9ba055fa5b1efd3ba7b6993f04d0 | carlhinderer/python-exercises | /daily-coding-problems/problem057.py | 729 | 4.125 | 4 | # Problem 57
# Medium
# Asked by Amazon
#
# Given a string s and an integer k, break up the string into multiple lines such that
# each line has a length of k or less. You must break it up so that words don't break across
# lines. Each line has to have the maximum possible amount of words. If there's no way to
# break the text up, then return null.
#
# You can assume that there are no spaces at the ends of the string and that there is exactly one
# space between each word.
#
# For example, given the string "the quick brown fox jumps over the lazy dog" and k = 10, you
# should return: ["the quick", "brown fox", "jumps over", "the lazy", "dog"]. No string in the
# list has a length of more than 10.
# | true |
e8ec7c1c8e7edd373c1a2dd59a98cb8444317c3a | carlhinderer/python-exercises | /ctci/code/chapter01/src/palindrome_permutation.py | 769 | 4.3125 | 4 | #
# 1.4 Palindrome Permutation:
#
# Given a string, write a function to check if it is a permutation of a palindrome.
# A palindrome is a word or phrase that is the same forwards and backwards. A
# permutation is a rearrangement of letters. The palindrome does not need to be
# limited to just dictionary words.
#
# EXAMPLE Input: Tact Coa Output: True (permutations: "taco cat". "atco cta". etc.)
#
from collections import Counter
def palindrome_permutation(s):
no_whitespace = s.strip().replace(' ', '')
counts = Counter(no_whitespace)
odd_count = False
for pair in counts.items():
if pair[1] % 2 == 1:
if odd_count:
return False
else:
odd_count = True
return True | true |
8bc07815ab7a29e1aa5b472bddaff588fc405cfa | carlhinderer/python-exercises | /zhiwehu/src/ex007.py | 1,033 | 4.21875 | 4 | # Question 7
# Level 2
#
# Question:
# Write a program which takes 2 digits, X,Y as input and generates a 2-dimensional array. The element value in
# the i-th row and j-th column of the array should be i*j.
#
# Note: i=0,1.., X-1; j=0,1,¡Y-1.
#
# Example:
# Suppose the following inputs are given to the program:
# 3,5
# Then, the output of the program should be:
# [[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]]
#
# Hints:
# Note: In case of input data being supplied to the question, it should be assumed to be a console input in a
# comma-separated form.
def print_matrix():
dimensions = get_dimensions()
matrix = build_matrix(dimensions[0], dimensions[1])
print(matrix)
def get_dimensions():
dimensions = input('Enter the dimensions: ')
return list(map(int, dimensions.split(',')))
def build_matrix(x, y):
matrix = []
for i in range(x):
row = [i * j for j in range(y)]
matrix.append(row)
return matrix
if __name__ == '__main__':
print_matrix() | true |
322db8f52f43c93c7ee36440e6355b62f1054166 | schase15/Sprint-Challenge--Data-Structures-Python | /names/binary_search_tree.py | 2,965 | 4.4375 | 4 | # Utilize the BST from the hw assignment
# Only need contains and insert methods
class BSTNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
# Insert the given value into the tree
# Compare the input value against the node's value
# Check if the direction we need to go in has a node
# If not, wrap the value in a node and park it
# Otherwise, go back to step 1, but with the node in that spot
# This doesn't work if there is no root
def insert(self, value):
# Compare the input value with the value of the Node
if value < self.value:
# We need to go left
# If there is no child node to the left
if self.left is None:
# Create and park the new node
self.left = BSTNode(value)
# Otherwise there is already a child
else:
# Call the insert method to do this loop again, until we reach no child node
self.left.insert(value)
# If the input value is greater than or equal to we move to the right
else:
# See if there is no right child
if self.right is None:
# Wrap the value in BSTNode and park it
self.right = BSTNode(value)
# Otherwise there is a child node
else:
# Call the insert method to continue the loop until we find a node without a child
self.right.insert(value)
# Return True if the tree contains the value
# False if it does not
def contains(self, target):
# If the input value is equal to the node value, return true
# Base Case
if self.value == target:
return True
# Recursive cases: How do we move closer to the base case
# If the input value is greater than the node value, move to the right -> re-run method on right child node
elif self.value < target:
# Check if there is a next node to move to to continue the comparison
# If there is not then it is the end of the tree and there is no match, return False
if self.right is None:
return False
else:
# Call contains method on right child
# Eventually we will need to return a value
return self.right.contains(target)
# If the input value is less than the node value, move to the left -> re-run method on left child node
else:
# Check to see if there is a node to the left to move to
# If not then it is the end of the tree, return False
if self.left is None:
return False
else:
# Call contains method on left child
# Eventually we will need to return a value
return self.left.contains(target)
| true |
198ce51002296c632ee5522b2ab4f5dec317727d | wangtaodd/LeetCodeSolutions | /069. Sqrt.py | 586 | 4.25 | 4 | """
Implement int sqrt(int x).
Compute and return the square root of x.
x is guaranteed to be a non-negative integer.
Example 1:
Input: 4
Output: 2
Example 2:
Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since we want to return an integer, the decimal part will be truncated.
"""
class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
res = 0
for i in range(15,-1,-1):
if (res + (1 << i)) * (res + (1 << i)) <= x:
res += (1 << i)
return res | true |
44327cd41d09d206b171781dd89aae73376e2dec | wangtaodd/LeetCodeSolutions | /693. Binary Number with Alternating Bits.py | 770 | 4.25 | 4 | """
Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.
Example 1:
Input: 5
Output: True
Explanation:
The binary representation of 5 is: 101
Example 2:
Input: 7
Output: False
Explanation:
The binary representation of 7 is: 111.
Example 3:
Input: 11
Output: False
Explanation:
The binary representation of 11 is: 1011.
Example 4:
Input: 10
Output: True
Explanation:
The binary representation of 10 is: 1010.
"""
class Solution:
def hasAlternatingBits(self, n):
"""
:type n: int
:rtype: bool
"""
res = 1
n = n ^ (n >> 1)
while n > 1:
res = res & (n & 1)
n = n >> 1
return True if res == 1 else False
| true |
42b522c5d47b3f31c12398ee1304a62814dec748 | wangtaodd/LeetCodeSolutions | /530. Minimum Absolute Difference in BST.py | 902 | 4.1875 | 4 | """
Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.
Example:
Input:
1
\
3
/
2
Output:
1
Explanation:
The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3).
Note: There are at least two nodes in this BST.
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def getMinimumDifference(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def dfs(node, l=[]):
if node.left: dfs(node.left, l)
l.append(node.val)
if node.right: dfs(node.right, l)
return l
l = dfs(root)
return min([abs(a - b) for a, b in zip(l, l[1:])])
| true |
ea0ce1b541e74ca38790a66990d809be4ce825af | wangtaodd/LeetCodeSolutions | /107. Binary Tree Level Order Traversal II.py | 1,190 | 4.125 | 4 | """
Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its bottom-up level order traversal as:
[
[15,7],
[9,20],
[3]
]
"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root: return []
tree=[root]
res=[]
dept=0
hasSubTree=True
while hasSubTree:
temp=[]
hasSubTree=False
res.append([])
for i in tree:
res[-1].append(i.val)
if i.left:
temp.append(i.left)
hasSubTree=True
if i.right:
temp.append(i.right)
hasSubTree=True
tree=temp
res.reverse()
return res | true |
c130d758ef000ea0de0b0ed4154dfa711f0b4504 | D-Bits/Math-Scripts | /main.py | 1,918 | 4.40625 | 4 | from vectors import get_dot_product
from series import get_fibonacci, get_num_of_fib, sum_of_terms
from math import factorial
# Choices for the user
options = {
'1': 'Calculate the dot product of two vectors.',
'2': 'Get the sum of the first n terms in an arithmetic series.',
'3': 'Get a specific number in the Fibonacci sequence.',
'4': 'Output the first n numbers in the Fibonacci sequence.',
'5': 'Calculate a factorial.'
}
if __name__ == "__main__":
print() # Blank line for readability
# Show the user their choices
for key, val in options.items():
print(key, val)
print() # Blank line for readability
choice = int(input('Enter a choice, based on the above options: '))
print()
if choice == 1:
vec_angle = float(input('Enter the angle between the two vectors (in degrees): '))
vec_a = int(input('Enter the magnitude of the first vector: '))
vec_b = int(input('Enter the magnitude of the second vector: '))
print('The dot product is:', get_dot_product(vec_angle, vec_a, vec_b), "\n")
elif choice == 2:
num_of_terms = int(input('Enter the number of terms in the series: '))
first_term = int(input('Enter the first term in the series: '))
second_term = int(input('Enter the second term in the series: '))
print(f'The sum of the first {num_of_terms} terms in the series is:', sum_of_terms(num_of_terms, first_term, second_term), "\n")
elif choice == 3:
fib_numb = int(input('Enter which number in the Fibonacci sequence you want to get the value of: '))
print(f'The {fib_numb} number in the Fibonacci sequence is:', get_fibonacci(fib_numb))
elif choice == 4:
fib_terms = int(input('Enter a number of terms in the Fibonacci sequence to display: '))
print(get_num_of_fib(fib_terms))
else:
raise Exception('Invalid Input.') | true |
096ac4e7c999f374495576ced8b6f9ac327a57de | pointmaster2/RagnarokSDE | /SDE/Resources/tut_part2.py | 1,281 | 4.3125 | 4 | """
Tutorial - Part 2
Selection
"""
# You can manipulate the selection of the editor and read its values.
# The example below prints the first three elements of the selected items.
if (selection.Count == 0):
script.throw("Please select an item in the tab!")
for tuple in selection:
print script.format("#{0}, {1}, {2}", tuple[0], tuple[1], tuple[2])
# The above will bring up the console output and show you the result.
# selection contains the items selected.
# script.format() is a useful method to format your output result.
# You can use the currently selected table with the following :
if (selected_db != item_db):
script.throw("Please select the Item tab!")
# To read the values of the table, simply iterate through it like a list.
for tuple in selected_db:
print "Id = " + str(tuple[0])
# This is the same as
for tuple in item_db:
print "Id = " + str(tuple[0])
# Let's say you want to select items from 500 to 560 :
selection.Clear()
for x in range(500, 561): # 561 is not included
if (selected_db.ContainsKey(x)):
selection.Add(selected_db[x])
# Or if you want to select all the potion items...¸
selection.Clear()
for tuple in item_db: # 561 is not included
if ("Potion" in tuple["name"]):
selection.Add(tuple)
| true |
612a5eb267901530782ffe5f82876c970fe34f65 | robseeen/Python-Projects-with-source-code | /Mile_to_KM_Converter_GUI/main.py | 1,119 | 4.34375 | 4 | from tkinter import *
# creating window object
window = Tk()
# Program title
window.title("Miles to Kilometer Converter")
# adding padding to window
window.config(padx=20, pady=20)
# taking user input
miles_input = Entry(width=7)
# grid placement
miles_input.grid(column=2, row=0)
# showing input label
miles_label = Label(text="Miles: ")
# grid placement
miles_label.grid(column=1, row=0)
# another text label
is_equal_label = Label(text="Equal to")
# grid placement
is_equal_label.grid(column=2, row=1)
# kilometer result label, default 0
kilometer_result_label = Label(text="0")
# grid placement
kilometer_result_label.grid(column=2, row=2)
# showing result label
kilometer_label = Label(text="KM:")
# grid placement
kilometer_label.grid(column=1, row=2)
# mile to km calculation
def miles_to_km():
miles = float(miles_input.get())
km = round(miles * 1.609)
kilometer_result_label.config(text=f"{km}")
# calculator button
calculate_button = Button(text="Calculate", command=miles_to_km)
# button placement
calculate_button.grid(column=2, row=3)
# continue run the window object
window.mainloop()
| true |
5cba02efb718d3cfdb85ee3439261fb2fa28cf9f | robseeen/Python-Projects-with-source-code | /average_height_using_for_loop.py | 852 | 4.125 | 4 | # Finding average height using for loop.
# takeing students height and sperated
student_heights = input(
"Input a list of students heights. Seperated by commas.\n => ").split()
# checking the input in list
for n in range(0, len(student_heights)):
student_heights[n] = int(student_heights[n])
# printing the students height list
print(f"Student Height List: {student_heights}")
# total sum of heigth using for loop
total_height = 0
for height in student_heights:
total_height += height
print(f"Total height: {total_height}")
# Total length of students
number_of_students = 0
for student in student_heights:
number_of_students += 1
print(f"Total Number of Students: {number_of_students}")
# Average Height of students
average_height = round(total_height / number_of_students)
print(f"Average Height of Studens: {average_height}")
| true |
530fb79024873eee062a23f2eec7096c00c2c3fc | patidarjp87/python_core_basic_in_one_Repository | /29.Co-Prime.py | 573 | 4.125 | 4 |
print('numbers which do not have any common factor between them,are called co-prime factors')
print('enter a value of a and b')
a=int(input())
b=int(input())
if a>b:
for x in range(2,b+1):
if a%x==0 and b%x==0:
print(a,'&',b,'are not co-prime numbers')
break
else:
continue
if x==b:
print(a,'&',b,'are co-prime numbers')
else:
for x in range(2,a+1):
if a%x==0 and b%x==0:
print(a,'&',b,'are not co-prime numbers')
break
else:
continue
if x==a:
print(a,'&',b,'are co-prime numbers')
input('press enter to exit')
| true |
f8471e2937ec8f64d491a1856f103442e7ec41b3 | patidarjp87/python_core_basic_in_one_Repository | /71.cheacksubset.py | 461 | 4.34375 | 4 |
print("program to check whether a given set is a subset of another given set")
s1=set([eval(x) for x in input('enter elements in superset set 1 as it is as you want to see in your set with separator space\n').split()])
s2=set([eval(x) for x in input('enter elements subset set 2 as it is as you want to see in your set with separator space\n').split()])
if s2.issubset(s1):
print('s2 is a subset of s1')
else:
print("s2 is not a subset of s1")
input()
| true |
d78cd51c22c282a5a5e9c2bdc69442237700985c | patidarjp87/python_core_basic_in_one_Repository | /92.Accoutclass.py | 1,168 | 4.25 | 4 |
print("define a class Account with static variable rate of interest ,instance variable balance and accounr no.make function to set them")
class Account:
def setAccount(self,a,b,rate):
self.accno=a
self.balance=b
Account.roi=rate
def showBalance(self):
print("Balance is ",self.balance)
def showROI(self):
print("rate of interest is",Account.roi)
def showWithdraw(self,withdrawAmount):
if withdrawAmount>self.balance:
print("withdraw unsuccessful...!!! , your account does not have sufficient balance")
else:
print("your request has proceed successfully")
self.balance-=withdrawAmount
def showDeposite(self,Amount):
self.balance+=Amount
s=input("Case deposite successfully...!!! , Type yes to show balance otherwise no")
if s=='yes':
print("Your updated balance is ",self.balance)
acc=Account()
acc.setAccount(101,10000,2)
acc.showBalance()
acc.showROI()
withdrawAmount=eval(input('Enter withdraw amount'))
acc.showWithdraw(withdrawAmount)
Amount=eval(input('Enter a deposite amount'))
acc.showDeposite(Amount)
input()
| true |
776b3c99569733f3f1746eb1dee10bb971d52684 | patidarjp87/python_core_basic_in_one_Repository | /84.countwords.py | 221 | 4.125 | 4 |
print("script to ciunt words in a given string \n Takes somthing returns something\n Enter a string")
s=input()
def count(s):
l=s.split()
return len(l)
print('no. of words in agiven string is ',count(s))
input()
| true |
ca903da90a4a8ce81c24bcc3258259facbef43eb | kapari/exercises | /pydx_oop/adding.py | 629 | 4.15625 | 4 | import datetime
# Class that can be used as a function
class Add:
def __init__(self, default=0):
self.default = default
# used when an instance of the Add class is used as a function
def __call__(self, extra=0):
return self.default + extra
add2 = Add(2)
print(add2(5))
# >> 7
class Person:
def __init__(self, name, birth_date=None):
self.name = name
self.birth_date = birth_date
@property
def days_alive(self):
raturn (datetime.datetime.today() - self.birth_date).days
me = Person(name="Ken", birth_date=datetime.datetime(1981, 5, 23))
print(me.days_alive)
| true |
394e21f7262da6bedbb53a667bc738662033d26a | Aegis-Liang/Python | /HackerRank/Data Structure/2_LinkedLists/10_GetNodeValue.py | 2,559 | 4.25 | 4 |
"""
Get Node data of the Nth Node from the end.
head could be None as well for empty list
Node is defined as
class Node(object):
def __init__(self, data=None, next_node=None):
self.data = data
self.next = next_node
return back the node data of the linked list in the below method.
"""
def GetNode(head, position):
headReverse = Reverse(head)
return GetSpecificNode(headReverse, position).data
def GetSpecificNode(head, position):
current_position = 0
current_node = head
while current_position < position:
#print str(current_position) + " " + str(position - 1)
#print str(current_node.data)
current_node = current_node.next
current_position += 1
return current_node
def Reverse(head):
node = head
# if we don't use a new head, the last node in reversed list is pointed to the first node in origin list
# exp: for an 1->2->3 list, after the first node in reversed list inserted, the list become 1->1->2->3
new_head = None #Node()
while node != None:
new_head = Insert(new_head, node.data) # Forget to assign the latest value to head
node = node.next
return new_head
def Insert(head, data): # Insert to head
new_node = Node(data)
if head == None: # or head.data == None: # if we don't initialize the new_head with Node(), we don't have to check its data
head = new_node
else:
new_node.next = head
head = new_node
return head
"""
This challenge is part of a tutorial track by MyCodeSchool
Youre given the pointer to the head node of a linked list and a specific position. Counting backwards from the tail node of the linked list, get the value of the node at the given position. A position of 0 corresponds to the tail, 1 corresponds to the node before the tail and so on.
Input Format
You have to complete the int GetNode(Node* head, int positionFromTail) method which takes two arguments - the head of the linked list and the position of the node from the tail. positionFromTail will be at least 0 and less than the number of nodes in the list. You should NOT read any input from stdin/console.
Constraints
Position will be a valid element in linked list.
Output Format
Find the node at the given position counting backwards from the tail. Then return the data contained in this node. Do NOT print anything to stdout/console.
Sample Input
1 -> 3 -> 5 -> 6 -> NULL, positionFromTail = 0
1 -> 3 -> 5 -> 6 -> NULL, positionFromTail = 2
Sample Output
6
3
""" | true |
d525e7b1fc92767c602e4911fed11253e09d58ff | Aegis-Liang/Python | /HackerRank/Data Structure/2_LinkedLists/2_InsertANodeAtTheTailOfALinkedList.py | 1,553 | 4.28125 | 4 |
"""
Insert Node at the end of a linked list
head pointer input could be None as well for empty list
Node is defined as
class Node(object):
def __init__(self, data=None, next_node=None):
self.data = data
self.next = next_node
return back the head of the linked list in the below method
"""
def Insert(head, data):
new_node = Node(data)
if head == None:
head = new_node
else:
node = head
while node.next != None:
node = node.next
node.next = new_node
return head
"""This challenge is part of a tutorial track by MyCodeSchool and is accompanied by a video lesson.
You are given the pointer to the head node of a linked list and an integer to add to the list. Create a new node with the given integer. Insert this node at the tail of the linked list and return the head node. The given head pointer may be null, meaning that the initial list is empty.
Input Format
You have to complete the Node* Insert(Node* head, int data) method. It takes two arguments: the head of the linked list and the integer to insert. You should not read any input from the stdin/console.
Output Format
Insert the new node at the tail and just return the head of the updated linked list. Do not print anything to stdout/console.
Sample Input
NULL, data =
--> NULL, data =
Sample Output
2 -->NULL
2 --> 3 --> NULL
Explanation
1. We have an empty list, and we insert .
2. We start with a in the tail. When is inserted, then becomes the tail.
""" | true |
62351503e0025c4fd5c358a16036c52d48eccac6 | Aegis-Liang/Python | /HackerRank/Data Structure/2_LinkedLists/3_InsertANodeAtTheHeadOfALinkedList.py | 1,496 | 4.21875 | 4 | """
Insert Node at the begining of a linked list
head input could be None as well for empty list
Node is defined as
class Node(object):
def __init__(self, data=None, next_node=None):
self.data = data
self.next = next_node
return back the head of the linked list in the below method.
"""
def Insert(head, data):
new_node = Node(data)
if head == None:
head = new_node
else:
new_node.next = head
head = new_node
return head
"""
This challenge is part of a tutorial track by MyCodeSchool and is accompanied by a video lesson.
Youre given the pointer to the head node of a linked list and an integer to add to the list. Create a new node with the given integer, insert this node at the head of the linked list and return the new head node. The head pointer given may be null meaning that the initial list is empty.
Input Format
You have to complete the Node* Insert(Node* head, int data) method which takes two arguments - the head of the linked list and the integer to insert. You should NOT read any input from stdin/console.
Output Format
Insert the new node at the head and return the head of the updated linked list. Do NOT print anything to stdout/console.
Sample Input
NULL , data = 1
1 --> NULL , data = 2
Sample Output
1 --> NULL
2 --> 1 --> NULL
Explanation
1. We have an empty list, on inserting 1, 1 becomes new head.
2. We have a list with 1 as head, on inserting 2, 2 becomes the new head.
""" | true |
9d11b885c5188412b5ed481fea5a49878ae3753e | sangzzz/AlgorithmsOnStrings | /week3&4_suffix_array_suffix_tree/01 - Knuth Morris Pratt/kmp.py | 905 | 4.1875 | 4 | # python3
import sys
def find_pattern(pattern, text):
"""
Find all the occurrences of the pattern in the text
and return a list of all positions in the text
where the pattern starts in the text.
"""
result = []
# Implement this function yourself
text = pattern + '$' + text
s = [0 for _ in range(len(text))]
border = 0
for i in range(1, len(text)):
while border > 0 and text[i] != text[border]:
border = s[border - 1]
if text[i] == text[border]:
border = border + 1
else:
border = 0
s[i] = border
l = len(pattern)
for j, i in enumerate(s[l + 1:]):
if i == l:
result.append(j-l+1)
return result
if __name__ == '__main__':
pattern = input().strip()
text = input().strip()
result = find_pattern(pattern, text)
print(" ".join(map(str, result)))
| true |
60dcba72cc85538aab4f58ddcd1a989e940f9522 | bhargav-makwana/Python-Corey-Schafer | /Practise-Problems/leap_year_functions.py | 654 | 4.3125 | 4 | # Program : Finding the days in the year
# Input : days_in_month(2015, 3)
# Output :
# Numbers of days per month. 0 is used as a placeholder for indexing purposes.
month_days = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
def is_leap(year):
""" Return True for leap years, False for non-leap years"""
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
def days_in_month(year, month):
""" Returns no of days in that month in that year. """
if not 1 <= month <= 12:
return 'Invalid Month'
if month == 2 and is_leap(year):
return 29
return month_days[month]
print(is_leap(2010))
print(days_in_month(2010,2)) | true |
7eb795b0920e210e7ff11317e1ba199129013837 | HypeDis/DailyCodingProblem-Book | /Email/81_digits_to_words.py | 1,058 | 4.21875 | 4 | """
Given a mapping of digits to letters (as in a phone number), and a digit string, return all possible letters the number could represent.
You can assume each valid number in the mapping is a single digit.
For example if {“2”: [“a”, “b”, “c”], 3: [“d”, “e”, “f”], …} then “23” should return [“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf"].
"""
from collections import deque
digitMap = {
2: ['a', 'b', 'c'],
3: ['d', 'e', 'f'],
4: ['g', 'h', 'i'],
5: ['j', 'k', 'l'],
6: ['m', 'n', 'o'],
7: ['p', 'q', 'r', 's'],
8: ['t', 'u', 'v'],
9: ['w', 'x', 'y', 'z'],
}
def numberToWords(num):
res = deque([''])
while num:
# working backwards from ones leftwards
digit = num % 10
num = num // 10
queLen = len(res)
for _ in range(queLen):
curStr = res.popleft()
for char in digitMap[digit]:
res.append(char + curStr)
return list(res)
print(numberToWords(253))
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.