blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
bb50b8feabc4e027222ed347042d5cefdf0e64da | abtripathi/data_structures_and_algorithms | /problems_and_solutions/arrays/Duplicate-Number_solution.py | 1,449 | 4.15625 | 4 | # Solution
'''
Notice carefully that
1. All the elements of the array are always non-negative
2. If array length = n, then elements would start from 0 to (n-2), i.e. Natural numbers 0,1,2,3,4,5...(n-2)
3. There is only SINGLE element which is present twice.
Therefore let's find the sum of all elements (current_sum) of the original array, and
find the sum of first (n-2) Natural numbers (expected_sum).
Trick:
The second occurance of a particular number (say `x`) is actually occupying the space
that would have been utilized by the number (n-1). This leads to:
current_sum = 0 + 1 + 2 + 3 + .... + (n-2) + x
expected_sum = 0 + 1 + 2 + 3 + .... + (n-2)
current_sum - expected_sum = x
Tada!!! :)
'''
def duplicate_number(arr):
current_sum = 0
expected_sum = 0
# Traverse the original array in the forward direction
for num in arr:
current_sum += num
# Traverse from 0 to (length of array-1) to get the expected_sum
# Alternatively, you can use the formula for sum of an Arithmetic Progression to get the expected_sum
# The argument of range() functions are:
# starting index [OPTIONAL], ending index (non exclusive), and the increment/decrement size [OPTIONAL]
# It means that if the array length = n, loop will run form 0 to (n-2)
for i in range(len(arr) - 1):
expected_sum += i
# The difference between the
return current_sum - expected_sum
| true |
26d6e211c524aae3668176e7f54638f589b9226c | nicholasrokosz/python-crash-course | /Ch. 15/random_walk.py | 945 | 4.25 | 4 | from random import choice
class RandomWalk:
"""Generates random walks."""
def __init__(self, num_points=5000):
"""Initializes walk attributes."""
self.num_points = num_points
# Walks start at (0, 0).
self.x_values = [0]
self.y_values = [0]
def fill_walk(self):
"""Calculate all the points in a walk."""
# Keep calculating random steps until number of steps is reached.
while len(self.x_values) < self.num_points:
# Randomly decide which direction and how far to step.
x_direction = choice([1, -1])
x_distance = choice([0, 1, 2, 3, 4])
x_step = x_direction * x_distance
y_direction = choice([1, -1])
y_distance = choice([0, 1, 2, 3, 4])
y_step = y_direction * y_distance
# Reject non-steps.
if x_step == 0 and y_step == 0:
continue
# Calculate the new position.
x = self.x_values[-1] + x_step
y = self.y_values[-1] + y_step
self.x_values.append(x)
self.y_values.append(y) | true |
6405fb18f932d4ef96807f2dc65b04401f32e5be | nicholasrokosz/python-crash-course | /Ch. 10/favorite_number.py | 467 | 4.125 | 4 | import json
def get_fav_num():
"""Asks a user for their favorite number and stores the value in a .json file."""
fav_num = input("What is your favorite number? ")
filename = 'fav_num.json'
with open(filename, 'w') as f:
json.dump(fav_num, f)
def print_fav_num():
"""Retrieves user's favoite number and prints it."""
filename = 'fav_num.json'
with open(filename) as f:
fav_num = json.load(f)
print(f"I know your favorite number! It's {fav_num}.") | true |
da5a646c0a2caecadb60485bf3d02d8c0661960b | nicholasrokosz/python-crash-course | /Ch. 8/user_albums.py | 572 | 4.25 | 4 | def make_album(artist, album, no_of_songs=None):
album_info = {'artist': artist, 'album': album}
if no_of_songs:
album_info['no_of_songs'] = no_of_songs
return album_info
while True:
artist_name = input("Enter the artist's name: ")
album_title = input("Enter the album title: ")
no_of_songs = input("Enter the number of songs (optional): ")
album_info = make_album(artist_name, album_title, no_of_songs)
print(album_info)
repeat = input("\nWould you like to enter another album? Enter Y or N: ")
if repeat == 'Y' or repeat == 'y':
continue
else:
break | true |
af5ab9aad7b047b9e9d061e22ab7afe7e64a4b01 | mumarkhan999/UdacityPythonCoursePracticeFiles | /9_exponestial.py | 347 | 4.5 | 4 | #claculating power of a number
#this can be done easily by using ** operator
#for example 2 ** 3 = 8
print("Assuming that both number and power will be +ve\n")
num = int(input("Enter a number:\n"))
power = int(input("Enter power:\n"))
result = num
for i in range(1,power):
result = result * num
print(result)
input("Press any key to quit...")
| true |
a6fc7a95a15f7c98ff59850c70a05fdb028a784f | mumarkhan999/UdacityPythonCoursePracticeFiles | /8_multi_mulTable.py | 208 | 4.25 | 4 | #printing multiple multiplication table
num = int(input("Enter a number:\n"))
for i in range (1, (num+1)):
print("Multiplication Table of",i)
for j in range(1,11):
print(i,"x",j,"=",i*j)
| true |
162b0739cda0d6fba65049b474bc72fecf547f3d | dodgeviper/coursera_algorithms_ucsandeigo | /course1_algorithmic_toolbox/week4/assignment/problem_4.py | 2,492 | 4.21875 | 4 | # Uses python3
"""How close a data is to being sorted
An inversion of sequence a0, a1, .. an-1 is a pair of indices 0<= i < j< n
such that ai < aj. The number of inversion of a sequence in some sense measures
how close the sequence is to being sorted. For example, a sorted (in non-decreasing
order) sequence contains no inversions at all, while in a sequence sorted in descending
order any two elements constitute an inversion (for a total of n(n - 1)/ 2 inversions)
Task: the goal is to count the number of inversions of a given sequence.
Input format: First line contains an integer n, the next one contains a sequence of
integers a0, a1.. an-1
Constraints:
1<= n < 10^5, 1 <= ai <= 10^9 for all 0 <= i < n
Output:
The number of inversions of the sequence.
"""
inversion_count = [0]
def merge(a, b):
d = list()
index_a, index_b = 0, 0
len_a = len(a)
while index_a < len(a) and index_b < len(b):
el_a = a[index_a]
el_b = b[index_b]
if el_a <= el_b:
d.append(el_a)
index_a += 1
else:
d.append(el_b)
index_b += 1
inversion_count[0] += (len_a - index_a)
d.extend(a[index_a:])
d.extend(b[index_b:])
return d
def merge_sort(n):
if len(n) == 1:
return n
mid = int(len(n) / 2)
left_half = merge_sort(n[:mid])
right_half = merge_sort(n[mid:])
return merge(left_half, right_half)
#
# def counting_inversions_naive(input_list):
# count = 0
# for i in range(len(input_list)):
# for j in range(i+1, len(input_list)):
# if input_list[i] > input_list[j]:
# count += 1
# return count
#
# import random
# def stress_testing():
# while True:
# n = random.randint(1, 3)
# input_list = [random.randint(1, 100) for _ in range(n)]
# count_naive = counting_inversions_naive(input_list)
# inversion_count[0] = 0
# merge_sort(input_list)
# count_eff = inversion_count[0]
# if count_naive != count_eff:
# print('Failed')
# print(n)
# print(input_list)
# print('count naive; ', count_naive)
# print('optimized: ', count_eff)
# break
#
#
#
# stress_testing()
#
n = input()
input_list = list(map(int, input().split()))
# # inversions = []
# # n = 6
# # input_list = [9, 8, 7, 3, 2, 1]
merge_sort(input_list)
print(inversion_count[0])
# print(counting_inversions_naive(input_list)) | true |
8c41e6813d5e137bf3acbe883b08d269d9cb7d7b | Smellly/weighted_training | /BinaryTree.py | 1,813 | 4.25 | 4 | # simple binary tree
# in this implementation, a node is inserted between an existing node and the root
import sys
class BinaryTree():
def __init__(self,rootid):
self.left = None
self.right = None
self.rootid = rootid
def getLeftChild(self):
return self.left
def getRightChild(self):
return self.right
def setNodeValue(self,value):
self.rootid = value
def getNodeValue(self):
return self.rootid
def insertRight(self,newNode):
if self.right == None:
self.right = BinaryTree(newNode)
else:
tree = BinaryTree(newNode)
tree.right = self.right
self.right = tree
def insertLeft(self,newNode):
if self.left == None:
self.left = BinaryTree(newNode)
else:
tree = BinaryTree(newNode)
self.left = tree
tree.left = self.left
def printTree(tree):
if tree != None:
# sys.stdout.write('<')
tmp = ''
tmp += printTree(tree.getLeftChild())
#print(tree.getNodeValue())
tmp += ' ' + tree.getNodeValue()
tmp += ' ' + printTree(tree.getRightChild())
#sys.stdout.write('>')
return tmp
else:
return ''
def getAllLeaves(tree):
leaves = set()
if tree != None:
if tree.getLeftChild() is None and tree.getRightChild() is None:
leaves.add(tree.getNodeValue())
else:
if tree.getLeftChild() is not None:
leaves = leaves.union(getAllLeaves(tree.getLeftChild()))
if tree.getRightChild() is not None:
leaves = leaves.union(getAllLeaves(tree.getRightChild()))
return leaves
# else:
# return None
| true |
a5f8cf2de38a252d3e9c9510368419e5a763cf74 | TheFibonacciEffect/interviewer-hell | /squares/odds.py | 1,215 | 4.28125 | 4 | """
Determines whether a given integer is a perfect square, without using
sqrt() or multiplication.
This works because the square of a natural number, n, is the sum of
the first n consecutive odd natural numbers. Various itertools
functions are used to generate a lazy iterable of odd numbers and a
running sum of them, until either the given input is found as a sum
or the sum has exceeded n.
"""
from itertools import accumulate, count, takewhile
import sys
import unittest
is_square = lambda n: n > 0 and n in takewhile(lambda x: x <= n, accumulate(filter(lambda n: n & 1, count())))
class SquareTests(unittest.TestCase):
def test_squares(self):
for i in range(1, 101):
if i in (1, 4, 9, 16, 25, 36, 49, 64, 81, 100):
assert is_square(i)
else:
assert not is_square(i)
if __name__ == '__main__':
if len(sys.argv) != 2:
sys.exit(unittest.main())
value = None
try:
value = int(sys.argv[1])
except TypeError:
sys.exit("Please provide a numeric argument.")
if is_square(value):
print("{} is a square.".format(value))
else:
print("{} is not a square.".format(value))
| true |
959fc6191262d8026e7825e50d80eddb08d6a609 | OliValur/Forritunar-fangi-1 | /20agust.py | 2,173 | 4.28125 | 4 | import math
# m_str = input('Input m: ') # do not change this line
# # change m_str to a float
# # remember you need c
# # e =
# m_float = float(m_str)
# c = 300000000**2
# e = m_float*c
# print("e =", e) # do not change this line)
# Einstein's famous equation states that the energy in an object at rest equals its mass times the square of the speed of light. (The speed of light is 300,000,000 m/s.)
# Complete the skeleton code below so that it:
# * Accepts the mass of an object (remember to convert the input string to a number, in this case, a float).
# * Calculate the energy, e
# * Prints e
# import math
# x1_str = input("Input x1: ") # do not change this line
# y1_str = input("Input y1: ") # do not change this line
# x2_str = input("Input x2: ") # do not change this line
# y2_str = input("Input y2: ") # do not change this line
# x1_int = int(x1_str)
# y1_int = int(y1_str)
# x2_int = int(x2_str)
# y2_int = int(y2_str)
# formula =(y1_int-y2_int)**2+(x1_int-x2_int)**2
# d = math.sqrt(formula)
# print(formula)
# print("d =",d) # do not change this line
# weight_str = input("Weight (kg): ") # do not change this line
# height_str = input("Height (cm): ") # do not change this line
# # weight_int = int(weight_str)
# # height_int = int(height_str)
# weight_float = float(weight_str)
# height_float = float(height_str)
# bmi = weight_float / (height_float**2)
# print("BMI is: ", bmi) # do not change this line75,290.6
n_str = input("Input n: ")
# remember to convert to an int
n_int = int(n_str)
first_three = n_int//100
last_two =n_int % 100
print("first_three:", first_three)
print("last_two:", last_two)
# Write a Python program that:
# Accepts a five-digit integer as input
# Assign the variable first_three (int) to be the first three digits.
# Assign the variable last_two (int) to be the last two digits.
# Prints out the two computed values.
# Hint: use quotient (//) and remainder (%)
# For example, if the input is 12345, the output should be:
# first_three: 123
# last_two: 45
# If the fourth digit is a zero, like 12305, the output should be:
# first_three: 123
# last_two: 5
# (even though that is not strictly correct). | true |
0837151d119a5496b00d63ae431b891e405d11cb | Shubham1744/Python_Basics_To_Advance | /Divide/Prog1.py | 249 | 4.15625 | 4 | #Program to divide two numbers
def Divide(No1,No2):
if No2 == 0 :
return -1
return No1/No2;
No1 = float(input("Enter First Number :"))
No2 = float(input("Enter Second Number :"))
iAns = Divide(No1,No2)
print("Division is :",iAns);
| true |
c35d93f5359f710db0bb6d3db7f4c8af1724b1e9 | umberahmed/hangman- | /index.py | 586 | 4.25 | 4 | # This program will run the game hangman
# random module will be used to generate random word from words list
import random
# list of words to use in game
list_of_words = ["chicken", "apple", "juice", "carrot", "hangman", "program", "success", "hackbright"]
# display dashes for player to see how many letters are in the word to guess
print random.choice(list_of_words)
def greet_user():
"""greets user to hangman"""
print "Welcome to Hangman!"
greet_user()
def player():
"""stores player's name"""
name = input("What's your name? ")
return name
player()
| true |
a462d5adc2feb9f2658701a8c2035c231595f81e | kristinejosami/first-git-project | /python/numberguessing_challenge.py | 911 | 4.3125 | 4 | '''
Create a program that:
Chooses a number between 1 to 100
Takes a users guess and tells them if they are correct or not
Bonus: Tell the user if their guess was lower or higher than the computer's number
'''
print('Number Guessing Challenge')
guess=int(input('This is a number guessing Challenge. Please enter your guess number:'))
from random import randint
number=int(randint(1,100))
# number=3
if number==guess:
print('Congratulations! Your guess is correct. The number is {} and your guess is {}.'.format(number, guess))
elif number<guess:
print("Sorry, your number is incorrect. The number is {} and your guess is {}."
" Your guess is greater than the number. Please try again.".format(number,guess))
else:
print("Sorry, your number is incorrect. The number is {} and your guess is {}. "
"Your guess is lesser than the number. Please try again.".format(number, guess))
| true |
b9310befbc4a399a8c239f22a1bc06f7286fedee | pawan9489/PythonTraining | /Chapter-2/4.Sets.py | 1,504 | 4.375 | 4 | # Set is a collection which is unordered and unindexed. No duplicate members.
fruits = {'apple', 'banana', 'apple', 'cherry'}
print(type(fruits))
print(fruits)
print()
# Set Constructor
# set() - empty set
# set(iterable) - New set initialized with iterable items
s = set([1,2,3,2,1])
print(s)
print()
# No Indexing - Since no ordering but we can Loop
for fruit in fruits:
print(fruit)
print()
# Membership
print("'cherry' in fruits = {0}".format('cherry' in fruits))
print()
# Only appending No Updating Items - Since no Indexing
# Add items
print("Before adding = {0}".format(fruits))
fruits.add('mango')
print("fruits.add('mango') = {0}".format(fruits))
print()
# Add Multiple items
print("Before Multiple adding = {0}".format(fruits))
fruits.update(['orange', 'grapes'])
print("fruits.update(['orange', 'grapes']) = {0}".format(fruits))
print()
# Length of Set
print("len(fruits) = {0}".format(len(fruits)))
print()
# Remove Item
# remove(item) - will throw error if item dont exist
# discard(item) - will not throw error if item dont exist
print("Before removing = {0}".format(fruits))
fruits.remove('grapes')
print("fruits.remove('grapes') = {0}".format(fruits))
print()
# pop - remove some random element - Since no Indexing
# only pop(), not pop(index) - Since no Indexing
print("Before pop = {0}".format(fruits))
print("fruits.pop() = {0}".format(fruits.pop()))
print()
# clear()
print("Before clear = {0}".format(fruits))
fruits.clear()
print("fruits.clear() = {0}".format(fruits)) | true |
ca7b96d6389b50e8637507cce32274991e792144 | SK7here/learning-challenge-season-2 | /Kailash_Work/Other_Programs/Sets.py | 1,360 | 4.25 | 4 | #Sets remove duplicates
Text = input("Enter a statement(with some redundant words of same case)")
#Splitting the statement into individual words and removing redundant words
Text = (set(Text.split()))
print(Text)
#Creating 2 sets
print("\nCreating 2 sets")
a = set(["Jake", "John", "Eric"])
print("Set 1 is {}" .format(a))
b = set(["John", "Jill"])
print("Set 2 is {}" .format(b))
#Adding elements
print("\nAdding 'SK7' item to both sets")
a.add("SK7")
b.add("SK7")
print("Set 1 after adding 'SK7' : ")
print(a)
print("Set 2 after adding 'SK7' : ")
print(b)
#Removing elements
del_index = (input("\nEnter the element to be removed in set 1: "))
a.remove(del_index)
print("After removing specified element")
print(a)
#Finding intersection
print("\nIntersection between set 1 and set 2 gives : ")
print(a.intersection(b))
#Finding items present in only one of the sets
print("\nItems present in only one of the 2 sets : ")
print(a.symmetric_difference(b))
print("\nItems present only in set a : ")
print(a.difference(b))
print("\nItems present only in set b : ")
print(b.difference(a))
#Finding union of 2 sets
print("\nUnion of 2 sets : ")
print(a.union(b))
#Clearing sets
print("\nClearing sets 1 and 2")
print("Set 1 is {}" .format(a.clear()))
print("Set 2 is {}" .format(b.clear()))
| true |
0164661e3480ce4df1f2140c07034b3bb75a6c3b | SK7here/learning-challenge-season-2 | /Kailash_Work/Arithmetic/Calculator.py | 1,779 | 4.125 | 4 | #This function adds two numbers
def add(x , y):
return x + y
#This function subtracts two numbers
def sub(x , y):
return x - y
#This function multiplies two numbers
def mul(x , y):
return x * y
#This function divides two numbers
def div(x , y):
return x / y
#Flag variable used for calculator termination purpose
#Initially flag is set to 0
flag = 0
#Until the user chooses option 5(Stop), calculator keeps on working
while(flag == 0):
#Choices displayed
print("\n\n\nSelect operation")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
print("5.Stop")
#Take input from the user
choice = input("\nEnter choice : ")
if(choice == '5'):
#If user wishes to stop calculator(choice 5), flag is set to 1
flag = 1
#If user has chosen choice 5(stop), control comes out of loop here, failing to satisfy the condition
if(flag == 0):
num1 = int(input("\nEnter first input : "))
num2 = int(input("Enter second input : "))
#Performing corresponding arithmetic operation
if choice == '1':
print("\nSum of {} and {} is {}" .format(num1 , num2 , add(num1,num2)))
elif choice == '2':
print("\nDifference between {} and {} is {}" .format(num1 , num2 , sub(num1,num2)))
elif choice == '3':
print("\nProduct of {} and {} is {}" .format(num1 , num2 , mul(num1,num2)))
elif choice == '4':
print("\nDivision of {} and {} is {}" .format(num1 , num2 , div(num1,num2)))
else:
print("Invalid operation")
#Comes out of the loop, if user chooses choice 5(flag is set to '1')
print("\nCalculator service terminated")
| true |
4e8b2c18ebf0d7793c7be7dc2830842f26535ab1 | githubfun/LPTHW | /PythonTheHardWay/ex14-ec.py | 1,061 | 4.25 | 4 | # Modified for Exercise 14 Extra Credit:
# - Change the 'prompt' to something else.
# - Add another argument and use it.
from sys import argv
script, user_name, company_name = argv
prompt = 'Please answer: '
print "Hi %s from %s! I'm the %s script." % (user_name, company_name, script)
print "I'd like to ask you a few questions."
print "Do you like me, %s from %s?" % (user_name, company_name)
likes = raw_input(prompt)
print "Where do you live, %s?" % user_name
lives = raw_input(prompt)
print "Where is %s located?" % company_name
company_location = raw_input(prompt)
print "What kind of computer do you have?"
computer = raw_input(prompt)
print "Did %s give you your %s computer?" % (company_name, computer)
company_gave_computer = raw_input(prompt)
print """
OK... so you said %r about liking me.
You live in %s. Yes, I think I know the area.
%s is in %s. You must have to fly to get there. That's a shame; there are closer companies, I'm sure.
Your %s computer? Meh. I've seen better.
""" % (likes, lives, company_name, company_location, computer)
| true |
c8176ae9af68ecc082863620472e9fe440300668 | githubfun/LPTHW | /PythonTheHardWay/ex03.py | 1,688 | 4.1875 | 4 | # The first line of executable code prints a statment (the stuff contained between the quotes) to the screen.
print "I will now count my chickens:"
# Next we print the word "Hens" followed by a space, then the result of the formula, which is analyzed 25 + (30 / 6)
print "Hens", 25 + 30 / 6
# Line 7 prints right below the above output the word "Roosters" then the result of the formula 100 - (( 25 * 3) % 4)
print "Roosters", 100 - 25 * 3 % 4
# 10 prints the statement about counting the eggs.
print "Now I will count the eggs:"
# 12 puts the result of the formula on the next line below the statement about counting eggs.
# This formula is calculated ( 3 + 2 + 1 - 5 ) + ( 4 % 2 ) - ( 1 / 4 ) + 6
# What tripped me up was ( 1 / 4 ) = 0, since we're doing integer math, not FP.
print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
# 19 prints a whole statement, including the whole formula, since everything
# is between the quotes.
print "Is it true that 3 + 2 < 5 - 7?"
# 22 prints the results of the formula, which is analyzed "Is ( 3 + 2 ) < ( 5 - 7 )"?
print 3 + 2 < 5 - 7
# 25 and 26 analyze the "halves" of the above question and formula, printing the "halves" first, then the result of the calculation.
print "What is 3 + 2?", 3 + 2
print "What is 5 - 7", 5 - 7
# vvv----I noticed a typo here while working on Extra Credit 5
# 29 is an "Aha" from the above two analyses.
print "Oh, that's why it's False."
print "How about some more." # print the statement to the screen
# The final three lines print a question, then the answer to a formula.
print "Is it greater?", 5 > -2
print "Is it greater or equal?", 5 >= -2
print "Is it less or equal?", 5 <= -2 | true |
6db17e91e654e5229ccad28166264478673839d9 | abrosen/classroom | /itp/spring2020/booleanExpressions.py | 427 | 4.1875 | 4 | print(3 > 7)
print(6 == 6)
print(6 != 6)
weather = "sunny"
temperature = 91
haveBoots = False
goingToTheBeach = True
if weather == "raining":
print("Bring an umbrella")
print(weather == "raining" and temperature < 60)
if weather == "raining" and temperature < 60:
print("Bring a raincoat")
if (weather == "raining" and temperature > 90 and not haveBoots) or goingToTheBeach:
print("Looks like sandals for today")
| true |
8f4b21a601c7e3a2da6c26971c7c7bb982d4a242 | hashncrash/IS211_Assignment13 | /recursion.py | 2,230 | 4.625 | 5 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Week 14 Assignment - Recursion"""
def fibonnaci(n):
"""Returns the nth element in the Fibonnaci sequence.
Args:
n (int): Number representing the nth element in a sequence.
Returns:
int: The number that is the given nth element in the fibonnaci sequence.
Examples:
>>> fibonnaci(1)
1
>>> fibonnaci(10)
55
"""
if n == 1 or n == 2:
return 1
else:
return fibonnaci(n - 1) + fibonnaci(n - 2)
def gcd(a, b):
"""Returns the greatest common divisor of two numbers.
Args:
a (int): an integer to find the greatest common divisor with b
b (int): an integer to find the greatest common divosor with a
Returns:
int: An integer representing the largest number that divides both given
integers a and b without leaving a remainder.
Examples:
>>> gcd(252, 105)
21
>>> gcd(100, 27)
1
"""
if b == 0:
return a
else:
return gcd(b, a % b)
def compareTo(s1, s2):
"""Compares two strings and returns a value depending on the comparison of
the two strings.
Args:
s1(str): a string to be compared to another given string in the second
argument.
s2(str): a string to be compared to the first given argument (s1).
Returns:
int: A value corresponding with the comparison of two strings; A
positive value if s1 > s2, a negative value if s1 < s2, and 0 if they
are the same.
Examples:
>>> compareTo("abracadabra", "poof")
-112
>>> compareTo("lmno", "hijkl")
108
>>> compareTo("", "")
0
>>> compareTo("boo", "book")
-111
"""
if s1 == '' and s2 == '':
return 0
elif ord(s1[0]) > ord(s2[0]):
return 0 + ord(s1[0])
elif ord(s1[0]) < ord(s2[0]):
return 0 - ord(s2[0])
elif s1[1:2] == '' and not s2[1:2] == '':
return 0 - ord(s2[0])
elif s2[1:2] == '' and not s1[1:2] == '':
return 0 + ord(s1[0])
elif s1[1:2] == '' and s2[1:2] == '':
return 0
else:
return compareTo(s1[1:], s2[1:])
| true |
8d1de591706470db3bbcf26374ff958f393e85f7 | tungnc2012/learning-python | /if-else-elif.py | 275 | 4.21875 | 4 | name = input("Please enter your username ")
if len(name) <= 5:
print("Your name is too short.")
elif len(name) == 8:
# print("Your name is 8 characters.")
pass
elif len(name) >= 8:
print("Your name is 8 or more characters.")
else:
print("Your name is short.") | true |
7de4e99e276c3e0ba73fc82112b55f7ee8190d5c | ayazzy/Plotter | /searches.py | 1,673 | 4.1875 | 4 | '''
This module has two functions.
Linear Search --> does a linear search when given a collection and a target.
Binary Search --> does a binary search when given a collection and a target.
output for both functions are two element tuples.
Written by: Ayaz Vural
Student Number: 20105817
Date: March 22nd 2019
'''
def linearSearch(collection,target):
count = 0
for item in collection:
count +=1
if target== item:
return target,count
return None, count
def binarySearch(collection,target):
low = 0
high = len(collection) - 1
count = 0
while high >= low:
count = count + 1
mid = (high + low) // 2
if target == collection[mid]:
return target, count
if target < collection[mid]:
high = mid - 1
else:
low = mid + 1
return None, count
if __name__ == "__main__":
print("~~TESTING~~")
aList = [1,2,3,4,5,6,7,8,9]
print(aList)
print("\n")
print("Testing the binarySearch function")
print("input is aList and target is 9. Expected output is 9 and 4 in a tuple")
print(binarySearch(aList,9 ))
print("\n")
print("input is the aList and target is 12. Since 12 is not in the list expected output is None and 4")
print(binarySearch(aList,12 ))
print("\n")
print("Testing the linearSearch function")
print("input is aList and target is 9. Expected output is 9 and 9 in a tuple")
print(linearSearch(aList,9))
print("\n")
print("input is aList and target is 11. Expected output is none and 9 in a tuple")
print(linearSearch(aList,11))
| true |
a4b22a4a32ffa1afb1508d232388d6bc759e0485 | avi651/PythonBasics | /ProgrammeWorkFlow/Tabs.py | 233 | 4.125 | 4 | name = input("Please enter your name: ")
age = int(input("Hi old are you, {0}? ".format(name))) #Adding type cast
print(age)
if age > 18:
print("You are old enough to vote")
else:
print("Please come back in {0}".format(18 - age)) | true |
9b2f359901f6a835563e878a9f103dec0b110a86 | nguiaSoren/Snake-game | /scoreboard.py | 1,123 | 4.3125 | 4 | from turtle import Turtle
FONT = ("Arial", 24, "normal")
#
class Scoreboard(Turtle):
def __init__(self):
super().__init__()
# Set initials score to 0
self.score = 0
# Set colot to white
self.color("white")
# Hide the turtle, we wonly want to see the text
self.hideturtle()
# Do not draaw when the turtle will move
self.penup()
# Move the turtle to the top
self.goto(0,370)
# Write initial score
self.write(arg = f"Score: {self.score}", align="center", font=FONT)
def update_score(self):
"Update current score"
# Clear the screen (erase the writings and drawings)
self.clear()
# Update the score attribute
self.score += 1
# Write the new text with the new score
self.write(arg = f"Score: {self.score}", align="center", font=FONT)
def game_over(self):
"Show game over message"
# Show game over message at the center of the screen
self.goto(0,0)
self.write(arg = "Game Over", align="center", font=FONT) | true |
ddfe13cbff04a326ed196b20beb8f1414364b086 | luzperdomo92/test_python | /hello.py | 209 | 4.25 | 4 | name = input("enter your name: ")
if len(name) < 3:
print("name must be al least 3 characters")
elif len(name) > 20:
print("name can be a maximun 50 characteres")
else:
print("name looks good!")
| true |
450b68eb2689957ce61da69333d6a0588820339d | GTVanitha/PracticePython | /bday_dict.py | 1,003 | 4.34375 | 4 |
birthdays = {
'Vanitha' : '05/05/90',
'Som' : '02/04/84',
'Vino' : '08/08/91'
}
def b_days():
print "Welcome to birthday dictionary! We know the birthdays of:"
names = birthdays.keys()
print ',\n'.join(names)
whose = raw_input("Who's birthday do you want to look up?")
if (whose in names):
print whose , "'s birthday is ", birthdays[whose]
print "Thank you for using birthday dictionary. Happy day :)"
else:
print "Sorry. We do not have ", whose, " birthday date."
add = raw_input(" Do you want to add it ? (y/n)" )
if add == 'y':
name = raw_input("Enter name:")
bday = raw_input("Enter birth date:")
birthdays[name] = bday
print "Added ", name, "'s birthday to dictionary. Try accessing it!"
b_days()
else:
print "Thank you for using birthday dictionary. Happy day :)"
b_days()
| true |
4c71d1fa592e3c54844946aa62e8eb4f7c69f95f | Aravindan-C/LearningPython | /LearnSet.py | 535 | 4.3125 | 4 | __author__ = 'aravindan'
"""A set is used to contain an unordered collection of objects,To create a set use the set() function and supply a sequence of items such as follows"""
s= set([3,5,9,10,10,11]) # create a set of unique numbers
t=set("Hello") # create a set of unique characters
u=set("abcde")
"""sets are unordered and cannot be indexed by numbers"""
print t ^ u
print s & u
t.add('x') # To add an item to a set
s.update([9,10,11],[9,14,16]) # To add a multiple item to set
print s
t.remove('H','l')
t.remove('e') | true |
c21762ec2545a3836c039837ec782c8828044fca | jkusita/Python3-Practice-Projects | /count_vowels.py | 1,833 | 4.25 | 4 | # Count Vowels – Enter a string and the program counts the number of vowels in the text. For added complexity have it report a sum of each vowel found.
vowel_list = ["a", "e", "i", "o", "u"]
vowel_count = 0 # Change this so it adds all the values of the keys in the new dictionary.
vowel_count_found = {"a": 0, "e": 0, "i": 0, "o": 0, "u": 0} # TODO: maybe you can change the keys from strings to variable (if possible)?
# vowel_count_a = 0
# vowel_count_e = 0
# vowel_count_i = 0
# vowel_count_o = 0
# vowel_count_u = 0
# Counts the number of vowels in the inputted string.
user_input = str.lower(input("Please enter a string: "))
for i in range(len(user_input)):
if user_input[i] in vowel_list:
# Counts the sum of each vowels found in the inputted string.
if user_input[i] == "a":
vowel_count_found[user_input[i]] += 1 # Is there a way to add to a non-string key value in dict?
vowel_count += 1
elif user_input[i] == "e":
vowel_count_found[user_input[i]] += 1
vowel_count += 1
elif user_input[i] == "i":
vowel_count_found[user_input[i]] += 1
vowel_count += 1
elif user_input[i] == "o":
vowel_count_found[user_input[i]] += 1
vowel_count += 1
elif user_input[i] == "u":
vowel_count_found[user_input[i]] += 1
vowel_count += 1
# Prints out how much vowels are in the string based on certain conditions.
if vowel_count == 0:
print("There are no vowels.")
elif vowel_count == 1:
print("There is only one vowel.")
else:
print(f"There are {vowel_count} vowels.")
# Prints out the sum of each vowels found in the inputted string.
for i, j in vowel_count_found.items():
print(i + ":" + str(j))
# For design/spacing.
print("")
| true |
2487fdd78e971f078f6844a2fa5bb0cd031b0d71 | Dunkaburk/gruprog_1 | /grundlaggande_programvareutveckling/week2/src/samples/MathMethods.py | 751 | 4.25 | 4 | # package samples
# math is the python API for numerical calculations
from math import *
def math_program():
f_val = 2.1
print(f"Square root {sqrt(f_val)}")
print(f"Square {pow(f_val, 2)}")
print(f"Floor {floor(f_val)}")
print(f"Ceil {ceil(f_val)}")
print(f"Round {round(f_val)}")
# etc. many more ... type math. (dot) and they will show up ...
print(pi) # Declared in Math library
# Comparing floats
f1 = 1.0 - 0.7 - 0.3 # ~= 0.0
f2 = 1.0 - 0.6 - 0.4 # ~= 0.0
print(f1 == f2) # False!! Rounding error!
print(abs(f1 - f2)) # How large is the rounding error?
# Pythagoras ... (nested calls)
print(sqrt(pow(3, 2) + pow(4, 2)) == 5)
if __name__ == "__main__":
math_program()
| true |
1b54c0d17ea896a12aa2a20779416e0bac85d066 | Dunkaburk/gruprog_1 | /grundlaggande_programvareutveckling/week3_tantan/src/exercises/Ex4MedianKthSmallest.py | 901 | 4.15625 | 4 | # package exercises
#
# Even more list methods, possibly even trickier
#
def median_kth_smallest_program():
list1 = [9, 3, 0, 1, 3, -2]
# print(not is_sorted(list1)) # Is sorted in increasing order? No not yet!
# sort(list1) # Sort in increasing order, original order lost!
print(list1 == [-2, 0, 1, 3, 3, 9])
# print(is_sorted(list1)) # Is sorted in increasing order? Yes!
list2 = [5, 4, 2, 1, 7, 0, -1, -4, 12]
list3 = [2, 3, 0, 1]
# print(median(list2) == 2) # Calculate median of elements
# print(median(list3) == 1.5)
list4 = [2, 3, 0, 1, 5, 4]
list5 = [5, 4, 2, 2, 1, 7, 4, 0, -1, -4, 0, 0, 12]
# print(k_smallest(list4, 2) == 1) # Second smallest is 1
# print(k_smallest(list5, 5) == 2) # 5th smallest is 2
# ---------- Write methods here --------------
if __name__ == "__main__":
median_kth_smallest_program()
| true |
16acd854ef3b668e05578fd5efff2b5c2a6f88f4 | Dunkaburk/gruprog_1 | /grundlaggande_programvareutveckling/Week1Exercises/Week1Exercises/week1/src/exercises/Ex2EasterSunday.py | 1,705 | 4.3125 | 4 | # package exercises
# Program to calculate easter Sunday for some year (1900-2099)
# https://en.wikipedia.org/wiki/Computus (we use a variation of
# Gauss algorithm, scroll down article, don't need to understand in detail)
#
# To check your result: http://www.wheniseastersunday.com/
#
# See:
# - LogicalAndRelationalOps
# - IfStatement
def when_is_easter_sunday_program():
# int a, b, c, d, e, s, t // Avoid variables on same line (but acceptable here)
# int date;
# int year;
# int month = 0;
# ---- Input --------------
year = int(input("Input a year (1900-2099) > "))
# ----- Process -----------
a = year % 19 # Don't need to understand, Gauss did understand
b = year % 4
c = year % 7
s = 19 * a + 24
d = s % 30
t = 2 * b + 4 * c + 6 * d + 5
e = t % 7
date = 22 + d + e
# TODO Now you continue ...
# If date is less than 32, then date is found and month is march.
# Else: Date is set to d + e - 9 and month is april ...
# ... but with two exceptions
# If date is 26 easter is on 19 of april.
# If date is 25 and a = 16 and d = 28 then date is 18 of april.
if date < 32 and date!=26 and date!=25:
month = "march"
elif date == 26:
month = "april"
date = 26
elif date == 25 and a == 16 and d == 28:
month = "april"
date = 18
else:
month = "april"
date = d + e - 9
# --------- Output -----------
print("Easter Sunday for " + str(year) + " is : " + str(date) + "/" + str(month))
# Recommended way to make module executable
if __name__ == "__main__":
when_is_easter_sunday_program()
| true |
fd550e115ac526fe5ac6bc9543278a7d852325b6 | anthonysim/Python | /Intro_to_Programming_Python/pres.py | 444 | 4.5 | 4 | """
US Presidents
Takes the names, sorts the order by first name, then by last name.
From there, the last name is placed in front of the first name, then printed
"""
def main():
names = [("Lyndon, Johnson"), ("John, Kennedy"), ("Andrew, Johnson")]
names.sort(key=lambda name: name.split()[0])
names.sort(key=lambda name: name.split()[1])
for name in names:
space = name.find(" ")
print(name[space + 1:] + ", " + name[ : space-1])
main()
| true |
c1dceb57ede0b3eb1f1fe5fe658fe283116d68f3 | pythonic-shk/Euler-Problems | /euler1.py | 229 | 4.34375 | 4 | n = input("Enter n: ")
multiples = []
for i in range(int(n)):
if i%3 == 0 or i%5 == 0:
multiples.append(i)
print("Multiples of 3 or 5 or both are ",multiples)
print("Sum of Multiples of ",n," Numbers is ",sum(multiples)) | true |
7468f255b87e3b4aa495e372b44aba87ff2928d1 | tengrommel/go_live | /machine_learning_go/01_gathering_and_organizating_data/gopher_style/python_ex/myprogram.py | 449 | 4.3125 | 4 | import pandas as pd
'''
It is true that, very quickly, we can write some Python code to parse this CSV
and output the maximum value from the integer column without even
knowing what types are in the data:
'''
# Define column names
cols = [
'integercolumn',
'stringcolumn'
]
# Read in the CSV with pandas.
data = pd.read_csv('myfile.csv', names=cols)
# Print out the maximum value in the integer column.
print(data['integercolumn'].max()) | true |
e863fd0cfe96478d6550b426d675de6cfc84c08a | kami71539/Python-programs-4 | /Program 19 Printing even and odd number in the given range.py | 515 | 4.28125 | 4 | #To print even numbers from low to high number.
low=int(input("Enter the lower limit: "))
high=int(input("ENter the higher limit: "))
for i in range(low,high):
if(i%2==0):
print(i,end=" ")
print("")
for i in range(low,high):
if(i%2!=0):
print(i,end=" ")
#Printing odd numbers from higher number to lower number
low=int(input("Enter the lower limit: "))
high=int(input("ENter the higher limit: "))
for i in range(high,low,-1):
if(i%2!=0):
print(i,end=" ") | true |
61bef90211ffd18868427d3059e8ab8dee3fefde | kami71539/Python-programs-4 | /Program 25 Printing text after specific lines.py | 303 | 4.15625 | 4 | #Printing text after specific lines.
text=str(input("Enter Text: "))
text_number=int(input("Enter number of text you'd like to print; "))
line_number=1
for i in range(0,text_number):
print(text)
for j in range(0,line_number):
print("1")
line_number=line_number+1
print(text) | true |
38658702ed937a7ba65fd1d478a371e4c6d5e789 | kami71539/Python-programs-4 | /Program 42 Finding LCM and HCF using recursion.py | 259 | 4.25 | 4 | #To find the HCF and LCM of a number using recursion.
def HCF(x,y):
if x%y==0:
return y
else:
return HCF(y,x%y)
x=int(input(""))
y=int(input(""))
hcf=HCF(x,y)
lcm=(x*y)/hcf
print("The HCF is",hcf,". The LCM is",lcm) | true |
6f2ac1ae18a208e032f7f1db77f64710f3b9bd00 | kami71539/Python-programs-4 | /Program 15 Exponents.py | 221 | 4.375 | 4 | print(2**3)
def exponents(base,power):
i=1
for index in range(power):
i=i*base
return i
a=int(input(""))
b=int(input(""))
print(a, "raised to the power of" ,b,"would give us", exponents(a,b))
| true |
e80d7d475ddcf65eddd08d77aa4c2c03f965dfb9 | kami71539/Python-programs-4 | /Program 35 To count the uppercase and lowercase characters in the given string. unresolved.py | 458 | 4.125 | 4 | #To count the uppercase and lowercase characters in the given string.
string=input("")
j='a'
lower=0
upper=0
space=0
for i in string:
for j in range(65,92):
if chr(j) in i:
upper=upper+1
elif j==" ":
space=space+1
for j in range(97,123):
if chr(j) in i:
lower=lower+1
#print(chr(j))
print("There are",lower-space,"lower characters and",upper,"upper characters.") | true |
84650242ab531d3a0755452b8c6eb4476e0a710c | dncnwtts/project-euler | /1.py | 582 | 4.21875 | 4 | # If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these
# multiples is 23.
#
# Find the sum of all the multiples of 3 or 5 below 1000.
def multiples(n,k):
multiples = []
i = 1
while i < n:
if k*i < n:
multiples.append(k*i)
i += 1
else:
return multiples
m3 = multiples(10,3)
m5 = multiples(10,5)
mults = m3 + m5
answer = sum(set(mults))
assert answer == 23, "Test case failed, I got {0}".format(answer)
m3 = multiples(1000,3)
m5 = multiples(1000,5)
mults = m3 + m5
answer = sum(set(mults))
print(answer)
| true |
e047b285aa5bf1b187187c52a22fae191836ed0f | chubaezeks/Learn-Python-the-Hard-Way | /ex19.py | 1,804 | 4.3125 | 4 | #Here we defined the function by two (not sure what to call them)
def cheese_and_crackers (cheese_count, boxes_of_crackers):
print "You have %d cheese!" % cheese_count
print "You have %d boxes of crackers!" % boxes_of_crackers
print "Man that's enough for a party!"
print "Get a blanket.\n"
#We take that function and give it a number directly, so no need to define what's in the function
#Just give the function numbers
print "We can just give the funtion numbers directly:"
cheese_and_crackers (20,30)
#We can also create variables that contain numbers
print "OR, we can use variables from our script:"
amount_of_cheese = 10
amount_of_crackers = 50
#Then run the function by those variables
cheese_and_crackers(amount_of_cheese, amount_of_crackers)
#Or we can run calculations within the function too
print "We can even do math inside too:"
cheese_and_crackers(10 + 20, 5 +6)
#Remember those variables we created earlier? We can also include them in the function
#as well as numbers to run calculations
print "And we can combine the two, variables and math:"
cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)
def me_and_you (chuba,mo):
print "You love %d" % chuba
print "I love %d" % mo
print "We both love each other.\n"
print "We can represent ourselves as numbers!:"
me_and_you (100,100)
print "We can add variables and use it within the function:"
half_of_me = 0.5
half_of_you = 0.5
print " Let's work the math of both of us:"
me_and_you (25+25, 25+25)
print " We combine numbers and variables to get more of us:"
me_and_you (half_of_me + 0.5, half_of_you + 0.5)
me= 10 +10
you=10+10
print "What other combination can we run?:"
me_and_you(half_of_me,half_of_you)
print "What happens when we make a family?:"
me_and_you(me + 1, you + 1)
| true |
965cd05ce217b1b5d27cefb89b62935dc250a692 | hmkthor/play | /play_006.py | 590 | 4.40625 | 4 | """
Change a Range of Item Values
To change the value of items within a specific range, define a list with the new values,
and refer to the range of index numbers where you want to insert the new values:
"""
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist)
thislist = ["apple", "banana", "cherry"]
thislist[1] = ["blackcurrant", "watermelon"]
print(len(thislist))
print(thislist)
thislist = ["apple", "banana", "cherry"]
thislist[1:2] = ["blackcurrant", "watermelon"]
print(len(thislist))
print(thislist) | true |
359ce1c69a952d51fd9024adade90be51e6ebb00 | LiuPengPython/algorithms | /algorithms/strings/is_rotated.py | 324 | 4.3125 | 4 | """
Given two strings s1 and s2, determine if s2 is a rotated version of s1.
For example,
is_rotated("hello", "llohe") returns True
is_rotated("hello", "helol") returns False
accepts two strings
returns bool
"""
def is_rotated(s1, s2):
if len(s1) == len(s2):
return s2 in s1 + s1
else:
return False | true |
b1a9fee52ca6eae1ee380a0d95491d735c7360bd | jeantardelli/wargameRepo | /wargame/designpatterns/strategies_traditional.py | 1,633 | 4.15625 | 4 | """strategies_traditional
Example to show one way of implementing different design pattern strategies
in Python.
The example shown here resembles a 'traditional' implementation in Python
(traditional = the one you may implement in languages like
C++). For a more Pythonic approach, see the file strategies_pythonic.py.
This module is compatible with Python 3.6.x.
RUNNING THE PROGRAM:
Assuming you have python in your environment variable PATH, type the following
in the command prompt to run the program:
$ python name_of_the_file.py
(Replace name_of_the_file.py with the name of this file)
:copyright: 2020, Jean Tardelli
:license: The MIT license (MIT). See LICENSE file for further details.
"""
from strategypattern_traditional_jumpstrategies import CanNotJump, PowerJump
from traditional_dwarffighter import DwarfFighter
from traditional_unitfactory import UnitFactory
from traditional_unitfactory_kingdom import Kingdom
if __name__ == '__main__':
# Strategy Example
print("Strategy Pattern")
print("="*17)
jump_strategy = CanNotJump()
dwarf = DwarfFighter("Dwarf", jump_strategy)
print("\n{STRATEGY-I} Dwarf trying to jump:")
dwarf.jump()
print("-"*56)
# Optionally change the jump strategy later
print("\n{STRATEGY-II} Dwarf given a 'magic potion' to jump:")
dwarf.set_jump_strategy(PowerJump())
dwarf.jump()
print("-"*56)
# Factory example
print("\nFactory Example")
print("="*17)
factory = UnitFactory()
k = Kingdom(factory)
elf_unit = k.recruit("ElfRider")
print("Created an instance of: {0}".format(elf_unit.__class__.__name__))
| true |
93b2af4c8f1a23483747d04ea3902c644b581543 | jeantardelli/wargameRepo | /wargame/performance-study/pool_example.py | 1,201 | 4.375 | 4 | """pool_example
Shows a trivial example on how to use various methods of the class Pool.
"""
import multiprocessing
def get_result(num):
"""Trivial function used in multiprocessing example"""
process_name = multiprocessing.current_process().name
print("Current process: {0} - Input number: {1}".format(process_name, num))
return 10 * num
if __name__ == '__main__':
numbers = [2, 4, 6, 8, 10]
# Create two worker processes.
pool = multiprocessing.Pool(3)
# Use Pool.apply method to run the task using pools of processes
#mylsit = [pool.apply(get_result, args=(num,) for num in numbers]
# Use Pool.map method to run the task using the pool of processes
#mylist = pool.map(func=get_result, iterable=numbers)
# Use Pool.apply_async method to run the task
results = [pool.apply_async(get_result, args=(num,))
for num in numbers]
# The elements of results list are instances of Pool.ApplyResult
# Use the object's get() method to get the final values.
mylist = [p.get() for p in results]
# Stop the worker processes
pool.close()
# Join the processes
pool.join()
print("Output: {0}".format(mylist))
| true |
d37a677d52bcb30328947235f0198a9447ddeb34 | jeantardelli/wargameRepo | /wargame/GUI/simple_application_2.py | 1,025 | 4.125 | 4 | """simple_application_2
A 'Hello World' GUI application OOP using Tkinter module.
"""
import sys
if sys.version_info < (3, 0):
from Tkinter import Tk, Label, Button, LEFT, RIGHT
else:
from tkinter import Tk, Label, Button, LEFT, RIGHT
class MyGame:
def __init__(self, mainwin):
"""Simple Tkinter GUI example that shows a label and an exit button.
:param mainwin: The Tk instance (also called 'root' sometimes)
"""
lbl = Label(mainwin, text="Hello World!", bg='yellow')
exit_button = Button(mainwin, text='Exit',
command=self.exit_btn_callback)
# pack the widgets
lbl.pack(side=LEFT)
exit_button.pack(side=RIGHT)
def exit_btn_callback(self):
"""Callback function to handle the button click event."""
mainwin.destroy()
if __name__ == '__main__':
# Create the main window or Tk instance
mainwin = Tk()
mainwin.geometry("140x40")
game_app = MyGame(mainwin)
mainwin.mainloop()
| true |
c72fb1953ee65169041fa399508fbd5204986270 | yeti98/LearnPy | /src/basic/TypeOfVar.py | 978 | 4.125 | 4 |
#IMMUTABLE: int,
## Immutable vs immutable var
#Case3:
# default parameter for append_list() is empty list lst []. but it is a mutable variable. Let's see what happen with the following codes:
def append_list(item, lst=[]):
lst.append(item)
return lst
print(append_list("item 1")) # ['item 1']
print(append_list("item 2")) # ['item 1', 'item 2']
# Shouldn't use mutable var as a parameter
def append_list(item, lst= None):
if lst is None:
lst = []
lst.append(item)
return lst
#Case2: don't use += for string, because string is immutable. Instead, use join() method
msg= ""
for i in range(1000):
msg+= "hello"
# each for loop, new msg varible created and that make RAM quickly full
#Case1: //list is mutable
def double_list(lists):
for i in range(len(lists)):
lists[i] = lists[i]*2
return lists
lists = [x for x in range(1, 12)]
doubled = double_list(lists)
for i in range(len(lists)):
print(doubled[i] / lists[i])
| true |
0243e8d54259a3cecd9e84443bae674a66f090f7 | amandamurray2021/Programming-Semester-One | /labs/week06-functions/menu2.py | 801 | 4.34375 | 4 | # Q3
# This program uses the function from student.py.
# It keeps displaying the menu until the user picks Q.
# If the user chooses a, then call a function called doAdd ().
# If the user chooses v, then call a function called doView ().
def displayMenu ():
print ("What would you like to do?")
print ("\t (a) Add new student")
print ("\t (v) View students")
print ("\t (q) Quit")
choice = input ("Type one letter (a/v/q):").strip ()
return choice
def doAdd ():
print ("in adding")
def doView ():
print ("in viewing")
# main program
choice = displayMenu ()
while (choice != 'q'):
if choice == 'a':
doAdd ()
elif choice == 'v':
doView ()
elif choice != 'q':
print ("\n\n please select either a, v or q")
choice = displayMenu () | true |
2df05235e11b4f969f147ffa6dcde19ceb0c0dec | VB-Cloudboy/PythonCodes | /10-Tuples/02_Access-Tuple.py | 403 | 4.125 | 4 | mytuple = (100,200,300,400,500,600,700,800,900)
#1. Print specific postion of the tuples starting from Right
print(mytuple[2])
print(mytuple[4])
print(mytuple[5])
#2. Print specific postion of the tuples starting from Left
print(mytuple[-3])
print(mytuple[-5])
print(mytuple[-4])
#3. Slicing (Start: Stop: Stepsize)
print(mytuple[:])
print(mytuple[1:3])
print(mytuple[::-3])
print(mytuple[-1::-5])
| true |
8c326cefac9c979874f8a03334934c685a88c953 | forthing/leetcode-share | /python/152 Maximum Product Subarray.py | 813 | 4.21875 | 4 | '''
Find the contiguous subarray within an array (containing at least one number) which has the largest product.
For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6.
'''
class Solution(object):
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
positive, negative = nums[0], nums[0]
result = nums[0]
for num in nums[1:]:
positive, negative = max(num, positive * num, negative * num), min(num,
positive * num, negative * num)
result = max(result, positive)
return result
if __name__ == "__main__":
assert Solution().maxProduct([2, 3, -2, 4]) == 6 | true |
88ddaec1c09a46fac173c4b520c6253b59aad09b | kmair/Graduate-Research | /PYOMO_exercises_w_soln/exercises/Python/fcn_soln.py | 1,248 | 4.40625 | 4 | ## Write a function that takes in a list of numbers and *prints* the value of the largest number. Be sure to test your function.
def print_max_value(nums):
print("The max value is: ")
print(max(nums))
## Write a function that takes a list of numbers and *returns* the largest number
def max_value(nums):
return max(nums)
## Do so without using any built-in functions
def my_max_value(nums):
tmp = nums[0]
for i in range(1, len(nums)):
if nums[i] > tmp:
tmp = nums[i]
return tmp
## Call both functions on a couple different lists of numbers to verify they return the same value
l1 = [1, 3, 0, 5, -2]
ans1 = max_value(l1)
print(ans1)
ans2 = my_max_value(l1)
print(ans2)
l2 = [12, 0, 11.9]
print(max_value(l2))
print(my_max_value(l2))
## Write a function that takes a list of numbers and returns a dict consisting of the smallest and largest number
## (use keys 'smallest' and 'largest'). Be sure to test your function.
def max_and_min(nums):
return {'smallest': min(nums), 'largest': max(nums)}
## Write a function that takes in two lists and prints any common elements between them
## hint: check if an item is in a list using:
## if item in list
def get_common(l1, l2):
for i in l1:
if i in l2:
print(i)
| true |
82d3e7c695fbab62b222781240a1865cfe877151 | Kaushalendra-the-real-1/Python-assignment | /Q2.py | 779 | 4.125 | 4 | # class Person:
# def __init__(self):
# print("Hello Reader ... ")
# class Male(Person):
# def get_gender(self):
# print("I am from Male Class")
# class Female(Person):
# def get_gender(self):
# print("I am from Female Class")
# Obj = Female()
# Obj.get_gender()
# ----------------------------------------------------------------------------------------------------------------------
# Bonus Section
from abc import ABC, abstractmethod
class Person(ABC):
@abstractmethod
def get_gender(self):
return 0
class Male(Person):
def get_gender(self):
print("I am from Male Class")
class Female(Person):
def get_gender(self):
print("I am from Female Class")
unknown = Person() #expecteed to throw an error.
| true |
e33a070506458cacbf4d52304982c491f2c9980d | xynicole/Python-Course-Work | /lab/435/ZeroDivideValue.py | 595 | 4.25 | 4 | def main():
print("This program will divide two numbers of your choosing for as long as you like\n")
divisorStr = input("Input a divisor: ")
while divisorStr:
dividendStr = input("Input a dividend: ")
try:
divisor = int(divisorStr)
dividend = int(dividendStr)
print (dividend / divisor)
except ZeroDivisionError:
print("You cannot divide by zero\n")
except ValueError:
print("You must input a number\n")
except Exception:
print("Something happened\n")
divisorStr = input("Input a divisor: ")
main()
| true |
240868c7fb1cf39a3db78c9c5912d7dc93c79e45 | SamuelMontanez/Shopping_List | /shopping_list.py | 2,127 | 4.1875 | 4 | import os
shopping_list = []
def clear_screen():
os.system("cls" if os.name == "nt" else "clear")
def show_help():
clear_screen()
print("What should we pick up at the store?")
print("""
Enter 'DONE' to stop adding items.
Enter 'HELP' for this help.
Enter 'SHOW' to see your current list.
Enter 'REMOVE' to delete an item from your list.
""")
def add_to_list(item):
show_list()
if len(shopping_list): #If there are items in the shopping list
position = input("Where should I add {}?\n"
"Press ENTER to add to the end of the list\n"
"> ".format(item))
else:
position = 0 #This means if this is the first item in the list then the position is 0.
try:
position = abs(int(position)) #abs stands for absolute, so if a user gives us -5 the abs of that is 5.
except ValueError:
position = None #If value error occurs, then 'none' means dont put the item in the list.
if position is not None:
shopping_list.insert(position-1, item) #The reason for the -1 is beacuse the user should input 1 for the first spot or 2 for the second spot so the -1 will put it in the correct spot.
else:
shopping_list.append(new_item)
show_list()
def show_list():
clear_screen()
print("Here's your list:")
index = 1
for item in shopping_list:
print("{}. {}".format(index, item))
index += 1
print("-"*10)
def remove_from_list():
show_list()
what_to_remove = input("What would you like to remove?\n> ")
try:
shopping_list.remove(what_to_remove)
except ValueError:
pass
show_list()
show_help()
while True:
new_item = input("> ")
if new_item.upper() == 'DONE' or new_item.upper() == 'QUIT':
break
elif new_item.upper() == 'HELP':
show_help()
continue
elif new_item.upper() == 'SHOW':
show_list()
continue
elif new_item.upper() == 'REMOVE':
remove_from_list()
else:
add_to_list(new_item)
show_list() | true |
ec8887453eaa5f263665f651338a470b4b8c5f7c | lura00/guess_the_number | /main.py | 915 | 4.15625 | 4 | from random import randint
from game1 import number_game
def show_menu():
print("\n===========================================")
print("| Welcome |")
print("| Do you want to play a game? |")
print("| 1. Enter the number game |")
print("| 2. Exit |")
print("===========================================")
while True:
random_value = randint(0,10)
show_menu()
try:
menu_choice = int(input("Make your choice, guess or exit: "))
if menu_choice == 1:
number_game(random_value)
elif menu_choice == 2:
print("Thanks for playing, welcome back! ")
break
else:
print("Thats a strange symbol, I can't seem to understand your input?")
except ValueError:
print("An error occurred, please try another input!")
| true |
18a73e6c8cd9289ce5ba0fd1006dc2ce400e375f | LehlohonoloMopeli/level_0_coding_challenge | /task_3.py | 350 | 4.1875 | 4 | def hello(name):
"""
Description: Accepts the name of an individual and prints "Hello ..." where
the ellipsis represents the name of the individual.
type(output) : str
"""
if type(name) == str:
result = print("Hello " + name + "!")
return result
else:
return "Invalid input!"
| true |
9d07cb1bbb8e780c193dbb19c6c0ef4b83cb7914 | unfo/exercism-python | /bob/bob.py | 723 | 4.25 | 4 | def hey(sentence):
"""
Bob is a lackadaisical teenager. In conversation, his responses are very limited.
Bob answers 'Sure.' if you ask him a question.
He answers 'Whoa, chill out!' if you yell at him.
He says 'Fine. Be that way!' if you address him without actually saying
anything.
He answers 'Whatever.' to anything else.
"""
sentence = sentence.strip()
response = "Whatever."
if len(sentence) == 0:
response = "Fine. Be that way!"
elif sentence.startswith("Let's"):
# This is just silly. If it ends with an ! then it is shouting...
response = "Whatever."
elif sentence[-1] == "!" or sentence.isupper():
response = "Whoa, chill out!"
elif sentence[-1] == "?":
response = "Sure."
return response | true |
be97e8da8f3733fbb6c0a2e8abb0b950a11181c4 | fitzcn/oojhs-code | /loops/printingThroughLoops.py | 313 | 4.125 | 4 | """
Below the first 12 numbers in the Fibonacci Sequence are declared in an array list (fibSeq).
Part 1, Use a loop to print each of the 12 numbers.
Part 2, use a loop to print each of the 12 numbers on the same line.
"""
fibSeq = ["1","1","2","3","5","8","13","21","34","55","89","144"]
#part 1
#part 2
| true |
d190cf17e29502fd451ff812f68414fef94eeec9 | aysin/Python-Projects | /ex32.py | 538 | 4.65625 | 5 | #creating list while doing loops
the_count = [1, 2, 3, 4, 5]
fruits = ['apple', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
#this first kind of for loop goes through a list
for n in the_count:
print "This is count %d." % n
#same as above
for n in fruits:
print "A fruit type is: %s." % n
for n in change:
print "I got: %r." % n
#build an empty list
element = []
for n in range(0,6):
print "Adding %d to the list." % n
element.append(n)
for i in element:
print "elements was: %d" % i | true |
cde03d01900ffa7f01f5f80e4bfc869454ac8116 | AshTiwari/Python-Guide | /OOPS/OOPS_Abstract_Class_and_Method.py | 720 | 4.5625 | 5 | #abstract classes
# ABC- Abstract Base Class and abstractmethod
from abc import ABC, abstractmethod
print('abstract method is the method user must implement in the child class.')
print('abstract method cannot be instantiated outside child class.')
print('\n\n')
class parent(ABC):
def __init__(self):
pass
@abstractmethod #it is a decorator.
def square():
pass
class child(parent):
def __init__(self,num):
self.num = num
def square(self): # if not implemented here, it will give TypeError:
return self.num**2
Child =child(5)
print(Child.square())
try:
Parent =parent()
except TypeError:
print('Cant instantiate abstract class.')
| true |
94555b4909e244e1e8e9e23bb97ad48b81308118 | jinliangXX/LeetCode | /380. Insert Delete GetRandom O(1)/solution.py | 1,462 | 4.1875 | 4 | import random
class RandomizedSet(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.result = list()
self.index = dict()
def insert(self, val):
"""
Inserts a value to the set. Returns true if the set did not already contain the specified element.
:type val: int
:rtype: bool
"""
if val in self.index:
return False
else:
self.result.append(val)
self.index[val] = len(self.result) - 1
return True
def remove(self, val):
"""
Removes a value from the set. Returns true if the set contained the specified element.
:type val: int
:rtype: bool
"""
if val in self.index:
index = self.index[val]
last_val = self.result[len(self.result) - 1]
self.result[index] = last_val
self.index[last_val] = index
self.result.pop()
self.index.pop(val,0)
return True
else:
return False
def getRandom(self):
"""
Get a random element from the set.
:rtype: int
"""
return self.result[random.randint(0, len(self.result) - 1)]
# Your RandomizedSet object will be instantiated and called as such:
# obj = RandomizedSet()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom()
| true |
076a40fc02b0791eedaae92747394f46170a9678 | prathyusak/pythonBasics | /errors.py | 2,720 | 4.21875 | 4 | #Syntax Errors and Exceptions
#while True print('Hello world') => syntax error
#ZeroDivisionError =>10 * (1/0)
#NameError => 4 + spam*3
#TypeError => '2' + 2
#################
# Handling Exceptions
import sys
def this_fails():
x = 1/0
while True:
try:
x = int(input("Please enter a number: "))
this_fails()
break
except ValueError:
print("Oops! That was no valid number. Try again...")
except (RuntimeError, TypeError, NameError): #except clause can have multiple exceptions
pass
except ZeroDivisionError as err:
print('Handling run-time error:', err)
break
except: #empty exception name serves as wildcard
print("Unexpected error:", sys.exc_info()[0])
raise #raising exceptions
################
#Exception chaining : when exception raised from except or finally block
# try:
# open('database.sqlite')
# except IOError as ioerr :
# raise RuntimeError from ioerr
# #To disable exception chaining
# try:
# open('database.sqlite')
# except IOError as ioerr :
# raise RuntimeError from None
################
#try except else finally
def divide(x, y):
try:
result = x / y
except ZeroDivisionError:
print("division by zero!")
else: #additional code in try block
print("result is", result)
finally: # executes at all times , cleanup acions
print("executing finally clause")
################
#User defined exceptions
class Error(Exception):
"""Base class for exceptions in this module."""
pass
class InputError(Error):
"""Exception raised for errors in the input.
Attributes:
expression -- input expression in which the error occurred
message -- explanation of the error
"""
def __init__(self, expression, message):
self.expression = expression
self.message = message
class TransitionError(Error):
"""Raised when an operation attempts a state transition that's not
allowed.
Attributes:
previous -- state at beginning of transition
next -- attempted new state
message -- explanation of why the specific transition is not allowed
"""
def __init__(self, previous, next, message):
self.previous = previous
self.next = next
self.message = message
#####################
class B(Exception):
pass
class C(B):
pass
class D(C):
pass
for cls in [B, C, D]:
try:
raise cls()
except B:
print("B")
# raise InputError('erro','mess')
except D: #an except clause listing a derived class is not compatible with a base class
print("D")
except C:
print("C")
| true |
57e443004e07c95bc99217d700e6b4f40f5c8a5f | yamaz420/PythonIntro-LOLcodeAndShit | /pythonLOL/vtp.py | 2,378 | 4.125 | 4 | from utils import Utils
class VocabularyTrainingProgram:
words = [
Word("hus", "house")
Word("bil", "car")
]
def show_menu(self):
choice = None
while choice !=5:
print(
'''
1. Add a new word
2. Shuffle the words in the list
3. Take the test
4. show all the words
5. Exit
'''
)
choice = Utils.get_int_input("Enter your menu choice: ")
if choice < 1 or choice > 5:
print("Error: not a valid menu choice")
elif choice != 5:
# print(self.menu_switcher(str(choice)))
# pass # invoke the corresponding method
self.menu_switcher(str(choice))()
else:
print("Closing the game...")
def menu_switcher(self, choice):
switch = {
"1": self.add_new_word,
"2": self.shuffle_words,
"3": self.take_the_test,
"4": self.show_all_words
}
return switch[choice]
def add_new_word(self):
swedish_word = Utils.get_string_input("Enter the swedish word: ")
english_word = Utils.get_string_input("Enter english word: ")
self.words.append(word(swedish_word, english_word))
print()
print("The new word has been added")
def show_all_words(self):
for word in self.words:
print(word.to_string())
def shuffle_words(self):
shuffle(self.words)
print("the words have been shuffeled")
def take_the_test(self):
points = 0
max_failures = 3
misses = 0
for word in self.words:
print()
answer = Utils.get_string_input(f"What is the translation for {word.get_english_word()}?")
if word.verify_answer(answer):
points += len(word.get_english_word())
print("CORRECT!")
else:
misses += 1
print(f"WronG! The Correct answer is {word.get_english_word()}.")
if misses = max_failures:
print()
print("GAME OVAH BIATCH, go practice nooooob")
print()
print(f"the test is ovah matey u focken focker fuuuuuuuuuuuuuuuuuuuck you got {points}")
| true |
4f55c17a043ee6a78b76220c8c25240a21b8195c | yamaz420/PythonIntro-LOLcodeAndShit | /pythonLOL/IfAndLoops.py | 1,881 | 4.15625 | 4 | #-----------!!!INDENTATION!!!-----------
# age = int(input("What is your age?"))
# if age >= 20:
# print("You are grown up, you can go to Systemet!")
# else:
# print("you are to young for systemet...")
# if age >= 20:
# if age >= 30:
# print("Allright, you can go to systemet for me, i hate showing ID")
# else:
# print("you can fo to systemet, just don't forget your ID...")
# else:
# print("you are too young for systemet")
### "or" = "||" "and" = "&&"
# if (day == "friday" or day == "Saturday") and age >= 18:
# print("is is a foot day to hit the club")
# elif day == "monday" or day == "tuseday":
# print("noooo, i hate these days")
# numbers = [1,2,3,45]
# if 45 in numbers:
# print("exists")
# else:
# print("no existo")
# truthy and falsy values also exist in python.
my_list = []
if my_list: # my_list.size() > 0 - in Java"
print(my_list)
else:
print("the list is empty")
i = 0 ## while-LOOP
while i < 10:
print (i, end = " ")
i += 1
# for-each-LOOP
names = ["hej", "niklas", "Erik"]
for name in names:
print(name, end = " ")
print(i, end = "\U0001F606") #Smiley ahahah #tackPelle
for i in range(10):
print(i, end = " ")
for i in range (1,20,2):
print (i, end= " ")
numbers = [1,24,12,52,26]
for i in range(len(numbers)):
print(numbers[i], end = " ")
persons = [ #list=arraylist of persons
{
"name": "Erik",
"age": 28
},
{
"name": "Martin",
"age": 34
},
{
"name": "Louise",
"age": 30
}
]
for person in persons:
print(person)
'''
multi-line-Commment
lalala
hahahahhahahahahahaHAH.
'''
just_names = [person["name"] for person in persons]
print(just_names)
over_30 = [person for person in persons if person["age"] >= 30] ##sortera persons-lista över 30
print(over_30)
| true |
421a3a05798ec7bfdfd104994e220ffb9f2613f7 | Tornike-Skhulukhia/IBSU_Masters_Files | /code_files/__PYTHON__/lecture_2/two.py | 1,401 | 4.1875 | 4 |
def are_on_same_side(check_p_1, check_p_2, point_1, point_2):
'''
returns True, if check points are on the same side of a line
formed by connecting point_1 and point_2
arguments:
1. check_p_1 - tuple with x and y coordinates of check point 1
2. check_p_2 - tuple with x and y coordinates of check point 2
2. point_1 - tuple with x and y coordinates of point 1
3. point_2 - tuple with x and y coordinates of point 2
'''
(x_3, y_3), (x_4, y_4), (x_1, y_1), (x_2, y_2) = check_p_1, check_p_2, point_1, point_2
value_1 = (x_3 - x_1) * (y_2 - y_1) - (y_3 - y_1) * (x_2 - x_1)
value_2 = (x_4 - x_1) * (y_2 - y_1) - (y_4 - y_1) * (x_2 - x_1)
# will be True only when value_1 * value_2 > 0, False otherwise
result = (value_1 * value_2 > 0)
return result
# test | run only if file is executed directly
if __name__ == "__main__":
point_1 = (1, 2)
point_2 = (5, 6)
check_points = [
(3, 4),
(1, 1),
(2, 0),
(0, 2),
]
# check point to every other point
for index_1, check_p_1 in enumerate(check_points):
for check_p_2 in check_points[index_1 + 1:]:
check_result = are_on_same_side(check_p_1, check_p_2, point_1, point_2)
print(f'Points {check_p_1} and {check_p_2} are {"not " if not check_result else ""}on the same side of a line')
| true |
0fdc190bda0f1af4caf7354f380ce94134c70c78 | cizamihigo/guess_game_Python | /GuessTheGame.py | 2,703 | 4.21875 | 4 | print("Welcome To Guess: The Game")
print("You can guess which word is that one: ")
def check_guess(guess, answer):
global score
Still = True
attempt = 0
var = 2
global NuQuest
while Still and attempt < 3 :
if guess.lower() == answer.lower() :
print("\nCorrect Answer " + answer)
Still = False
score += 1
NuQuest += 1
else :
if attempt < 2 :
guess = input("Wrong answer. Try again. {0} chance(s) reamining . . .".format(var))
var = 2 - 1
attempt += 1
pass
if attempt == 3 :
print("The correct answer is " + answer)
NuQuest += 1
score = 0
NuQuest = 0
guess1 = input("Designe une oeuvre littéraire en vers: ")
check_guess(guess1,'Poème')
guess1 = ""
guess1 = input("Designe ce qui est produit par un ouvrier un artisan un travail quelconque: ")
check_guess(guess1,'Ouvrage')
guess1 = ""
guess1 = input("En anglais DOOM quelle est sa variance en français???: ")
check_guess(guess1,'destin')
guess1 = ""
guess1 = input("Désigne Un Habittant de Rome: ")
check_guess(guess1,'Romain')
guess1 = ""
guess1 = input("Ce qui forme Un angle droit est dit: ")
check_guess(guess1,'Perpendiculaire')
guess1 = ""
guess1 = input("Adjectif, désignant ce qui est rélatif aux femmes: ")
check_guess(guess1,'Féminin')
guess1 = ""
guess1 = input("Nom masculin désignant le corps céleste: ")
check_guess(guess1,'astre')
guess1 = ""
guess1 = input("Ma messe, la voici ! c'est la Bible, et je n'en veux pas d'autre ! de qui on tient cette citation ")
check_guess(guess1,"Jean Calvin")
guess1 = ""
guess1 = input("Le vin est fort, le roi est plus fort, les femmes le sont plus encore, mais la vérité est plus forte que tout. ! de qui tenons-nous cette citation ")
check_guess(guess1,"Martin Luther")
guess1 = ""
mpt = "plrboèem"
guess1 = input("Voici Un anagramme: " + str(mpt.upper()) +" Trouvez en un mot complet : ")
check_guess(guess1,"Problème")
guess1 = ""
mpt = "uonjcgnaiso"
guess1 = input("Voici Un anagramme: " + str(mpt.upper()) +" Trouvez en un mot complet : ")
check_guess(guess1,"conjugaison")
guess1 = ""
guess1 = input("Which is the fastest land animal?")
check_guess(guess1,"Cheetah")
##################################################
# OTHER QUESTIONS CAN BE ADDED LATERLY. #
##################################################
Prcentage = (score * 100 ) / NuQuest
print("Votre Pourcentage a ce test a ete de : {0}".format(Prcentage))
print("Your score is : " +str(score) + " Sur " + str(NuQuest))
######################################## THE END ###################################### | true |
0ebfa784abeddd768186f99209602dd7ef870e56 | feleHaile/my-isc-work | /python_work_RW/6-input-output.py | 1,745 | 4.3125 | 4 | print
print "Input/Output Exercise"
print
# part 1 - opening weather.csv file
with open ('weather.csv', 'r') as rain: # opens the file as 'read-only'
data = rain.read() # calls out the file under variable rain and reads it
print data # prints the data
# part 2 - reading the file line by line
with open ('weather.csv', 'r') as rainy:
line = rainy.readline() # uses .readline()
while line: # while there is still data to read
print line # print the line
line = rainy.readline() # need to re-iterate here so it goes beyond just line 1.
print "That's the end of the data"
# part 3 - using a loop and collecting just rainfall values
with open ('weather.csv', 'r') as rainfall:
header = rainfall.readline() # this reads and discards the first line of the data (we dont want to use the header line with the text in it
droplet = [] # creating an empty list to store rainfall data
for line in rainfall.readlines():
# readlines reads the whole file, readline just takes the first line
r = line.strip() .split(',')[-1] # takes last variable, see below
r = float(r) # make it a float (with decimals)
droplet.append(r) # append r to droplet list (store the data)
print droplet # prints the data for rainfall
with open ('myrain.txt', 'w') as writing: # creates a text file with the result
for r in droplet: # prints the rainfall results in the text file
writing.write(str(r) + '\n')
"""
Explantation for r = line.strip() .split(',')[-1]
one line as example: 2014-01-01,00:00,2.34,4.45\n
line.strip() removes the \n, so takes just one line without the paragraphing
.split(',') splits the list by the comma, and takes each as a seperate item
.split(',')[-1] means, seperate out and then take the last item
"""
print
| true |
a40fd3e7668b013a356cfa8559e993e770cc7231 | feleHaile/my-isc-work | /python_work_RW/13-numpy-calculations.py | 2,314 | 4.3125 | 4 | print
print "Calculations and Operations on Numpy Arrays Exercise"
print
import numpy as np # importing the numpy library, with shortcut of np
# part 1 - array calculations
a = np.array([range(4), range(10,14)]) # creating an array 2x4 with ranges
b = np.array([2, -1, 1, 0]) # creating an array from a list
# multiples the array by each other, 1st line of a * b, then the 2nd line of a * b
multiply = a * b
b1 = b * 1000 # creates a new array with every item in b * 1000
b2 = b * 1000.0 # creates new array similar to b1 but with floats rather than int
b2 == b1 # yes, this is True. b2 is a float but they are the same
print b1.dtype, b2.dtype # how to print the type of each
# part 2 - array comparisons
arr = np.array([range(10)]) # creates an array with items 0 to 9
print arr < 3 # prints true and false values in the array where item is <3
print np.less(arr, 3) # exactly the same as above, just different format of asking
# sets a condition to call true or false based on two parameters, <3 OR > 8
condition = np.logical_or(arr < 3, arr > 8)
print "condition: ", condition
# uses "where" function to create new array where value is arr*5 if "condition" is true, and arr*-5 where "condition" is false
new_arr = np.where(condition, arr * 5, arr * -5)
# part 3 - mathematical functions working on arrays
"""
Calculating magnitudes of wind, where a minimum acceptable value is 0.1, and all values below this are set to 0.1. Magnitude of wind is calculated by the square-root of the sum of the squares of u and v (which are east-west and north-south wind magnitudes)
"""
def calcMagnitude(u, v, minmag = 0.1): # these are the argument criteria
mag = ((u**2) + (v**2))**0.5 # the calculation
# sets a where function so that minmag is adopted where values are less than 0.1:
output = np.where(mag > minmag, mag, minmag)
return output
u = np.array([[4, 5, 6],[2, 3, 4]]) # the east-west winds
v = np.array([[2, 2, 2],[1, 1, 1]]) # the north-south winds
print calcMagnitude(u,v) # calls the argument with the u and v arrays
# testing on different wind values, these values use the minmag clause
u = np.array([[4, 5, 0.01],[2, 3, 4]]) # the east-west winds
v = np.array([[2, 2, 0.03],[1, 1, 1]]) # the north-south winds
print calcMagnitude(u,v) # calls the argument with the u and v arrays
print
| true |
12f3789e81a69e4daa75f9497dd94f382f5f0153 | zamunda68/python | /main.py | 507 | 4.21875 | 4 | # Python variable function example
# Basic example of the print() function with new line between the words
print("Hello \n Marin")
print("Bye!")
# Example of .islower method which returns true if letters in the variable value are lower
txt = "hello world" # the variable and its value
txt.islower() # using the .islower() boolean method to print true or false
print("\n") # print a new line
print(txt) # print the variable
# Example of .isupper method
txt2 = "UPPER"
y = txt2.isupper()
print("\n", y)
| true |
1ef4a7869a5048f6d66fbdb56203fa2f0198fb22 | zamunda68/python | /dictionaries.py | 1,116 | 4.75 | 5 | """ Dictionary is a special structure, which allows us to store information in what is called
key value pairs (KVP). You can create one KVP and when you want to access specific information
inside of the dictionary, you can just refer to it by its key """
# Similar to actual dictionary, the word is the key and the meaning is the value
# Word - meaning == Key - value
# Every dictionary has a name:
# directory_name = {key_value_pair1, key_value_part2,}
monthConversions = {
"Jan": "January", # "Jan" is the key, "January" is the value
"Feb": "February",
"Mar": "March",
"Apr": "April",
"May": "May",
"Jun": "June",
"Jul": "July",
"Aug": "August",
"Sep": "September",
"Oct": "October",
"Nov": "November",
"Dec": "December",
}
# Printing out the value of the key, by referring to the key itself:
print(monthConversions["Nov"])
# Another way to retrieve the value is using the "get()" function:
print(monthConversions.get("Dec"))
# If we want to pass a default value, which is not listed in the list above:
print(monthConversions.get("Dec", "Not a valid key"))
| true |
a95b3e4a2102e76c1a6b4932d6053a66b9593d5d | b-zhang93/CS50-Intro-to-Computer-Science-Harvard-Problem-Sets | /pset6 - Intro to Python/caesar/caesar.py | 1,022 | 4.21875 | 4 | from cs50 import get_string
from cs50 import get_int
from sys import argv
# check for CLA to be in order and return error message if so
if len(argv) != 2:
print("Usage: ./caesar key k")
exit(1)
# checks for integer and positive
elif not argv[1].isdigit():
print("Usage: ./caesar key k")
exit(1)
# defining the key and converting it to an integer
key = argv[1]
k = int(key)
# prompt for user and return cipher
word = get_string("plaintext: ")
print("ciphertext: ", end="")
# c is the iterator for each letter in input
for c in word:
# for lowercase letters to convert and mod to wrap around then convert back to letter
if c.islower():
x = (ord(c) - 97 + k) % 26
y = 97 + x
z = chr(y)
print(z, end="")
# do the same for upper case
elif c.isupper():
x = (ord(c) - 65 + k) % 26
y = 65 + x
z = chr(y)
print(z, end="")
# every other non-alpha char just print it out no conversion
else:
print(c, end="")
print()
| true |
c891f23d90e49fa066d06e90fd5ad2d45c9afd7d | gmarler/courseware-tnl | /labs/py3/decorators/memoize.py | 1,122 | 4.1875 | 4 | '''
Your job in this lab is to implement a decorator called "memoize".
This decorator is already applied to the functions f, g, and h below.
You just need to write it.
HINT: The wrapper function only needs to accept non-keyword arguments
(i.e., *args). You don't need to accept keyword arguments in this lab.
(That is more complex to do, which is why it's saved for a later
next lab.)
>>> f(2)
CALLING: f 2
4
>>> f(2)
4
>>> f(7)
CALLING: f 7
49
>>> f(7)
49
>>> g(-6, 2)
CALLING: g -6 2
4.0
>>> g(-6, 2)
4.0
>>> g(6, 2)
CALLING: g 6 2
-2.0
>>> g(6, 2)
-2.0
>>> h(2, 4)
CALLING: h 2 4 42
7
>>> h(2, 4)
7
>>> h(3, 2, 31)
CALLING: h 3 2 31
6
>>> h(3, 2, 31)
6
'''
# Write your code here:
# Do not edit any code below this line!
@memoize
def f(x):
print("CALLING: f {}".format(x))
return x ** 2
@memoize
def g(x, y):
print("CALLING: g {} {}".format(x, y))
return (2 - x) / y
@memoize
def h(x, y, z=42):
print("CALLING: h {} {} {}".format(x, y, z))
return z // (x + y)
if __name__ == '__main__':
import doctest
doctest.testmod()
# Copyright 2015-2017 Aaron Maxwell. All rights reserved.
| true |
3f7a247198d94307902d20edec5016511a4343e6 | kpetrone1/kpetrone1 | /s7hw_mysqrt_final.py | 1,348 | 4.4375 | 4 | #23 Sept 2016 (Homework following Session 7)
#While a few adjustments have been made, the majority of the following code has been sourced from a blog titled "Random Thoughts" by Estevan Pequeno at https://epequeno.wordpress.com/2011/01/04/solutions-7-3/.
#function to test Newton's method vs. math.sqrt() to find square root
#Note: Newton's method is represented below as "mysqrt," and math.sqrt, I believe, is represented as "libmath_method."
import math
def mysqrt(n):
a = float(n)
x = n / 2 #rough estimate
i = 0
while i < 10:
y = (x + n/x) / 2 #Newton's method
x = y
i += 1
return y
def libmath_method(n):
a = float(n)
return math.sqrt(n)
#This function has a mix of int, str and float, so there is a bit of conversion going on.
def test_square_root():
for i in range(1,10):
n = str(mysqrt(i)) #mysqrt() gets int and returns float. Change to str.
l = str(libmath_method(i)) #libmath_method() gets int and returns float. Change to str.
ab = abs(mysqrt(i)-libmath_method(i)) #out as int in as float, no str
if (len(n) or len (l)) == 3:
print(i, n, ' ', 1, ' ', ab)
elif len(n) == 12:
print(i, n, ' ', ab)
else:
print(i, n, l, ' ', ab)
test_square_root() | true |
92297bb3778093c35679b32b2a1ffd22a3339403 | harsh52/Assignments-competitive_coding | /Algo_practice/LeetCode/Decode_Ways.py | 1,874 | 4.1875 | 4 | '''
A message containing letters from A-Z can be encoded into numbers using the following mapping:
'A' -> "1"
'B' -> "2"
...
'Z' -> "26"
To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106" can be mapped into:
"AAJF" with the grouping (1 1 10 6)
"KJF" with the grouping (11 10 6)
Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6" is different from "06".
Given a string s containing only digits, return the number of ways to decode it.
Input: s = "12"
Output: 2
Explanation: "12" could be decoded as "AB" (1 2) or "L" (12).
'''
class Solution:
def numDecodings(self, s: str) -> int:
s = list(s)
#print(s)
dp = [0 for _ in range(len(s))]
dp[0] = 1
if(len(s) == 1 and s[0] == '0'):
return 0
if(s[0] == '0'):
dp[0]=0
for i in range(1,len(s)):
print(s)
#print("in loop")
if(s[i-1] == '0' and s[i] == '0'):
dp[i] = 0
elif(s[i-1] == '0' and s[i] != '0'):
#print("in second")
dp[i] = dp[i-1]
elif(s[i-1] != '0' and s[i] == '0'):
#print("here")
if(s[i-1] == '1' or s[i-1] == '2'):
dp[i] = (dp[i-2] if i>=2 else 1)
print(dp)
else:
dp[i]=0
else:
#print("in last")
temp = ''.join(map(str,s[i-1:i+1]))
if(int(temp) <= 26):
dp[i] = dp[i-1] + (dp[i-2] if i>=2 else 1)
else:
dp[i] = dp[i-1]
#print("test")
return(dp[-1])
| true |
28f0e5637cd7ca7d5b47451e27e6e1d0ac7db093 | zlatnizmaj/GUI-app | /OOP/OOP-03-Variables.py | 642 | 4.40625 | 4 | # In python programming, we have three types of variables,
# They are: 1. Class variable 2. Instance variable 3. Global variable
# Class variable
class Test():
class_var = "Class Variable"
class_var2 = "Class Variable2"
# print(class_var) --> error, not defined
x = Test()
print(x.class_var)
print(x.class_var2)
# Instance Variables
# This variable is created within class in instance method
class TestIns():
def __init__(self, name, age):
self.name = name
self.age = age
y = TestIns('Y', 9)
print(y.name)
print(y.age)
# Global variable:
# It can be accessed anywhere in the project as it is assigned globally
| true |
1e45cfd30735bc93f3341bb6bfdec05603fa77fc | pravsp/problem_solving | /Python/BinaryTree/solution/invert.py | 1,025 | 4.125 | 4 | '''Invert a binary tree.'''
import __init__
from binarytree import BinaryTree
from treenode import TreeNode
from util.btutil import BinaryTreeUtil
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Invert:
def invertTree(self, root: TreeNode) -> TreeNode:
if root:
right = root.right
left = root.left
root.right = self.invertTree(left)
root.left = self.invertTree(right)
return root
if __name__ == '__main__':
print("Create a binary tree")
bt = BinaryTree()
btutil = BinaryTreeUtil()
btutil.constructBinaryTree(bt)
bt.printTree(traversal=BinaryTree.LevelOrder, verbose=True)
bt.printTree(traversal=BinaryTree.InOrder)
print("Height of the tree: ", bt.getHeight())
bt.printTree(traversal=BinaryTree.LevelOrder, verbose=True)
bt.root = Invert().invertTree(bt.root)
bt.printTree(traversal=BinaryTree.InOrder)
| true |
b6ff3bb38beaea248d13389d5246d449e8e8bf8a | Arushi96/Python | /Radical- Python Assignment Solutions/Loops and Conditions/Question 3.py | 367 | 4.15625 | 4 | #Assignment Questions
#Q: Write a program which calculates the summation of first N numbers except those which are divisible by 3 or 7.
n = int(input ("Enter the number till which you want to find summation: "))
s=0
i=0
while i<=n:
if (i%3==0)or(i%7==0):
#print(i)
i+=1
continue
else:
s=s+i
i=i+1
print("sum is: ", s)
| true |
35025370621c265eff6d02c68d4284525634f5e1 | mtjhartley/codingdojo | /dojoassignments/python/fundamentals/find_characters.py | 568 | 4.21875 | 4 | """
Write a program that takes a list of strings and a string containing a single character, and prints a new list of all the strings containing that character.
Here's an example:
# input
word_list = ['hello','world','my','name','is','Anna']
char = 'o'
# output
new_list = ['hello','world']
"""
def find_characters(lst, char):
new_list = []
for word in lst:
if char in word:
new_list.append(word)
return new_list
word_list = ['hello','world','my','name','is','Anna']
char = 'o'
print find_characters(word_list, char)
| true |
ac0c500a62196c5bf29fe013f86a82946fdb65b2 | mtjhartley/codingdojo | /dojoassignments/python/fundamentals/list_example.py | 854 | 4.28125 | 4 | fruits = ['apple', 'banana', 'orange']
vegetables = ['corn', 'bok choy', 'lettuce']
fruits_and_vegetables = fruits + vegetables
print fruits_and_vegetables
salad = 3 * vegetables
print salad
print vegetables[0] #corn
print vegetables[1] #bok choy
print vegetables[2] #lettuce
vegetables.append('spinach')
print vegetables[3]
print vegetables[2:] #[lettuce, spinach]
print vegetables[1:3] #[bok choy, lettuce]
for index, item in enumerate(vegetables):
item = item.upper()
vegetables[index] = item
print vegetables
index = 0
for food in vegetables:
vegetables[index] = food.lower()
index += 1
print vegetables
#another enumerate example
my_list = ['apple', 'banana', 'grapes', 'pear']
counter_list = list(enumerate(my_list, 1))
print counter_list
numbers = [1,2,3,4]
new_numbers = map(lambda x: x*3, numbers)
print new_numbers | true |
3389a2cb84c667ada3e41ec096592cfdbf6c2e07 | mtjhartley/codingdojo | /dojoassignments/python/fundamentals/compare_array.py | 2,432 | 4.3125 | 4 | """
Write a program that compares two lists and prints a message depending on if the inputs are identical or not.
Your program should be able to accept and compare two lists: list_one and list_two.
If both lists are identical print "The lists are the same".
If they are not identical print "The lists are not the same."
Try the following test cases for lists one and two:
"""
list_one = [1,2,5,6,2]
list_two = [1,2,5,6,2]
list_three = [1,2,5,6,5]
list_four = [1,2,5,6,5,3]
list_five = [1,2,5,6,5,16]
list_six = [1,2,5,6,5]
list_seven = ['celery','carrots','bread','milk']
list_eight = ['celery','carrots','bread','cream']
list_nine = ['a', 'b', 'c']
list_ten = ['a','b','z']
#assumes order matters. if order doesn't matter, would call sorted() or .sort on both lists before checking.
def compare_array_order_matters(lst1, lst2):
if len(lst1) != len(lst2):
print "The lists are not the same"
print "This is because the list lengths are not the same."
else:
for index in range(len(lst1)):
if lst1[index] == lst2[index] and (index == len(lst1)-1):
print lst1[index], lst2[index]
print "The lists are identical"
elif lst1[index] == lst2[index]:
print lst1[index], lst2[index]
continue
else:
print lst1[index], lst2[index]
print "These items are not the same, thus: "
print "The lists are not the same."
break
compare_array_order_matters(list_one, list_two)
print
compare_array_order_matters(list_three, list_four)
print
compare_array_order_matters(list_five, list_six)
print
compare_array_order_matters(list_seven, list_eight)
print
compare_array_order_matters(list_nine, list_ten)
print
def compare_array_order_doesnt_matter(lst1, lst2):
sorted_lst1 = sorted(lst1)
sorted_lst2 = sorted(lst2)
if sorted_lst1 == sorted_lst2:
print "The lists are equal"
else:
print "The lists are not equal"
print "--------------------------------------------------"
print "Now testing the lists when order doesn't matter"
print
compare_array_order_doesnt_matter(list_one, list_two)
compare_array_order_doesnt_matter(list_three, list_four)
compare_array_order_doesnt_matter(list_five, list_six)
compare_array_order_doesnt_matter(list_seven, list_eight)
compare_array_order_doesnt_matter(list_nine, list_ten)
| true |
19aa6ef97da6fdbb4a2a11fd2e66060d8a04f72e | nmarriotti/PythonTutorials | /readfile.py | 659 | 4.125 | 4 | ################################################################################
# TITLE: Reading files in Python
# DESCRIPTION: Open a text file and read the contents of it.
################################################################################
def main():
# Call the openFile method and pass it Files/file1.txt
openFile('Files/file1.txt')
def openFile(filename):
# Create variable and set it to the contents of the file
fh = open(filename)
# Output each line in the file
for line in fh:
print(line.strip())
if __name__ == "__main__":
# Here we start the program by calling the main method
main()
| true |
85d84d9c937233fb243c2a67a482c84d778bb60b | nicolas-huber/reddit-dailyprogrammer | /unusualBases.py | 1,734 | 4.3125 | 4 | # Decimal to "Base Fib" - "Base Fib" to Decimal Converter
# challenge url: "https://www.reddit.com/r/dailyprogrammer/comments/5196fi/20160905_challenge_282_easy_unusual_bases/"
# Base Fib: use (1) or don't use (0) a Fibonacci Number to create any positive integer
# example:
# 13 8 5 3 2 1 1
# 1 0 0 0 1 1 0 = 16 in "Base Fib"
# collect and save user input
input_line = raw_input("Enter base (F or 10) and number to be converted: ")
input_list = input_line.split(" ")
base = input_list[0]
number = input_list[1]
# translate from base fib to decimal
if base == "F":
# Create sufficient amount of Fibonacci Numbers
a, b = 0, 1
fib_numbers = []
for i in range(len(number)):
a, b = b, a+b
fib_numbers.append(a)
fib_numbers.sort(reverse=True)
result = []
number_digit_list = [int(i )for i in str(number)]
for item1, item2 in zip(number_digit_list, fib_numbers):
if item1 == 1:
result.append(item2)
else:
pass
print(sum(result))
# translate from decimal to base fib
elif base == "10":
# Create sufficient amount of Fibonacci Numbers
a, b = 0, 1
fib_num_list = []
while True:
a, b = b, a+b
fib_num_list.append(a)
if fib_num_list[-1] >= int(number):
fib_num_list.sort(reverse=True)
break
fib_result = []
for entry in fib_num_list:
if int(number)/entry == 1:
fib_result.append(int(number)/entry)
number = int(number)%entry
else:
fib_result.append(0)
# remove first item of fib_results since excess 0 is added (?)
print(" ".join(str(x) for x in fib_result[1:]))
| true |
b0b353eb1b6e426d235a046850ba74aea627d7a2 | LJ-Godfrey/Learn-to-code | /Encryption-101/encryption_project/encrypt.py | 1,178 | 4.25 | 4 | # This file contains various encryption methods, for use in an encryption / decryption program
def caesar(string):
res = str()
for letter in string:
if letter.lower() >= 'a' and letter.lower() <= 'm':
res += chr(ord(letter) + 13)
elif letter.lower() >= 'n' and letter.lower() <= 'z':
res += chr(ord(letter) - 13)
else:
res += letter
return res
def reverse(string):
res = str()
for letter in string:
res = letter + res
return res
def xor(string, key):
res = str()
for letter in string:
res += chr(ord(letter) ^ key)
return res
def rotate(string):
res = str()
if len(string) % 2 > 0:
mid = string[len(string)/2 + 1]
res = string[:mid] + string[mid+1:]
res = rot_sub(res)
res = res[:len(res)/2] + mid + res[len(res)/2:]
else:
res = rot_sub(string)
return res
# This function is used in the 'rotate' function
def rot_sub(string):
res = string
# pylint: disable=unused-variable
for letter in range(int(len(string)/2)):
last = len(res) - 1
res = res[last] + res[:last]
return res | true |
fd1f0836c9c89a66ff6a555f48577538e398f026 | Moby5/myleetcode | /python/671_Second_Minimum_Node_In_a_Binary_Tree.py | 2,525 | 4.125 | 4 | #!/usr/bin/env python
# coding=utf-8
"""
@File: 671_Second_Minimum_Node_In_a_Binary_Tree.py
@Desc:
@Author: Abby Mo
@Date Created: 2018-3-10
"""
"""
Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly two or zero sub-node.
If the node has two sub-nodes, then this node's value is the smaller value among its two sub-nodes.
Given such a binary tree, you need to output the second minimum value in the set made of all the nodes' value in the whole tree.
If no such second minimum value exists, output -1 instead.
Example 1:
Input:
2
/ \
2 5
/ \
5 7
Output: 5
Explanation: The smallest value is 2, the second smallest value is 5.
Example 2:
Input:
2
/ \
2 2
Output: -1
Explanation: The smallest value is 2, but there isn't any second smallest value.
题目大意:
给定一棵二叉树,树中的节点孩子个数为偶数(0个或者2个),若包含2个孩子节点,则值等于较小孩子的值。求树中第二小的节点。
解题思路:
遍历二叉树,记录比根节点大的所有节点中值最小的元素
"""
# 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 findSecondMinimumValue(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root or not root.left:
return -1
res = self.traverse(root)
res = sorted(res)
return res[1] if len(res) >= 2 else -1
def traverse(self, node):
if not node:
return {}
res = {node.val}
res.update(self.traverse(node.left))
res.update(self.traverse(node.right))
return res
def findSecondMinimumValue_ref(self, root): # http://bookshadow.com/weblog/2017/09/03/leetcode-second-minimum-node-in-a-binary-tree/
self.ans = 0x80000000
minVal = root.val
def traverse(root):
if not root: return
if self.ans > root.val > minVal:
self.ans = root.val
traverse(root.left)
traverse(root.right)
traverse(root)
return self.ans if self.ans != 0x80000000 else -1
if __name__ == '__main__':
solution = Solution()
n1, n2, n3 = TreeNode(5), TreeNode(8), TreeNode(5)
n1.left, n1.right = n2, n3
print solution.findSecondMinimumValue(n1)
| true |
b76d2e373ea53f6ef7498888b0a80365bc48ec38 | Moby5/myleetcode | /python/532_K-diff_Pairs_in_an_Array.py | 2,592 | 4.125 | 4 | #!/usr/bin/env python
# coding=utf-8
"""
LeetCode 532. K-diff Pairs in an Array
Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in the array. Here a k-diff pair is defined as an integer pair (i, j), where i and j are both numbers in the array and their absolute difference is k.
Example 1:
Input: [3, 1, 4, 1, 5], k = 2
Output: 2
Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5).
Although we have two 1s in the input, we should only return the number of unique pairs.
Example 2:
Input:[1, 2, 3, 4, 5], k = 1
Output: 4
Explanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5).
Example 3:
Input: [1, 3, 1, 5, 4], k = 0
Output: 1
Explanation: There is one 0-diff pair in the array, (1, 1).
Note:
The pairs (i, j) and (j, i) count as the same pair.
The length of the array won't exceed 10,000.
All the integers in the given input belong to the range: [-1e7, 1e7].
题目大意:
给定一个整数数组nums,以及一个整数k,找出其中所有差恰好为k的不重复数对。
注意:
数对(i, j) 和 (j, i)算作同一个数对
数组长度不超过10,000
所有整数在范围[-1e7, 1e7]之间
解题思路:
字典(Map)
首先将nums中的数字放入字典c
遍历set(nums),记当前数字为n
若n + k在c中,则将结果+1
"""
import argparse
import collections
class Solution(object):
def findPairs(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
if k < 0:
return 0
c = collections.Counter(nums)
thres = 0 if k else 1
return sum(c[n+k] > thres for n in c.keys())
# return sum(c[n+k] > 1 - bool(k) for n in c.keys())
def findPairs_2(self, nums, k): # Time Limit Exceeded
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
if k < 0:
return 0
ans = set()
arr = sorted(nums)
# print 'arr:', arr
for i in range(len(arr) - 1):
if arr[i] not in ans and (arr[i] + k) in arr[i+1:]:
# print arr[i], arr[i+1:]
ans.add(arr[i])
return len(ans)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='find k-diff pairs in an array')
parser.add_argument('-nums', type=int, nargs='+')
parser.add_argument('-k', type=int)
args = parser.parse_args()
test = Solution()
print test.findPairs(args.nums, args.k)
| true |
bd4619b0c4c69fddaa93c8e896a89873c74e245a | Moby5/myleetcode | /python/414_Third_Maximum_Number.py | 2,199 | 4.15625 | 4 | #!/usr/bin/env python
# coding=utf-8
"""
http://bookshadow.com/weblog/2016/10/09/leetcode-third-maximum-number/
414. Third Maximum Number
Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n).
Example 1:
Input: [3, 2, 1]
Output: 1
Explanation: The third maximum is 1.
Example 2:
Input: [1, 2]
Output: 2
Explanation: The third maximum does not exist, so the maximum (2) is returned instead.
Example 3:
Input: [2, 2, 3, 1]
Output: 1
Explanation: Note that the third maximum here means the third maximum distinct number.
Both numbers with value 2 are both considered as second maximum.
题目大意:
给定一个整数数组,返回数组中第3大的数,如果不存在,则返回最大的数字。时间复杂度应该是O(n)或者更少。
解题思路:
利用变量a, b, c分别记录数组第1,2,3大的数字
遍历一次数组即可,时间复杂度O(n)
"""
import numpy as np
class Solution(object):
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
a, b, c = None, None, None
for n in nums:
if n > a:
a, b, c = n, a, b
elif a > n > b:
b, c = n, b
elif b > n > c:
c = n
return c if c is not None else a # 不能直接 return c if c else a 因为c可能为0
def thirdMax_runtime_error(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
ns = np.unique(nums)
return np.max(ns) if len(ns) < 3 else ns[-3]
def thirdMax_ref(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
a = b = c = None
for n in nums:
if n > a:
a, b, c = n, a, b
elif a > n > b:
b, c = n, b
elif b > n > c:
c = n
return c if c is not None else a
test = Solution()
print test.thirdMax([3,2,1])
print test.thirdMax([1,2])
print test.thirdMax([2,2,3,1])
print test.thirdMax([3,3,4,3,4,3,0,3,3])
| true |
a3f0ed60542ab8174c23174d1a48c8e2273b9e50 | Moby5/myleetcode | /python/640_Solve_the_Equation.py | 2,492 | 4.3125 | 4 | #!/usr/bin/env python
# coding=utf-8
# 566_reshape_the_matrix.py
"""
http://bookshadow.com/weblog/2017/07/09/leetcode-solve-the-equation/
LeetCode 640. Solve the Equation
Solve a given equation and return the value of x in the form of string "x=#value". The equation contains only '+', '-' operation, the variable x and its coefficient.
If there is no solution for the equation, return "No solution".
If there are infinite solutions for the equation, return "Infinite solutions".
If there is exactly one solution for the equation, we ensure that the value of x is an integer.
Example 1:
Input: "x+5-3+x=6+x-2"
Output: "x=2"
Example 2:
Input: "x=x"
Output: "Infinite solutions"
Example 3:
Input: "2x=x"
Output: "x=0"
Example 4:
Input: "2x+3x-6x=x+2"
Output: "x=-1"
Example 5:
Input: "x=x+2"
Output: "No solution"
题目大意:
给定一元一次方程,求x的值
解题思路:
字符串处理
用'='将等式分为左右两半
分别求左右两侧x的系数和常数值,记为lx, lc, rx, rc
令x, c = lx - rx, rc - lc
若x != 0,则x = c / x
否则,若c != 0,说明方程无解
否则,说明有无数组解
"""
class Solution(object):
def solveEquation(self, equation):
"""
:type equation: str
:rtype: str
"""
left, right = equation.split('=')
lcoef, lconst = self.solve(left)
rcoef, rconst = self.solve(right)
coef, const = lcoef - rcoef, rconst - lconst
if coef: return 'x=%d' % (const / coef)
elif const: return 'No solution'
return 'Infinite solutions'
def solve(self, expr):
coef = const = 0
num, sig = '', 1
for ch in expr + '#':
if '0' <= ch <= '9':
num += ch
elif ch == 'x':
coef += int(num or '1') * sig
num, sig = '', 1
else:
const += int(num or '0') * sig
num, sig = '', 1
if ch == '-': sig = -1
return coef, const
if __name__ == '__main__':
solution = Solution()
equations = ["x+5-3+x=6+x-2", "x=x" ,"2x=x", "2x+3x-6x=x+2", "x=x+2"]
for e in equations:
print e, solution.solveEquation(e)
pass
| true |
549ae44ba1517ca134e2677a63cc3fe5cfb5f205 | joaoribas35/distance_calculator | /app/services/calculate_distance.py | 943 | 4.34375 | 4 | import haversine as hs
def calculate_distance(coordinates):
""" Will calculate the distance from Saint Basil's Cathedral and the address provided by client usind Haversine python lib. Saint Basil's Cathedral is used as an approximation to define whether the provided address is located inside the MKAD Moscow Ring Road (MKAD) or not. It's location is the center point to a 18 km radius circle. Will return a null string indicating the address is inside MKAD or a string with the distance from MKAD border, expressed in kilometers, if the address falls outside the MKAD. """
CENTER_POINT = (55.75859164153293, 37.623173678442136)
CIRCLE_RADIUS = 18
input_address = (coordinates['lat'], coordinates['lon'])
distance = hs.haversine(CENTER_POINT, input_address)
if distance <= CIRCLE_RADIUS:
return 'null'
distance_from_border = round(distance - CIRCLE_RADIUS, 2)
return f'{distance_from_border} km'
| true |
536bf2470f47c6353bc674b6c1efd668f8c03473 | nonbinaryprogrammer/python-poet | /sentence_generator.py | 787 | 4.15625 | 4 | import random
from datetime import datetime
from dictionary import Words
#initializes the dictionary so that we can use the words
words = Words();
#makes the random number generator more random
random.seed(datetime.now)
#gets 3 random numbers between 0 and the length of each list of words
random1 = random.randint(0, 3000) % (len(words.plural_nouns))
random2 = random.randint(0, 3000) % (len(words.plural_verbs))
random3 = random.randint(0, 3000) % (len(words.plural_nouns))
#gets the n-th word from the list of words
#where n is the randomly chosen number above
noun1 = words.plural_nouns[random1]
verb1 = words.plural_verbs[random2]
noun2 = words.plural_nouns[random3]
#prints out each of the randomly chosen words with spaces between them
print noun1 + " " + verb1 + " " + noun2
| true |
5ac31df1a7457d4431e7c8fbdc1892bf02d393d0 | qtdwzAdam/leet_code | /py/back/work_405.py | 1,282 | 4.53125 | 5 | # -*- coding: utf-8 -*-
#########################################################################
# Author : Adam
# Email : zju_duwangze@163.com
# File Name : work_405.py
# Created on : 2019-08-30 15:26:20
# Last Modified : 2019-08-30 15:29:47
# Description :
# Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used.
#
# Note:
#
# All letters in hexadecimal (a-f) must be in lowercase.
# The hexadecimal string must not contain extra leading 0s. If the number is zero, it is represented by a single zero character '0'; otherwise, the first character in the hexadecimal string will not be the zero character.
# The given number is guaranteed to fit within the range of a 32-bit signed integer.
# You must not use any method provided by the library which converts/formats the number to hex directly.
# Example 1:
#
# Input:
# 26
#
# Output:
# "1a"
# Example 2:
#
# Input:
# -1
#
# Output:
# "ffffffff"
#########################################################################
class Solution(object):
def toHex(self, num):
"""
:type num: int
:rtype: str
"""
def main():
return 0
if __name__ == '__main__':
main()
| true |
4b3ce42dde5e951efe9620bfce24c01f380715e7 | gauravtatke/codetinkering | /leetcode/LC110_balanced_bintree.py | 2,087 | 4.3125 | 4 | # Given a binary tree, determine if it is height-balanced.
# For this problem, a height-balanced binary tree is defined as:
# a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
# Example 1:
# Given the following tree [3,9,20,null,null,15,7]:
# 3
# / \
# 9 20
# / \
# 15 7
# Return true.
# Example 2:
# Given the following tree [1,2,2,3,3,null,null,4,4]:
# 1
# / \
# 2 2
# / \
# 3 3
# / \
# 4 4
# Return false
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution1:
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root is None:
return True
hleft = self.height(root.left)
hright = self.height(root.right)
if abs(hleft - hright) > 1 and self.isBalanced(
root.left) and self.isBalanced(root.right):
return True
return False
def height(self, root):
if root is None:
return 0
return max(self.height(root.left), self.height(root.right)) + 1
class Solution2:
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
# another way is to return height at each recursion and -1 if it is un-balanced.
# no need to traverse tree twice, once for height and once for isBalance as in above solution
height = self.heightBalance(root)
if height == -1:
return False
return True
def heightBalance(self, root):
if root is None:
return 0
left_height = self.heightBalance(root.left)
if left_height == -1:
return -1
right_height = self.heightBalance(root.right)
if right_height == -1:
return -1
if abs(left_height - right_height) > 1:
return -1
return max(left_height, right_height) + 1
| true |
32a89094e2c55e2a5b13cf4a52a1cf6ef7206894 | gauravtatke/codetinkering | /leetcode/LC98_validate_BST.py | 798 | 4.21875 | 4 | # Given a binary tree, determine if it is a valid binary search tree (BST).
#
# Assume a BST is defined as follows:
#
# The left subtree of a node contains only nodes with keys less than the node's key.
# The right subtree of a node contains only nodes with keys greater than the node's key.
# Both the left and right subtrees must also be binary search trees.
def isValidBST(root):
def isValid(root, minNode, maxNode):
# define the min and max between which the node val should be
if root is None:
return True
if (minNode and minNode.val >= root.val) or (maxNode and maxNode.val <= root.val):
return False
return isValid(root.left, minNode, root) and isValid(root.right, root, maxNode)
return isValid(root, None, None)
| true |
996e3858f7eb3c4a8de569db426c2f9cdd5fd71a | gauravtatke/codetinkering | /dsnalgo/firstnonrepeatcharinstring.py | 1,292 | 4.15625 | 4 | #!/usr/bin/env python3
# Given a string, find the first non-repeating character in it. For
# example, if the input string is “GeeksforGeeks”, then output should be
# ‘f’ and if input string is “GeeksQuiz”, then output should be ‘G’.
def findNonRepeatChar(stri):
chlist = [0 for ch in range(256)]
for ch in stri:
chlist[ord(ch)] += 1
for ch in stri:
if chlist[ord(ch)] == 1:
return ch
return None
def findNonRepeatCharFromCount(str1):
# store count of char and index at which it first occured in count list
count = [[0, None] for i in range(256)]
for i, ch in enumerate(str1):
count[ord(ch)][0] += 1
if not count[ord(ch)][1]:
# if index is None, set it else leave as it is
count[ord(ch)][1] = i
# now only traverse count list i.e. 256 elements instead of whole string
# again which could be very long
maxi = 257
result = None
for cnt, indx in count:
if cnt == 1 and indx < maxi:
result = str1[indx]
maxi = indx
return result
def main(argv):
print(findNonRepeatChar(argv[0]))
print(findNonRepeatCharFromCount(argv[0]))
return 0
if __name__ == '__main__':
import sys
sys.exit(main(sys.argv[1:]))
| true |
c106671082f8f393f73ebad1a355929e142cfdc6 | gauravtatke/codetinkering | /leetcode/LC345_reverse_vowelsof_string.py | 739 | 4.28125 | 4 | # Write a function that takes a string as input and reverse only the vowels of a string.
#
# Example 1:
# Given s = "hello", return "holle".
#
# Example 2:
# Given s = "leetcode", return "leotcede".
#
# Note:
# The vowels does not include the letter "y".
def reverseVowels(s):
lstr = list(s)
i = 0
j = len(lstr) - 1
vowels = ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U')
while i < j:
while i < j and lstr[i] not in vowels:
i = i + 1
while i < j and lstr[j] not in vowels:
j = j - 1
lstr[i], lstr[j] = lstr[j], lstr[i]
# print(i, j)
i = i + 1
j = j - 1
return ''.join(lstr)
if __name__ == '__main__':
print(reverseVowels('hello'))
| true |
0d37f87ebde2412443f7fefbf53705ac0f03b019 | gauravtatke/codetinkering | /dsnalgo/lengthoflongestpalindrome.py | 2,308 | 4.1875 | 4 | #!/usr/bin/env python3
# Given a linked list, the task is to complete the function maxPalindrome which
# returns an integer denoting the length of the longest palindrome list that
# exist in the given linked list.
#
# Examples:
#
# Input : List = 2->3->7->3->2->12->24
# Output : 5
# The longest palindrome list is 2->3->7->3->2
#
# Input : List = 12->4->4->3->14
# Output : 2
# The longest palindrome list is 4->4
class SllNode:
def __init__(self, val=None):
self.key = val
self.nextp = None
def __str__(self):
return str(self.key)
def createlist(alist):
head = tail = None
for val in alist:
if tail:
tail.nextp = SllNode(val)
tail = tail.nextp
else:
head = tail = SllNode(val)
tail.nextp = SllNode() # just put dummy node at end so that comparisons are easy.
return head
def printlist(head):
curr = head
while curr.key:
print(curr, end='->')
curr = curr.nextp
print(None)
def findMaxPalindromeLen(head):
# reverse the linked list at each node and traverse from that node in opp
# directions.
curr = head
prev = SllNode()
maxlen = 0
while curr.key:
nxt = curr.nextp
curr.nextp = prev
# now from curr traverse back and forward and check if palindrome exists. if exists then get the length.
# first check for odd length palindrome from curr
i = prev
j = nxt
currmax = 1
while i.key == j.key:
# print('i == j for odd')
currmax += 2
i = i.nextp if i else None
j = j.nextp if j else None
maxlen = max(maxlen, currmax)
# now check for even length palindrome starting at curr and nxt
i = curr
j = nxt
currmax = 0
while i.key == j.key:
currmax += 2
i = i.nextp if i else None
j = j.nextp if j else None
maxlen = max(maxlen, currmax)
prev = curr
curr = nxt
return maxlen
def main():
alist1 = [2, 3, 7, 3, 2, 12, 24]
alist2 = [12, 4, 4, 3, 14]
alist3 = [1,2,3,6,3,9,6,6,9,3]
head = createlist(alist3)
printlist(head)
print(findMaxPalindromeLen(head))
if __name__ == '__main__':
main()
| true |
8d9bb6926f1bd85ef8da53778229913d6ac4bc86 | gauravtatke/codetinkering | /dsnalgo/sort_pile_of_cards.py | 1,047 | 4.125 | 4 | #!/usr/bin/env python3
# We have N cards with each card numbered from 1 to N. All cards are randomly shuffled. We are allowed only operation moveCard(n) which moves the card with value n to the top of the pile. You are required to find out the minimum number of moveCard() operations required to sort the cards in increasing order.
def minMove(arr):
# start iterating from back and count number of elements already in descending order.
# minimum movement to sort will be n-(num of elem in desc ord) because only those elem need to move
# for e.g. 4, 2, 5, 1, 6, 3 item in desc ord are 3 i.e.{6, 5, 4} so 6 - 3 = 3 movement to sort.
# moveCard(3) -> moveCard(2) -> moveCard(1)
n = len(arr)
count = 0
for i in arr[-1::-1]:
if i == n:
count += 1
n -= 1
return len(arr)-count
def main():
arr1 = [4, 2, 5, 1, 6, 3]
arr2 = [5, 1, 2, 3, 4]
arr3 = [3, 4, 2, 1]
print(minMove(arr1))
print(minMove(arr2))
print(minMove(arr3))
if __name__ == '__main__':
main()
| true |
a783b4053b012143e18b6a8bd4335a8b84b5d031 | gauravtatke/codetinkering | /leetcode/LC433_min_gene_mut.py | 2,495 | 4.15625 | 4 | # A gene string can be represented by an 8-character long string, with choices from "A", "C", "G", "T".
# Suppose we need to investigate about a mutation (mutation from "start" to "end"), where ONE mutation is defined as ONE single character changed in the gene string.
# For example, "AACCGGTT" -> "AACCGGTA" is 1 mutation.
# Also, there is a given gene "bank", which records all the valid gene mutations. A gene must be in the bank to make it a valid gene string.
# Now, given 3 things - start, end, bank, your task is to determine what is the minimum number of mutations needed to mutate from "start" to "end". If there is no such a mutation, return -1.
# Note:
# Starting point is assumed to be valid, so it might not be included in the bank.
# If multiple mutations are needed, all mutations during in the sequence must be valid.
# You may assume start and end string is not the same.
# Example 1:
# start: "AACCGGTT"
# end: "AACCGGTA"
# bank: ["AACCGGTA"]
# return: 1
# Example 2:
# start: "AACCGGTT"
# end: "AAACGGTA"
# bank: ["AACCGGTA", "AACCGCTA", "AAACGGTA"]
# return: 2
# Example 3:
# start: "AAAAACCC"
# end: "AACCCCCC"
# bank: ["AAAACCCC", "AAACCCCC", "AACCCCCC"]
# return: 3
from collections import deque
class Solution(object):
def minMutation(self, start, end, bank):
"""
:type start: str
:type end: str
:type bank: List[str]
:rtype: int
"""
bankset = set(bank)
visited = set()
dq = deque()
dq.append(start)
level = 0
while dq:
size = len(dq)
while size:
gene = dq.popleft()
if gene == end:
return level
gene_list = list(gene)
for i, ch in enumerate(gene_list):
# oldchar = ch
for repch in ('A', 'C', 'G', 'T'):
gene_list[i] = repch
# print(gene_list)
mut_gene_str = ''.join(gene_list)
if mut_gene_str in bankset and mut_gene_str not in visited:
visited.add(mut_gene_str)
dq.append(mut_gene_str)
gene_list[i] = ch
size -= 1
level += 1
return -1
def main():
retval = Solution().minMutation("AACCGGTT", "AACCGGTA", ["AACCGGTA"])
print(retval)
if __name__ == '__main__':
main() | true |
ffe24156489d5063ee564b1b5c558585363a7944 | directornicm/python | /Project_4.py | 572 | 4.28125 | 4 | # To calculate leap year:
# A leap year is a year which is divisible by 4 but ...
# if it is divisible by 100, it must be divisible by 400.
# indentation matters - take care of it
year = int(input("Give the year to be checked for leap year"))
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print(f"The year {year} is a leap year")
else:
print(f"The year {year} is not a leap year")
else:
print(f"The year {year} is a leap year")
else:
print(f"The year {year} is not a leap year")
| true |
67eb2e0043b1c1d63395df0de8f4e39a98930a7e | luthraG/ds-algo-war | /general-practice/17_09_2019/p16.py | 996 | 4.1875 | 4 | '''
Given a non-empty string check if it can be constructed by taking a substring of it and
appending multiple copies of the substring together.
You may assume the given string consists of lowercase English letters only and its length will not exceed 10000.
Example 1:
Input: "abab"
Output: True
Explanation: It's the substring "ab" twice.
Example 2:
Input: "aba"
Output: False
Example 3:
Input: "abcabcabcabc"
Output: True
Explanation: It's the substring "abc" four times. (And the substring "abcabc" twice.)
'''
def can_construct_string(str1):
length = len(str1)
i = 1
limit = length // 2
while i <= limit:
if length % i == 0:
times = length // i
if str1[:i] * times == str1:
return True
i += 1
return False
str1 = str(input('Enter input string :: '))
print('can this string be constructed by sub strings :: {}'.format(can_construct_string(str1))) | true |
bd48564a03e15ec4c6f2d287ec3b651947418118 | luthraG/ds-algo-war | /general-practice/20_08_2019/p1.py | 861 | 4.125 | 4 | # If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.
# The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 10 Million.
from timeit import default_timer as timer
if __name__ == '__main__':
start = timer()
number = 1000
# Since we want below hence
number -= 1
# Sum of multiple of 3s
upper3 = number // 3
sum3 = 3 * upper3 * (upper3 + 1) // 2
# Sum of multiple of 5s
upper5 = number // 5
sum5 = 5* upper5 * (upper5 + 1) // 2
# Sum of multiple of 15s
upper15 = number // 15
sum15 = 15 * upper15 * (upper15 + 1) // 2
sum = sum3 + sum5 - sum15
print("sum3 {}, sum5 {} and sum15 {}".format(sum3, sum5, sum15))
print("Overall sum = {}".format(sum))
end = timer()
print("Time taken is {}".format(end - start)) | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.