blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
5077815f19f7bd1d729650704069e64e448cd89c | Souravdg/Python.Session_4.Assignment-4.2 | /Vowel Check.py | 776 | 4.15625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
"""
Problem Statement 2:
Write a Python function which takes a character (i.e. a string of length 1) and returns
True if it is a vowel, False otherwise.
"""
def vowelChk(char):
if(char == 'a' or char == 'e' or char == 'i' or char == 'o' or char == 'u'):
return True
else:
return False
# Take user input
char = input("Enter character: ");
# If Invalid input, exit
if (len(char) > 1):
print("string Length must be one")
exit();
else:
# If Invalid input, exit
if (char.isalpha() == False):
print("Invalid entry")
else:
# Invoke function
if (vowelChk(char)):
print(char, "is a vowel.");
else:
print(char, "is not a vowel.");
| true |
fb6ac747fcf5d0fc4fc360cdfbb7e146f9e099e4 | sharyar/design-patterns-linkedin | /visitor.py | 1,285 | 4.25 | 4 | class House(object):
def accept(self, visitor):
''' The interface to accept a visitor '''
# Triggers the visiting operation
visitor.visit(self)
def work_on_hvac(self, hvac_specialist):
print(self, 'worked on by', hvac_specialist)
# This creates a reference to the HVAC specialist within the house object.
def work_on_electricity(self, electrician):
print(self, 'worked on by', electrician)
def __str__(self) -> str:
return self.__class__.__name__
class Visitor(object):
''' Abstract Visitor '''
def __str__(self) -> str:
'''Simply returns the class name when visitor object is printed'''
return self.__class__.__name__
class HVACSpecialist(Visitor):
# Concrete class fro HVACSpecialist
def visit(self, house):
house.work_on_hvac(self)
# now the visitor has a reference to the house object
class Electrician(Visitor):
'''Concrete visitor: electrician'''
def visit(self, house):
house.work_on_electricity(self)
hvac1 = HVACSpecialist()
elec1 = Electrician()
h1 = House()
# House accepting visitors
h1.accept(hvac1)
h1.accept(elec1)
# The visitors visiting the house.
hvac1.visit(h1)
elec1.visit(h1) | true |
9dd9050ffca4e9c67628c713695472613b6ef5bd | mas254/tut | /String methods.py | 349 | 4.125 | 4 | course = "Python for Beginners"
print(len(course))
print(course.upper())
print(course.find("P"))
# You get 0 here as this is the position of P in the string
print(course.find("z"))
# Negative 1 is if not found
print(course.replace("Beginners", "Absolute Beginners"))
print(course)
print("Python" in course)
# All case sensitive
print(course.title()) | true |
132d54605b7b373f7d8494dce66665cf80cd9373 | mas254/tut | /creating_a_reusable_function.py | 935 | 4.28125 | 4 | message = input('>')
words = message.split(' ')
emojis = {
':)': 'smiley',
':(': 'frowney'
}
output = ''
for word in words:
output += emojis.get(word, word) + ' '
print(output)
def emojis(message):
words = message.split(' ')
emojis = {
':)': 'smiley',
':(': 'frowney'
}
output = ''
for word in words:
output += emojis.get(word, word) + ' '
return output
message = input('>')
result = emojis(message)
print(result)
# An explanation: add the def at the start. The parameter is what we've called message, which is what
# the user inputs (taken from previous code). You don't include the first or last lines (the ones which
# ask for or print input) into your function). Add return output into the function as the function has to
# return a value, which can then be stored into a separate variable.
message = input('>')
print(emojis(message))
# Can make it shorter like so. | true |
cda3560dfafcb1c358ea0c6ff93477d6e868bb68 | sabach/restart | /script10.py | 540 | 4.375 | 4 | # Write a Python program to guess a number between 1 to 9.
#Note : User is prompted to enter a guess.
#If the user guesses wrong then the prompt appears again
#until the guess is correct, on successful guess,
#user will get a "Well guessed!" message,
#and the program will exit.
from numpy import random
randonly_selected=random.randint(10)
guessed_number=input("Type your number to Guess: ")
while randonly_selected == int(guessed_number):
guessed_number=input("Type your number to Guess: ")
print (randonly_selected, guessed_number) | true |
713773b1c5d7b50b23270a1ac5f7ca2aa62ac58b | VelizarMitrev/Python-Homework | /Homework1/venv/Exercise6.py | 343 | 4.34375 | 4 | nand = input("Choose a number ")
operator = input("Input + OR * for either computing a number or multiplying it ")
sum = 0
if operator == "+":
for x in range(1, int(nand) + 1):
sum = sum + x
if operator == "*":
sum = 1
for x in range(1, int(nand) + 1):
sum = sum * x
print("The final number is " + str(sum)) | true |
b44c3fcdf3aa99d88f9d5a03c7d12cb64e9715d6 | VelizarMitrev/Python-Homework | /Homework2/venv/Exercise10.py | 387 | 4.34375 | 4 | def fibonacci(num): # this is a recursive solution, in this case it's slower but the code is cleaner
if num <= 1:
return num
else:
return(fibonacci(num-1) + fibonacci(num-2))
numbers_sequence = input("Enter how many numbers from the fibonacci sequence you want to print: ")
print("Fibonacci sequence:")
for i in range(int(numbers_sequence)):
print(fibonacci(i)) | true |
02d3f469da092a1222b12b48327c61da7fc1fea3 | mvargasvega/Learn_Python_Exercise | /ex6.py | 903 | 4.5 | 4 | types_of_people = 10
# a string with embeded variable of types_of_people
x = f"There are {types_of_people} types of people."
binary = "binary"
do_not = "don't"
# assigns a string to y with embeded variables
y = f"Those who know {binary} and those who {do_not}."
print(x)
print(y)
print(f"I said: {x}")
# printing a string with variable y
print(f"I also said: '{y}'")
# assign the boolean value of false to hilarious
hilarious = False
# assigns a string with an empty curly brace, which allows us to print something in
joke_evaluation = "Isn't that joke so funny?! {}"
# prints thet variable joke_evaluation and plugs in False into the two curlry braces
print(joke_evaluation.format(hilarious))
# a variable that stores a string
w = "This is the left side of..."
# a variable that stores a string
e = "a string with a right side."
# Conncatintes two variables that are holding strings
print(w + e)
| true |
b13dd7edaf3c6269f3d3fa90682eeeb989d78571 | TigerAppsOrg/TigerHost | /deploy/deploy/utils/click_utils.py | 586 | 4.1875 | 4 | import click
def prompt_choices(choices):
"""Displays a prompt for the given choices
:param list choices: the choices for the user to choose from
:rtype: int
:returns: the index of the chosen choice
"""
assert len(choices) > 1
for i in range(len(choices)):
click.echo('{number}) {choice}'.format(
number=i + 1,
choice=choices[i]
))
value = click.prompt('1-{}'.format(len(choices)), type=int) - 1
if value < 0 or value >= len(choices):
raise click.ClickException('Invalid choice.')
return value
| true |
2609c2b1f06d647b086493c1294a1652787cefd8 | FranciscoValadez/Course-Work | /Python/CS119-PJ 6 - Simple Calculator/PJ 6 - Simple Calculator/PJ_6___Simple_Calculator.py | 1,900 | 4.5 | 4 | # Author: Francisco Valadez
# Date: 1/23/2021
# Purpose: A simple calculator that shows gives the user a result based on their input
#This function is executed when the user inputs a valid operator
def Results(num1, num2, operator):
if operator == '+':
print("Result:", num1, operator, num2, "=", (num1 + num2))
elif operator == '-':
print("Result:", num1, operator, num2, "=", (num1 - num2))
elif operator == '*':
print("Result:", num1, operator, num2, "=", (num1 * num2))
elif operator == '/':
if num2 == 0: #checks if the second number is zero
print("The second number cannot be zero!")
else:
print("Result:", num1, operator, num2, "=", (num1 / num2))
elif operator == '**':
print("Result:", num1, operator, num2, "=", (num1 ** num2))
elif operator == '%':
if num2 == 0: #checks if the second number is zero
print("The second number cannot be zero!")
else:
print("Result:", num1, operator, num2, "=", (num1 % num2))
else:
print("Sorry,", operator, "is not a valid operator!")
#Prints the welcom message
print("Welcome to use the Simple Calculator of Francisco Valadez!")
counter = 0
operator = ''
#The while loop below will not stop until the user enter '@' for the operator
while operator != '@':
counter +=1
print (counter, "="*40)
num1 = float(input("Enter your first number: "))
operator = input("Enter your operator(@ to stop): ")
num2 = float(input("Enter your second number: "))
#If the user does not want to exit then this bit of code is run
if operator != '@':
Results(num1, num2, operator) #sends the user's input to a function
else: #Prints the goodbye message
print(counter + 1, "="*40)
print("Thank you for playing this Simple Calculator of Francisco Valadez!")
print(counter + 2, "="*40)
| true |
f5617054ec164da96fe6c2d4b638c9889060bbf0 | hirani/pydec | /pydec/pydec/math/parity.py | 2,695 | 4.15625 | 4 | __all__ = ['relative_parity','permutation_parity']
def relative_parity(A,B):
"""Relative parity between two lists
Parameters
----------
A,B : lists of elements
Lists A and B must contain permutations of the same elements.
Returns
-------
parity : integer
The parity is 0 if A differs from B by an even number of
transpositions and 1 otherwise.
Examples
--------
>>> relative_parity( [0,1], [0,1] )
0
>>> relative_parity( [0,1], [1,0] )
1
>>> relative_parity( [0,1,2], [0,1,2] )
0
>>> relative_parity( [0,1,2], [0,2,1] )
1
>>> relative_parity( ['A','B','C'], ['A','B','C'] )
0
>>> relative_parity( ['A','B','C'], ['A','C','B'] )
1
"""
if len(A) != len(B): raise ValueError("B is not a permutation of A")
# represent each element in B with its index in A and run permutation_parity()
A_indices = dict(zip(A,range(len(A))))
if len(A_indices) != len(A): raise ValueError("A contains duplicate values")
try:
perm = [A_indices[x] for x in B]
except KeyError:
raise ValueError("B is not a permutation of A")
return permutation_parity(perm, check_input=False)
def permutation_parity(perm, check_input=True):
"""Parity of a permutation of the integers
Parameters
----------
perm : list of integers
List containing a permutation of the integers 0...N
Optional Parameters
-------------------
check_input : boolean
If True, check whether the input is a valid permutation.
Returns
-------
parity : integer
The parity is 0 if perm differs from range(len(perm)) by an
even number of transpositions and 1 otherwise.
Examples
--------
>>> permutation_parity( [0,1,2] )
0
>>> permutation_parity( [0,2,1] )
1
>>> permutation_parity( [1,0,2] )
1
>>> permutation_parity( [1,2,0] )
0
>>> permutation_parity( [2,0,1] )
0
>>> permutation_parity( [0,1,3,2] )
1
"""
n = len(perm)
if check_input:
rangen = range(n)
if sorted(perm) != rangen:
raise ValueError("Invalid input")
# Decompose into disjoint cycles. We only need to
# count the number of cycles to determine the parity
num_cycles = 0
seen = set()
for i in range(n):
if i in seen:
continue
num_cycles += 1
j = i
while True:
assert j not in seen
seen.add(j)
j = perm[j]
if j == i:
break
return (n - num_cycles) % 2
| true |
e3f3da252345a8e54f3e7bff4d6c695d379b5e42 | grupy-sanca/dojos | /039/2.py | 839 | 4.53125 | 5 | """
https://www.codewars.com/kata/55960bbb182094bc4800007b
Write a function insert_dash(num) / insertDash(num) / InsertDash(int num)
that will insert dashes ('-') between each two odd digits in num.
For example: if num is 454793 the output should be 4547-9-3.
Don't count zero as an odd digit.
Note that the number will always be non-negative (>= 0).
>>> verificaImpares(23543)
'23-543'
>>> verificaImpares(2543)
'2543'
>>> verificaImpares(454793)
'4547-9-3'
>>> verificaImpares(353793)
'3-5-3-7-9-3'
"""
def verificaImpares(numero):
impar = "13579"
res = ""
anterior_impar = False
for letter in str(numero):
if letter in impar:
if anterior_impar:
res += "-"
anterior_impar = True
else:
anterior_impar = False
res += letter
return res
| true |
4fd23931962dd3a22a5a168a9a49bc68fd8eadd6 | grupy-sanca/dojos | /028/ex2.py | 1,416 | 4.40625 | 4 | """
A newly opened multinational brand has decided to base their company logo on the three most common characters in the company name.
They are now trying out various combinations of company names and logos based on this condition.
Given a string, which is the company name in lowercase letters, your task is to find the top three most common characters in the string.
-> Print the three most common characters along with their occurrence count.
-> Sort in descending order of occurrence count.
-> If the occurrence count is the same, sort the characters in alphabetical order.
-> ordena a string inicial -> garante que o dicionário tá ordenado
-> cria outra função que roda 3 vezes, e antes do for chama letter_count_func
Example:
* input:
aabbbccde
* output:
[("b": 3), ("a": 2), ("c": 2)]
>>> main('aaabbc')
[('a', 3), ('b', 2), ('c', 1)]
>>> main('aaabbcdef')
[('a', 3), ('b', 2), ('c', 1)]
>>> main('aaabbbcccdef')
[('a', 3), ('b', 3), ('c', 3)]
>>> main('abcccdddeffff')
[('f', 4), ('c', 3), ('d', 3)]
"""
def letter_count_func(string):
letter_count = {}
for letter in string:
letter_count[letter] = letter_count.get(letter, 0) + 1
return letter_count
def sort_values(x):
return [-x[1], x[0]]
def main(string):
letter_count = letter_count_func(string)
letter_count = sorted(letter_count.items(), key=sort_values, reverse=True)
return letter_count[-1:-4:-1] | true |
f17e7bc0acc2e97393a392ffb15e96a3f9f805f2 | ayust/controlgroup | /examplemr.py | 645 | 4.28125 | 4 | # A mapper function takes one argument, and maps it to something else.
def mapper(item):
# This example mapper turns the input lines into integers
return int(item)
# A reducer function takes two arguments, and reduces them to one.
# The first argument is the current accumulated value, which starts
# out with the value of the first element.
def reducer(accum, item):
# This example reducer sums the values
return accum+item
# You'd run this via the following command:
#
# some_input_cmd | ./pythonmr.py --auto=examplemr | some_output_command
#
# or...
#
# ./pythonmr.py --in=infile.txt --out=outfile.txt --auto=examplemr
| true |
41b44b20257c4a5e99ca9af99d7ca7fc7066ed1c | Lesikv/python_tasks | /python_practice/matrix_tranpose.py | 654 | 4.1875 | 4 | #!usr/bin/env python
#coding: utf-8
def matrix_transpose(src):
"""
Given a matrix A, return the transpose of A
The transpose of a matrix is the matrix flipped over it's main diagonal, switching the row and column indices of the matrix.
"""
r, c = len(src), len(src[0])
res = [[None] * r for i in range(c)]
for i in range(len(src)):
for j in range(len(src[i])):
res[j][i] = src[i][j]
return res
def test_1():
assert matrix_transpose([[1], [2]]) == [[1, 2]]
def test_2():
assert matrix_transpose([[1, 2], [3, 4]]) == [[1, 3], [2,4]]
if __name__ == '__main__':
test_1()
test_2()
| true |
c70cbbe6dd0107e74cd408a899dc6bbe77432829 | reenadhawan1/coding-dojo-algorithms | /week1/python-fundamentals/selection_sort.py | 1,044 | 4.15625 | 4 | # Selection Sort
x = [23,4,12,1,31,14]
def selection_sort(my_list):
# find the length of the list
len_list = len(my_list)
# loop through the values
for i in range(len_list):
# for each pass of the loop set the index of the minimum value
min_index = i
# compare the current value with all the remaining values in the array
for j in range(i+1,len_list):
# to update the min_index if we found a smaller int
if my_list[j] < my_list[min_index]:
min_index = j
# if the index of the minimum value has changed
# we will make a swap
if min_index != i:
# we could do the swap like this
# temp = my_list[i]
# my_list[i] = my_list[min_index]
# my_list[min_index] = temp
# but using tuple unpacking to swap values here makes it shorter
(my_list[i], my_list[min_index]) = (my_list[min_index], my_list[i])
# return our array
return my_list
print selection_sort(x)
| true |
249cbda74673f28d7cc61e8be86cdfef2b855e2a | Bharadwaja92/DataInterviewQuestions | /Questions/Q_090_SpiralMatrix.py | 414 | 4.4375 | 4 | """""""""
Given a matrix with m x n dimensions, print its elements in spiral form.
For example:
#Given:
a = [ [10, 2, 11],
[1, 3, 4],
[8, 7, 9] ]
#Your function should return:
10, 2, 11, 4, 9, 7, 8, 1, 3
"""
def print_spiral(nums):
# 10, 2, 11, 4, 9, 7, 8, 1, 3
# 4 Indicators -- row start and end, column start and end
return
a = [[10, 2, 11],
[1, 3, 4],
[8, 7, 9]]
print_spiral(a)
| true |
8b2af30e0e3e4fc2cfefbd7c7e9a60edc42538c0 | Bharadwaja92/DataInterviewQuestions | /Questions/Q_029_AmericanFootballScoring.py | 2,046 | 4.125 | 4 | """""""""
There are a few ways we can score in American Football:
1 point - After scoring a touchdown, the team can choose to score a field goal
2 points - (1) after scoring touchdown, a team can choose to score a conversion,
when the team attempts to score a secondary touchdown or
(2) an uncommon way to score, a safety is score when the opposing team causes the ball to
become dead
3 points - If no touchdown is scored on the possession, a team can attempt to make a field goal
6 points - Awarded for a touchdown
Given the above, let's assume the potential point values for American Football are:
2 points - safety
3 points - only field goal
6 points - only touchdown
7 points - touchdown + field goal
8 points - touchdown + conversion
Given a score value, can you write a function that lists the possible ways the score could have been achieved?
For example, if you're given the score value 10, the potential values are:
8 points (touchdown + conversion) + 2 points (safety)
6 points (only touchdown) + 2x2 points (safety)
7 points (touchdown + field goal) + 3 points (only field goal)
5x2 points (safety)
2x2 points (safety) + 2x3 points (only field goal)
"""
from collections import Counter
# A different version of Coin Change
possible_scores = []
def get_possible_ways(score, points, partial=[]):
s = sum(partial)
if s == score:
possible_scores.append(partial)
if s >= score:
return
for i in range(len(points)):
p = points[i]
remaining = points[i: ]
get_possible_ways(score=score, points=remaining, partial=partial+[p])
return 0
points_dict = {2: 'safety', 3: 'only field goal', 6: 'only touchdown', 7: 'touchdown + field goal',
8: 'touchdown + conversion'}
points = list(points_dict.keys())
print(points)
print(get_possible_ways(10, points))
print(possible_scores)
for ps in possible_scores:
d = dict(Counter(ps))
sent = ['{} * {} = {} Points'.format(d[v], points_dict[v], v) for v in d]
print(sent)
| true |
604a4bb01ff02dc0da1ca2ae0ac71e414c5a6afe | Bharadwaja92/DataInterviewQuestions | /Questions/Q_055_CategorizingFoods.py | 615 | 4.25 | 4 | """""""""
You are given the following dataframe and are asked to categorize each food into 1 of 3 categories:
meat, fruit, or other.
food pounds
0 bacon 4.0
1 STRAWBERRIES 3.5
2 Bacon 7.0
3 STRAWBERRIES 3.0
4 BACON 6.0
5 strawberries 9.0
6 Strawberries 1.0
7 pecans 3.0
Can you add a new column containing the foods' categories to this dataframe using python?
"""
import pandas as pd
df = pd.DataFrame(columns=['food', 'pounds'])
df['category'] = df['food'].apply(lambda f: 'fruit' if f.lower() in ['strawberries'] else 'meat' if f.lower() == 'bacon' else 'other')
| true |
58401ce6e6a3876062d2a629d39314432e08b64f | mattling9/Algorithms2 | /stack.py | 1,685 | 4.125 | 4 | class Stack():
"""a representation of a stack"""
def __init__(self, MaxSize):
self.MaxSize = MaxSize
self.StackPointer = 0
self.List = []
def size(self):
StackSize = len(self.List)
return StackSize
def pop(self):
StackSize = self.StackSize()
if StackSize > 0:
self.items.pop()
self.StackPointer = StackSize
else:
print("There are no items in the stack")
def push(self, item ):
size()
StackSize = self.StackSize()
if self.StackSize < MaxSize:
self.List.append(item)
self.StackPoitner = StackSize
else:
print("The stack is full")
def peek(self):
size()
StackSize = self.StackSize
if StackSize == 0:
print(" the stack is empty")
else:
print("The top item is {0}".format(self.List[StackSize-1]))
def main():
CustomStack = Stack(5)
Done = False
while Done == False:
print("Please select an option")
print()
print("1. Peek")
print("2. Push")
print("3. Pop")
print("4. Exit")
choice = int(input())
if choice == 1:
CustomStack.peek()
elif choice == 2:
CustomStack.push()
elif choice == 3:
CustomStack.pop()
elif choice == 4:
Done = True
while choice < 2 or choice > 4:
print("Please enter a valid number")
choice=int(input())
if __name__ == "__main__":
main()
| true |
31b272d2675be1ecfd20e9b4bae4759f5b533106 | iemeka/python | /exercise-lpthw/snake6.py | 1,792 | 4.21875 | 4 | #declared a variable, assigning the string value to it.
#embedded in the string is a format character whose value is a number 10 assigned to it
x = "There are %d types of people." % 10
#declared a variable assigning to it the string value
binary = "binary"
#same as above
do_not = "don't"
# also same as above but with who format characters whose values variables
# hence the value of the two format characters equals the value of the two variables assigned to the format character
y = "Those who know %s and those who %s." % (binary, do_not)
# told python to print the values of the variable x
print x
# told python to print the values of the variable y
print y
# here python has the print a string in which a format character is embedded and whose value is he
# the values of he variable x
print "I said: %r." % x
# same here ...which value is the values of the variable y
print " I also said: '%s'. " % y
#assigned a boolean to a variable
hilarious = False
# declared a variable assigning assigning to it a string with an embedded format character
joke_evaluation = "Isn't that joke so funny?! %r"
# told python to print the value of the variable which is a string which a format character
# is embedded in it then assigning the value of the embedde character in the string the value
# of another variable.
# so python has to print a variable value assigning a variable to the format character in the first variable value
print joke_evaluation % hilarious
w = "This is the left side of..."
e = "a string with a right side."
# here python simply joined two stings together using the operator + thats why is makes
# a longer string. In javaScript is called concatenation of strings (learnt javaScript initially) tongue out* <(-,-)>
print w + e
# yes! they are four places fuck you shaw! | true |
ed10b4f7cebef6848b14803ecf76a16b8bc84ca4 | iemeka/python | /exercise-lpthw/snake32.py | 713 | 4.40625 | 4 | the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
# this first kind of for-loop goes through a list
for number in the_count:
print "This is count %d" % number
# same as above
for fruit in fruits:
print "A fruit of type: %s" % fruit
for i in change:
print "I got %r" % i
elements = []
# range function to do 0 to 5 counts
for i in range(0, 6):
print "Adding %d to the list." % i
# append is a function that lists understands
elements.append(i)
print "Element was: %d" % i
print elements.pop(0)
print elements[1:3]
elements[3] = "apple"
print elements
del elements[2]
print elements
print len(elements)
print elements[2]
| true |
bb1a2972bc806e06fe6302c703c158130318bf07 | iemeka/python | /exercise-lpthw/snake20.py | 1,128 | 4.21875 | 4 | from sys import argv
script, input_file = argv
# a function to read the file held and open in the variable 'current_file' and then passed..
# the variable is passed to this functions's arguement
def print_all(f):
print f.read()
# seek takes us to the begining of the file
def rewind(f):
f.seek(0)
# we print the numer of the line we want to read and the we print the content of the line
# the comma makes sure the 'print' doesnt end with newline
def print_a_line(line_count, f):
print line_count, f.readline(),
current_file = open(input_file)
print "First let's print the whole file:\n"
# calling the function print_all'
print_all(current_file)
print "Now lets rewind, kind of like a tape"
# calling the function 'rewind'
rewind(current_file)
print "Let's print three lines:"
#calling functions
current_line = 1
print_a_line(current_line, current_file)
# current_line = 1 (initially) plus another 1. current lines = 2
current_line +=1
print_a_line(current_line, current_file)
# current_line = 2 (from the last global variable) plus another 1. current lines = 3
current_line +=1
print_a_line(current_line, current_file) | true |
3d3bb07c0afda8d2c9943a39883cbbee67bfe4b1 | icgowtham/Miscellany | /python/sample_programs/tree.py | 2,130 | 4.25 | 4 | """Tree implementation."""
class Node(object):
"""Node class."""
def __init__(self, data=None):
"""Init method."""
self.left = None
self.right = None
self.data = data
# for setting left node
def set_left(self, node):
"""Set left node."""
self.left = node
# for setting right node
def set_right(self, node):
"""Set right node."""
self.right = node
# for getting the left node
def get_left(self):
"""Get left node."""
return self.left
# for getting right node
def get_right(self):
"""Get right node."""
return self.right
# for setting data of a node
def set_data(self, data):
"""Set data."""
self.data = data
# for getting data of a node
def get_data(self):
"""Get data."""
return self.data
# Left -> Root -> Right: ./\.
def in_order(node):
"""In-order traversal (Left->Root->Right)."""
if node:
in_order(node.get_left())
print(node.get_data(), end=' ')
in_order(node.get_right())
return
# Root -> Left ->Right: \._.
def pre_order(node):
"""Pre-order traversal (Root->Left->Right)."""
if node:
print(node.get_data(), end=' ')
pre_order(node.get_left())
pre_order(node.get_right())
return
# Left -> Right -> Root: ._.\
def post_order(node):
"""Post-order traversal (Left->Right->Root)."""
if node:
post_order(node.get_left())
post_order(node.get_right())
print(node.get_data(), end=' ')
return
if __name__ == '__main__':
root = Node(1)
root.set_left(Node(2))
root.set_right(Node(3))
root.left.set_left(Node(4))
print('In-order Traversal:')
in_order(root)
print('\nPre-order Traversal:')
pre_order(root)
print('\nPost-order Traversal:')
post_order(root)
# OUTPUT:
# Inorder Traversal:
# 4 2 1 3
# Preorder Traversal:
# 1 2 4 3
# Postorder Traversal:
# 4 2 3 1
| true |
87661803c954900ef11a81ac450ffaaf76b83167 | truas/kccs | /python_overview/python_database/database_03.py | 1,482 | 4.375 | 4 | import sqlite3
'''
The database returns the results of the query in response to the cursor.fetchall call
This result is a list with one entry for each record in the result set
'''
def make_connection(database_file, query):
'''
Common connection function that will fetch data with a given query in a specific DB
The cursor will be closed at the end of it
'''
connection = sqlite3.connect(database_file)
cursor = connection.cursor()
cursor.execute(query) # if id is available here we can also use cursor.execute(query, [person_id])
results = cursor.fetchall()
cursor.close()
connection.close()
return results
def get_name(database_file, person_id):
'''
Here we get one specific record according to an ID
Different from database_01 we are using variable names to compose our query,
just make sure to compose one string at the end
'''
query = "SELECT personal || ' ' || family FROM Person WHERE id='" + person_id + "';"
results = make_connection(database_file, query)
return results[0][0]
def get_allnames(database_file):
'''
Here we fetch all data in our table, regardless of id
'''
query = "SELECT personal || ' ' || family FROM Person;"
results = make_connection(database_file, query)
return results
print("Full name for dyer:", get_name('survey.db', 'dyer')) # specific id
partial = get_allnames("survey.db") # all results
for item in partial:
print(item[0]) | true |
5217a281d3ba76965d0cb53a38ae90d16e7d7640 | truas/kccs | /python_overview/python_oop/abstract_animal_generic.py | 2,001 | 4.25 | 4 | from abc import ABC, abstractmethod #yes this is the name of the actual abstract class
'''
From the documentation:
"This module provides the infrastructure for defining abstract base classes (ABCs) in Python"
'''
class AbstractBaseAnimal(ABC):
'''
Here we have two methods that need to be implemented by any class that extends AbstractBaseAnimal
'''
@abstractmethod
def feed(self, other_food=None):
print("All animals have to feed!")
@abstractmethod
def sleep(self, state=1):
if state == 1:
print("This animal needs to sleep")
else:
print("This animal does not need to sleep")
# no abstract, we can implement if we want, but it is not required
def exist(self):
print("I am alive!")
class Dolphins(AbstractBaseAnimal):
'''
All the abstract methods need to be implemented otherwise we cannot instantiate any object
from this class
'''
def __init__(self, food="Fish"):
self.food_type = food
'''
Note that the abstract functions need to be implemented, even if with 'pass' (try that)
We don't need to follow the same signature of the function but it has to be implemented
Notice we do not implement the method 'exist()'. Why ? Try to spot the difference between
this exist() and the other methods. That's right, exist() is not an abstract method,
thus we do not need to implement in our class.
'''
# this is an abstract method from our base class
def feed(self, alternative=None):
print("I like to eat ", self.food_type)
print("I can also eat other things, such as ", alternative)
# this is an abstract method from our base class
def sleep(self, state=-1):
if state == 1:
print("This animal needs to sleep.")
elif state == 0:
print("This animal does not need to sleep.")
elif state == -1:
print("This animal only sleeps with half of the brain.") | true |
f0c289169c7eea7a8d4675450cda1f36b10c3baf | alexeydevederkin/Hackerrank | /src/main/python/min_avg_waiting_time.py | 2,648 | 4.4375 | 4 | #!/bin/python3
'''
Tieu owns a pizza restaurant and he manages it in his own way. While in a normal restaurant,
a customer is served by following the first-come, first-served rule, Tieu simply minimizes
the average waiting time of his customers. So he gets to decide who is served first,
regardless of how sooner or later a person comes.
Different kinds of pizzas take different amounts of time to cook. Also, once he starts cooking a pizza,
he cannot cook another pizza until the first pizza is completely cooked. Let's say we have three customers
who come at time t=0, t=1, & t=2 respectively, and the time needed to cook their pizzas is 3, 9, & 6 respectively.
If Tieu applies first-come, first-served rule, then the waiting time of three customers is 3, 11, & 16 respectively.
The average waiting time in this case is (3 + 11 + 16) / 3 = 10. This is not an optimized solution.
After serving the first customer at time t=3, Tieu can choose to serve the third customer.
In that case, the waiting time will be 3, 7, & 17 respectively.
Hence the average waiting time is (3 + 7 + 17) / 3 = 9.
Help Tieu achieve the minimum average waiting time. For the sake of simplicity,
just find the integer part of the minimum average waiting time.
input:
3
0 3
1 9
2 6
output:
9
'''
from queue import PriorityQueue
def solve():
queue_arrival = PriorityQueue()
queue_cook_time = PriorityQueue()
end_time = 0
sum_time = 0
num = int(input())
# parse all data and push it in queue_arrival
for i in range(num):
arrival, cook_time = [int(x) for x in input().split()]
queue_arrival.put((arrival, cook_time))
while True:
next_arrival = 0
# pop all arrived by end_time from queue_arrival
# push them into queue_cook_time
if not queue_arrival.empty():
next_arrival = queue_arrival.queue[0][0]
while not queue_arrival.empty() and end_time >= queue_arrival.queue[0][0]:
arrival, cook_time = queue_arrival.get()
queue_cook_time.put((cook_time, arrival))
# pop 1 item from queue_cook_time or move to next_arrival or break
if queue_cook_time.empty():
if queue_arrival.empty():
break
end_time = next_arrival
continue
else:
cook_time, arrival = queue_cook_time.get()
# add waiting time for it to sum_time
# update end_time
end_time += cook_time
sum_time += end_time - arrival
average_time = sum_time // num
print(average_time)
if __name__ == '__main__':
solve() | true |
2e86e6d499de5d51f19051728db135aac6b36044 | avisek-3524/Python- | /oddeven.py | 260 | 4.1875 | 4 | '''write a program to print all the numbers from
m-n thereby classifying them as even or odd'''
m=int(input('upper case'))
n=int(input('lower case'))
for i in range(m,n+1):
if(i%2==0):
print(str(i)+'--even')
else:
print(str(i)+'--odd') | true |
4a4f0e71027d92fa172f78811993aa1d62e2a6c7 | JuveVR/Homework_5 | /Exercise_2.py | 2,650 | 4.21875 | 4 | #2.1
class RectangularArea:
"""Class for work with square geometric instances """
def __init__(self, side_a, side_b):
"""
Defines to parameters of RectangularArea class. Checks parameters type.
:param side_a: length of side a
:param side_b:length of side a
"""
self.side_a = side_a
self.side_b = side_b
if type(self.side_a) and type(self.side_b) == int or float:
pass
else:
raise Exception("Wrong type, sides should be int or float")
def square(self):
"""
:return: value of square for class instance
"""
return self.side_a * self.side_b
def perimeter(self):
"""
:return: alue of square for class instance
"""
return (self.side_b + self.side_a)*2
#2.2
class Dot:
"""Defines coordinates of the dot on the map"""
def __init__(self, x, y):
"""
:param x: distance from point x to y-axis
:param y: distance from point y to x-axis
"""
self.x = x
self.y = y
def dist_from_zero_version1(self):
"""
:return: the distance on the plain from the dot to the origin
"""
x1 = 0
y1 = 0
d = ((self.x-x1)**2 + (self.y - y1)**2)**0.5
return d
def dist_from_zero_version2(self, x2=0, y2=0):
"""
:param x2: origin of x-axis (by default)
:param y2: origin of y-axis (by default)
:return: :return: the distance on the plain from the dot to the origin
"""
dv2 = ((self.x-x2)**2 + (self.y - y2)**2)**0.5
return dv2
def between_two_dots(self, x3, y3): # I am not sure that this is correct way to solve your exercise
"""
:param x3: distance from point x to y-axis
:param y3: distance from point y to x-axis
:return: the distance on the plain between two dots
"""
d = ((self.x - x3) ** 2 + (self.y - y3) ** 2) ** 0.5
return d
def three_dimensional(self, z): # Maybe I misunderstood the task. My method looks weird
"""
Converts coordinates to three_dimensional system
:param z: distance from point x to xy plane
:return: coordinates of the dot in three_dimensional system
"""
return (self.x, self.y, z)
if __name__ == "__main__":
rect = RectangularArea(10, 12)
print(rect.square())
print(rect.perimeter())
dot1 = Dot(20,20)
print(dot1.dist_from_zero_version1())
print(dot1.dist_from_zero_version2())
print(dot1.between_two_dots(34.4, 45))
print(dot1.three_dimensional(12))
| true |
0b0e1f3f55ae4faa409b1fefb704b577aebb6c87 | saicataram/MyWork | /DL-NLP/Assignments/Assignment4/vowel_count.py | 801 | 4.3125 | 4 | """
*************************************************************************************
Author: SK
Date: 30-Apr-2020
Description: Python Assignments for practice;
a. Count no of vowels in the provided string.
*************************************************************************************
"""
def vowel_count(str):
# Initializing count variable to 0
count = 0
# Creating a set of vowels
vowel = set("aeiouAEIOU")
# Loop to traverse the alphabet
# in the given string
for alphabet in str:
# If alphabet is present
# in set vowel
if alphabet in vowel:
count = count + 1
print("No. of vowels :", count)
str = input("Enter a character: ")
# Function Call
vowel_count(str) | true |
bd557b8cb881b1a6a0832b347c6855289a7c7cef | saicataram/MyWork | /DL-NLP/Assignments/Assignment4/lengthofStringinList.py | 528 | 4.375 | 4 | """
*************************************************************************************
Author: SK
Date: 30-Apr-2020
Description: Python Assignments for practice;
a. Count length of the string in list provided.
*************************************************************************************
"""
string = ["mahesh","hello","nepal","Hyderabad","mahesh","Delhi", "Amsterdam", "Tokyo"]
index = len(string)
for i in range (0, index):
count_each_word = len(string[i])
print(count_each_word)
| true |
d4aa13f6bd5d92ad0445200c91042b1b72f8f4cc | lilianaperezdiaz/cspp10 | /unit4/Lperez_rps.py | 2,982 | 4.3125 | 4 | import random
#function name: get_p1_move
# arguments: none
# purpose: present player with options, use input() to get player move
# returns: the player's move as either 'r', 'p', or 's'
def get_p1_move():
move=input("rock, paper, scissors: ")
return move
#function name: get_comp_move():
# arguments: none
# purpose: randomly generates the computer's move,
# either 'r' 'p' or 's'
# returns: the computer's randomly generated move
def get_comp_move():
randy=random.randint(1,3)
if randy==1:
return("rock")
elif randy==2:
return("paper")
elif randy==3:
return("scissors")
return randy
#function name: get_rounds
# arguments: none
# purpose: allows the user to choose a number of rounds from 1 to 9.
# returns: the user-chosen number of rounds
def get_rounds():
rounds=int(input("How many rounds do you want to play 1-9: "))
return rounds
#function name: get_round_winner
# arguments: player move, computer move
# purpose: based on the player and computer's move, determine
# the winner or if it's a tie
# returns: returns a string based on the following:
# "player" if player won
# "comp" if computer won
# "tie" if it's a tie
def get_round_winner(p1move, cmove):
if p1move == cmove:
return("Tie!")
if p1move == "rock" and cmove == "paper":
return("You lose!")
elif p1move == "paper" and cmove == "rock":
return("You win!")
elif p1move == "scissors" and cmove == "rock":
return("You lose!")
elif p1move == "rock" and cmove == "scissors":
return("You win!")
elif p1move == "paper" and cmove == "scissors":
return ("You lose!")
elif p1move == "scissors" and cmove == "paper":
return ("You win!")
#function name: print_score
# arguments: player score, computer score, number of ties
# purpose: prints the scoreboard
# returns: none
def print_score(pscore, cscore, ties):
print("Player score: {}".format(pscore))
print("Computer score: {}".format(cscore))
print("Tie score: {}".format(ties))
#function name: rps
# arguments: none
# purpose: the main game loop. This should be the longest, using
# all the other functions to create RPS
# returns: none
def rps():
pscore=0
cscore=0
ties=0
rounds = get_rounds()
for rounds in range(1, rounds + 1):
p1move = get_p1_move()
randy = get_comp_move()
winner = get_round_winner(p1move, randy)
print ("Computer chose {}".format(randy))
if winner == "You win!":
print("Player won!")
pscore= pscore+1
elif winner =="You lose!":
print("Computer won!")
cscore = cscore +1
else:
print("It's a tie!")
ties = ties+1
print_score(pscore,cscore,ties)
print("_________________________________")
rps() | true |
287660ee7a1580903b9815b83106e8a5bd6e0c20 | 5folddesign/100daysofpython | /day_002/day_004/climbing_record_v4.py | 2,228 | 4.15625 | 4 | #python3
#climbing_record.py is a script to record the grades, and perceived rate of exertion during an indoor rock climbing session.
# I want this script to record: the number of the climb, wall type, grade of climb, perceived rate of exertion on my body, perceived rate of exertion on my heart, and the date and time of the climbing session. I then want all of this information to be added to a .csv file
import csv
#import the datetime library.
csvFile = open('/Users/laptop/github/100daysofpython/day_004/climbinglog.csv','a',newline='')
csvWriter = csv.writer(csvFile,delimiter=',',lineterminator='\n\n')
#add functions for each question.
climb_number =''
wall_type = ''
grade = ''
pre_heart = ''
pre_body = ''
def climbNumber():
global climb_number
climb_number = input("What number route is this? \n > ")
answer_string = str(climb_number)
if str.isnumeric(answer_string):
pass
else:
print("You must enter a number. Try again. ")
climbNumber()
def wallType():
global wall_type
wall_type = input("What type of wall was the route on? \n >")
if str.isalpha(wall_type):
pass
else:
print("You entered a number, you must enter a word. Try again. ")
wallType()
def grade():
global grade
grade = input("What was the grade of the route? \n >")
answer_string = str(grade)
if answer_string:
pass
else:
print("You must enter a number. Try again. ")
grade()
def preBody():
global pre_body
pre_body = input("On a scale of 1-10, how difficult did this route feel on your body? \n >")
answer_string = str(pre_body)
if str.isnumeric(answer_string):
pass
else:
print("You must enter a number. Try again. ")
preBody()
def preHeart():
global pre_heart
pre_heart = input("On a scale of 1-10, how difficult did this route feel on your heart? \n >")
answer_string = str(pre_heart)
if str.isnumeric(answer_string):
pass
else:
print("You must enter a number. Try again. ")
preHeart()
climbNumber()
wallType()
grade()
preBody()
preHeart()
csvWriter.writerow([climb_number,wall_type,grade,pre_body,pre_heart])
| true |
6367b485bbbeb065dc379fa1164072db6bac22e4 | risbudveru/machine-learning-deep-learning | /Machine Learning A-Z/Part 2 - Regression/Section 4 - Simple Linear Regression/Simple linear reg Created.py | 1,590 | 4.3125 | 4 | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
#X is matrix of independent variables
#Y is matrix of Dependent variables
#We predict Y on basis of X
dataset = pd.read_csv('Salary_data.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 1].values
# Splitting the dataset into the Training set and Test set
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 1/3, random_state = 0)
#Random_state = 0 indicates no randomized factors in algorithm
#Fitting Simple linear regression to Training set
from sklearn.linear_model import LinearRegression
#This class will help us to build models
regresor = LinearRegression() #Here we created a machine
regresor.fit(X_train, y_train) #Machine has learnt
#Now, We'll predict future values based on test set
#y_pred is predicted salary vector
y_pred = regresor.predict(X_test)
#Visualization of Trainning set data
plt.scatter(X_train, y_train, color='red') #Make scatter plot of real value
plt.plot(X_train, regresor.predict(X_train), color='blue') #Plot Predictions
plt.title('Salary vs Exprience(Training Set)')
plt.xlabel('Exprience(Years)')
plt.ylabel('Salary')
plt.show
#Visualization of Test set data
plt.scatter(X_test, y_test, color='red') #Make scatter plot of real value
plt.plot(X_train, regresor.predict(X_train), color='blue') #Plot Predictions
plt.title('Salary vs Exprience(Training Set)')
plt.xlabel('Exprience(Years)')
plt.ylabel('Salary')
plt.show
| true |
84c9145c5802f5f1b2c2e70b8e2038b573220bd5 | renan09/Assignments | /Python/PythonAssignments/Assign8/fibonacci2.py | 489 | 4.15625 | 4 | # A simple generator for Fibonacci Numbers
def fib(limit):
# Initialize first two Fibonacci Numbers
a, b = 0, 1
# One by one yield next Fibonacci Number
while a < limit:
yield a
#print("a : ",a)
a, b = b, a + b
#print("a,b :",a," : ",b)
# Create a generator object
x = fib(5)
# Iterating over the generator object using for
# in loop.
print("\nUsing for in loop")
for i in fib(55):
print("\t\t Series :",i) | true |
be1a6beb03d6f54c3f3d42882c84031cd415dc83 | shaversj/100-days-of-code-r2 | /days/27/longest-lines-py/longest_lines.py | 675 | 4.25 | 4 | def find_longest_lines(file):
# Write a program which reads a file and prints to stdout the specified number of the longest lines
# that are sorted based on their length in descending order.
results = []
num_of_results = 0
with open(file) as f:
num_of_results = int(f.readline())
for line in f.readlines():
line = line.strip()
results.append([line, len(line)])
sorted_results = sorted(results, reverse=True, key=lambda x: x[1])
for num in range(0, num_of_results):
print(sorted_results[num][0])
find_longest_lines("input_file.txt")
# 2
# Hello World
# CodeEval
# Quick Fox
# A
# San Francisco
| true |
f99e68cfa634143883bfce882bc3b399bf1f1fcf | shaversj/100-days-of-code-r2 | /days/08/llist-py/llist.py | 862 | 4.21875 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def add(self, data):
new_node = Node(data)
node = self.head
# Get to the last node
previous = None
while node is not None:
node = node.next
if node is None:
previous.next = new_node
previous = node
def print_list(self):
node = self.head
while node:
print(f"{node.data} ->", end=" ")
node = node.next
print("None")
ll = LinkedList()
first_node = Node("A")
second_node = Node("B")
third_node = Node("C")
first_node.next = second_node
second_node.next = third_node
ll.head = first_node
ll.print_list()
ll.add("D")
ll.add("E")
ll.print_list()
| true |
1b68f58a36594c14385ff3e3faf8569659ba0532 | derekcollins84/myProjectEulerSolutions | /problem0001/problem1.py | 521 | 4.34375 | 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.
'''
returnedValues = []
sumOfReturnedValues = 0
for testNum in range(1, 1000):
if testNum % 3 == 0 or \
testNum % 5 == 0:
returnedValues.append(testNum)
for i in range(len(returnedValues)):
sumOfReturnedValues = \
sumOfReturnedValues \
+ returnedValues[i]
print(sumOfReturnedValues)
| true |
8b29ca12d190975f7b957645e9a18b4291e662a1 | Sohom-chatterjee2002/Python-for-Begineers | /Assignment 2 -Control statements in Python/Problem 6.py | 556 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Dec 23 14:25:28 2020
@author: Sohom Chatterjee_CSE1_T25
"""
#The set of input is given as ages. then print the status according to rules.
def age_status(age):
if(age<=1):
print("in_born")
elif(age>=2 and age<=10):
print("child")
elif(age>=11 and age<=17):
print("young")
elif(age>=18 and age<=49):
print("adult")
elif(age>=50 and age<=79):
print("old")
else:
print("very_old")
age=int(input("Enter your age: "))
age_status(age) | true |
413524181632130eb94ef936ff18caecd4d47b06 | nikhilroxtomar/Fully-Connected-Neural-Network-in-NumPy | /dnn/activation/sigmoid.py | 341 | 4.1875 | 4 | ## Sigmoid activation function
import numpy as np
class Sigmoid:
def __init__(self):
"""
## This function is used to calculate the sigmoid and the derivative
of a sigmoid
"""
def forward(self, x):
return 1.0 / (1.0 + np.exp(-x))
def backward(self, x):
return x * (1.0 - x)
| true |
8e96a6fcac5695f7f0d47e1cf3f6ecef9382cbbf | janvanboesschoten/Python3 | /h3_hours_try.py | 275 | 4.125 | 4 | hours = input('Enter the hour\n')
try:
hours = float(hours)
except:
hours = input('Error please enter numeric input\n')
rate = input('Enter your rate per hour?\n')
try:
rate = float(rate)
except:
rate = input('Error please enter numeric input\n')
| true |
ed98b46454cb7865aadfe06077dff076dfd71a73 | mujtaba4631/Python | /FibonacciSeries.py | 308 | 4.5625 | 5 | #Fibonacci Sequence -
#Enter a number and have the program generate the Fibonacci sequence to that number or to the Nth number.
n = int(input("enter the number till which you wanna generate Fibonacci series "))
a = 0
b = 1
c = a+1
print(a)
print(b)
for i in range(0,n):
c = a+ b
print(c)
a,b=b,c
| true |
2ddc4abc64069852fdd535b49a26f5712463f14a | nathanandersen/SortingAlgorithms | /MergeSort.py | 1,122 | 4.25 | 4 | # A Merge-Sort implementation in Python
# (c) 2016 Nathan Andersen
import Testing
def mergeSort(xs,key=None):
"""Sorts a list, xs, in O(n*log n) time."""
if key is None:
key = lambda x:x
if len(xs) < 2:
return xs
else:
# sort the l and r halves
mid = len(xs) // 2
l = mergeSort(xs[:mid],key)
r = mergeSort(xs[mid:],key)
# merge them r together
return merge(l,r,key)
def merge(l,r,key):
"""A merge routine to complete the mergesort."""
result = []
l_ptr = 0
r_ptr = 0
while (l_ptr < len(l) or r_ptr < len(r)):
if l_ptr == len(l):
# if we have added everything from the l
result.extend(r[r_ptr:])
return result
elif r_ptr == len(r):
# we have added everything from the r
result.extend(l[l_ptr:])
return result
elif key(l[l_ptr]) < key(r[r_ptr]):
result.append(l[l_ptr])
l_ptr += 1
else:
result.append(r[r_ptr])
r_ptr += 1
if __name__ == "__main__":
Testing.test(mergeSort)
| true |
614d2f3dfc383cf24fd979bb2918bef80fda3450 | fancycheung/LeetCodeTrying | /easy_code/Linked_List/876.middleofthelinkedlist.py | 1,180 | 4.15625 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
@author:nali
@file: 876.middleofthelinkedlist.py
@time: 2018/9/3/上午9:41
@software: PyCharm
"""
"""
Given a non-empty, singly linked list with head node head, return a middle node of linked list.
If there are two middle nodes, return the second middle node.
Example 1:
Input: [1,2,3,4,5]
Output: Node 3 from this list (Serialization: [3,4,5])
The returned node has value 3. (The judge's serialization of this node is [3,4,5]).
Note that we returned a ListNode object ans, such that:
ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, and ans.next.next.next = NULL.
Example 2:
Input: [1,2,3,4,5,6]
Output: Node 4 from this list (Serialization: [4,5,6])
Since the list has two middle nodes with values 3 and 4, we return the second one.
Note:
The number of nodes in the given list will be between 1 and 100.
"""
import sys
reload(sys)
sys.setdefaultencoding("utf8")
def middleNode(head):
"""
:type head: ListNode
:rtype: ListNode
"""
one, two = head, head
while two and two.next:
one = one.next
two = two.next.next
return one
if __name__ == "__main__":
pass | true |
4afad10bff966b08e4f0aab782049901a3fb66dc | BalintNagy/GitForPython | /Checkio/01_Elementary/checkio_elementary_11_Even_the_last.py | 1,261 | 4.21875 | 4 | """\
Even the last
You are given an array of integers. You should find the sum of the elements
with even indexes (0th, 2nd, 4th...) then multiply this summed number and
the final element of the array together. Don't forget that the first element
has an index of 0.
For an empty array, the result will always be 0 (zero).
Input: A list of integers.
Output: The number as an integer.
Example:
checkio([0, 1, 2, 3, 4, 5]) == 30
checkio([1, 3, 5]) == 30
checkio([6]) == 36
checkio([]) == 0
How it is used: Indexes and slices are important elements of coding. This
will come in handy down the road!
Precondition:
0 ≤ len(array) ≤ 20
all(isinstance(x, int) for x in array)
all(-100 < x < 100 for x in array)
"""
def checkio(array):
"""
sums even-indexes elements and multiply at the last
"""
index = 0
sumofevens = 0
try:
for i in array:
if index%2 == 0:
sumofevens += i
index += 1
return sumofevens * array[len(array)-1]
except IndexError:
return 0
print(checkio([0, 1, 2, 3, 4, 5]))
print(checkio([1, 3, 5]))
print(checkio([6]))
print(checkio([]))
| true |
92067b660f1df00f7d622b49388994c892145033 | BalintNagy/GitForPython | /OOP_basics_1/01_Circle.py | 572 | 4.125 | 4 | # Green Fox OOP Basics 1 - 1. feladat
# Create a `Circle` class that takes it's radius as cinstructor parameter
# It should have a `get_circumference` method that returns it's circumference
# It should have a `get_area` method that returns it's area
import math
class Circle:
def __init__(self, radius):
self.radius = radius
def get_circumference(self):
return 2 * self.radius * math.pi
def get_area(self):
return pow(self.radius, 2) * math.pi
karika = Circle(5)
print(karika.get_circumference())
print(karika.get_area())
| true |
7852ff2dfef25e356a65c527e94ee88d10c74a0b | BalintNagy/GitForPython | /Checkio/01_Elementary/checkio_elementary_16_Digits_multiplication.py | 929 | 4.40625 | 4 | """\
Digits Multiplication
You are given a positive integer. Your function should calculate the product
of the digits excluding any zeroes.
For example: The number given is 123405. The result will be 1*2*3*4*5=120
(don't forget to exclude zeroes).
Input: A positive integer.
Output: The product of the digits as an integer.
Example:
checkio(123405) == 120
checkio(999) == 729
checkio(1000) == 1
checkio(1111) == 1
How it is used: This task can teach you how to solve a problem with simple
data type conversion.
Precondition:
0 < number < 10^6
"""
def checkio(number: int) -> int:
numberlist = list(str(number))
product = 1
for i in numberlist:
if int(i) != 0:
product = product * int(i)
return product
print(checkio(123405))
print(checkio(999))
print(checkio(1000))
print(checkio(1111))
# szép, könnyen olvasható | true |
d5353aa98262d9de8b540c9ae863bde41ab0cda9 | mura-wx/mura-wx | /python/Practice Program/basic program/chekPositifAndNegatif.py | 306 | 4.15625 | 4 | try :
number=int(input("Enter Number : "))
if number < 0:
print("The entered number is negatif")
elif number > 0:
print("The entered number is positif")
if number == 0:
print("number is Zero")
except ValueError :
print('The input is not a number !') | true |
76b5171706f347c58c33eed212798f84c6ebcfd1 | zuxinlin/leetcode | /leetcode/350.IntersectionOfTwoArraysII.py | 1,434 | 4.1875 | 4 | #! /usr/bin/env python
# coding: utf-8
'''
'''
class Solution(object):
'''
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].
Note:
Each element in the result should appear as many times as it shows in both arrays.
The result can be in any order.
Follow up:
What if the given array is already sorted? How would you optimize your algorithm?
What if nums1's size is small compared to nums2's size? Which algorithm is better?
What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
'''
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
result = []
cache = {}
# 先用哈希表存储一个数组统计情况,另外一个数组查表即可
for i in nums1:
if i in cache:
cache[i] += 1
else:
cache[i] = 1
for i in nums2:
if i in cache and cache[i] > 0:
result.append(i)
cache[i] -= 1
return result
if __name__ == '__main__':
solution = Solution()
assert solution.intersect([1, 2, 2, 1], [2]) == [2, ]
assert solution.intersect([3, 1, 2], [1, 1]) == [1, ]
| true |
37e1234e8f39adc280dc20a3c39ea86f93143b0e | zuxinlin/leetcode | /leetcode/110.BalancedBinaryTree.py | 1,342 | 4.28125 | 4 | #! /usr/bin/env python
# coding: utf-8
'''
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.
判断一颗二叉树是否是平衡二叉树,主要是左右子树高度差有没有大于1
'''
# 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 dfs(self, root):
if root is None:
return 0
left = self.dfs(root.left)
right = self.dfs(root.right)
if left == -1 or right == -1 or abs(left - right) > 1:
return -1
else:
return max(left, right) + 1
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if self.dfs(root) == -1:
return False
else:
return True
if __name__ == '__main__':
pass
| true |
7a750725399d333e2cd1b46add1b8cc0c02b1522 | MadyDixit/ProblemSolver | /Google/Coding/UnivalTree.py | 1,039 | 4.125 | 4 | '''
Task 1: Check weather the Given Tree is Unival or Not.
Task 2: Count the Number of Unival Tree in the Tree.
'''
'''
Task 1:
'''
class Tree:
def __init__(self,x):
self.val = x
self.left = None
self.right = None
def insert(self, data):
if self.val:
if self.val > data:
if self.left is None:
self.left = Tree(data)
else:
self.left.insert(data)
else:
if self.right is None:
self.right = Tree(data)
else:
self.right.insert(data)
else:
return False
class Tasker:
def is_unival(self,root):
return unival_helper(root, root.val)
def unival_helper(self, root, value):
if root is None:
return True
elif root.val == value:
return self.unival_helper(root.left, value) and self.unival_helper(root.right, value)
return False
if __name__ == '__main__':
| true |
02d2c723586f0b98c48dde041b20e5ec86809fae | pkray91/laravel | /string/string.py | 1,254 | 4.4375 | 4 | print("Hello python");
print('Hello python');
x = '''hdbvfvhbfvhbf'''
y = """mdnfbvnfbvdfnbvfvbfm"""
print(y)
print(x)
a='whO ARE you Man';
print(a);
print(a.upper());
print(a.lower());
print(len(a));
print(a[1]);
#sub string not including the given position.
print(a[4:8]);
#The strip() method removes any whitespace from the beginning or the end:
b=" hello ";
print(b);
print(b.strip());
print(b.replace('h','l'));
#The split() method splits the string into substrings if it finds instances of the separator:
print(a.split(' '));
print(a.split('a'));
#As we learned in the Python Variables chapter, we cannot combine strings and numbers like this:
#The format() method takes unlimited number of arguments, and are placed into the respective placeholders:
age=36;
c='I am going home {}';
print(c.format(age));
quant=20;
age=28;
mobile=898767898;
txt='total men was {} and their age was {} and have only one mobile no is {}';
print(txt.format(quant,age,mobile));
age=36;
c='I am going home {}';
print(c.format(age));
quant=20;
age=28;
mobile=898767898;
txt='total men was {2} and their age was {0} and have only one mobile no is {1}';
print(txt.format(quant,age,mobile));
#reverse the string.
rev= 'hello python'[::-1];
print(rev); | true |
996520dcd43c24c0391fc8767ee4eb9f8f3d309e | AdityaChavan02/Python-Data-Structures-Coursera | /8.6(User_input_no)/8.6.py | 481 | 4.3125 | 4 | #Rewrite the program that prompts the user for a list of numbers and prints the max and min of the numbers at the end when the user presses done.
#Write the program to store the numbers in a list and use Max Min functions to compute the value.
List=list()
while True:
no=input("Enter the no that you so desire:\n")
if no=='done':
break
List.append(no)
print(List)
print("The MAX value is %d",max(List))
print("The MIN value is %d",min(List))
| true |
0ac525f075a96f8a749ddea35f8e1a59775217c8 | ZoranPandovski/al-go-rithms | /sort/selection_sort/python/selection_sort.py | 873 | 4.125 | 4 | #defines functions to swap two list elements
def swap(A,i,j):
temp = A[i]
A[i] = A[j]
A[j] = temp
#defines functions to print list
def printList(A,n):
for i in range(0,n):
print(A[i],"\t")
def selectionSort(A,n):
for start in range(0,n-1):
min=start #min is the index of the smallest element in the list during the iteration
#Scan from A[min+1] to A[n-1] to find a list element that is smaller than A[min]
for cur in range(min+1,n):
#if A[cur] is smaller than A[min] min is updated
if A[cur]<A[min]:
min = cur
#the two elements are swapped
swap(A,start,min)
def test():
A = [38,58,13, 15,21,27,10,19,12,86,49,67,84,60,25]
n = len(A)
print("Selection Sort: ")
selectionSort(A,n)
print("Sorted List: ")
printList(A,n)
test()
| true |
6b2ae13e2f7dfa26c15cef55978cf7e70f4bf711 | ZoranPandovski/al-go-rithms | /dp/min_cost_path/python/min_cost_path_.py | 809 | 4.21875 | 4 |
# A Naive recursive implementation of MCP(Minimum Cost Path) problem
R = 3
C = 3
import sys
# Returns cost of minimum cost path from (0,0) to (m, n) in mat[R][C]
def minCost(cost, m, n):
if (n < 0 or m < 0):
return sys.maxsize
elif (m == 0 and n == 0):
return cost[m][n]
else:
return cost[m][n] + min( minCost(cost, m-1, n-1),
minCost(cost, m-1, n),
minCost(cost, m, n-1) )
#A utility function that returns minimum of 3 integers */
def min(x, y, z):
if (x < y):
return x if (x < z) else z
else:
return y if (y < z) else z
# Driver program to test above functions
cost= [ [1, 2, 3],
[4, 8, 2],
[1, 5, 3] ]
print(minCost(cost, 2, 2))
| true |
1f2547aa08428209cf4d106ad8361033dd411efc | ZoranPandovski/al-go-rithms | /strings/palindrome/python/palindrome2.py | 369 | 4.53125 | 5 | #We check if a string is palindrome or not using slicing
#Accept a string input
inputString = input("Enter any string:")
#Caseless Comparison
inputString = inputString.casefold()
#check if the string is equal to its reverse
if inputString == inputString[::-1]:
print("Congrats! You typed in a PALINDROME!!")
else:
print("This is not a palindrome. Try Again.")
| true |
fc9287fca6c7b390cbd47ae7f70806b10d6114c3 | ZoranPandovski/al-go-rithms | /data_structures/b_tree/Python/check_bst.py | 1,131 | 4.28125 | 4 | """
Check whether the given binary tree is BST(Binary Search Tree) or not
"""
import binary_search_tree
def check_bst(root):
if(root.left != None):
temp = root.left
if temp.val <= root.val:
left = check_bst(root.left)
else:
return False
else:
left = True
if(root.right != None):
temp = root.right
if temp.val > root.val:
right = check_bst(root.right)
else:
return False
else:
right = True
if (left and right):
return True
else:
return False
# ### Testcases ###
#
# root = None
# tree = binary_search_tree.Tree()
#
# # This tree should return Tree
# root = tree.insert(root, 6)
# root = tree.insert(root,3)
# root = tree.insert(root,1)
# root = tree.insert(root,4)
# root = tree.insert(root,8)
# root = tree.insert(root,7)
# root = tree.insert(root,9)
# tree.preorder(root)
# print check_bst(root)
#
# # This tree should return False
# root = tree.not_bst()
# print check_bst(root)
| true |
bf23783e9c07a11cdf0a186ab28da4edc1675b54 | ZoranPandovski/al-go-rithms | /sort/Radix Sort/Radix_Sort.py | 1,369 | 4.1875 | 4 | # Python program for implementation of Radix Sort
# A function to do counting sort of arr[] according to
# the digit represented by exp.
def countingSort(arr, exp1):
n = len(arr)
# The output array elements that will have sorted arr
output = [0] * (n)
# initialize count array as 0
count = [0] * (10)
# Store count of occurrences in count[]
for i in range(0, n):
index = arr[i] // exp1
count[index % 10] += 1
# Change count[i] so that count[i] now contains actual
# position of this digit in output array
for i in range(1, 10):
count[i] += count[i - 1]
# Build the output array
i = n - 1
while i >= 0:
index = arr[i] // exp1
output[count[index % 10] - 1] = arr[i]
count[index % 10] -= 1
i -= 1
# Copying the output array to arr[],
# so that arr now contains sorted numbers
i = 0
for i in range(0, len(arr)):
arr[i] = output[i]
# Method to do Radix Sort
def radixSort(arr):
# Find the maximum number to know number of digits
max1 = max(arr)
# Do counting sort for every digit. Note that instead
# of passing digit number, exp is passed. exp is 10^i
# where i is current digit number
exp = 1
while max1 / exp > 0:
countingSort(arr, exp)
exp *= 10
# Driver code
arr = [170, 45, 75, 90, 802, 24, 2, 66]
# Function Call
radixSort(arr)
for i in range(len(arr)):
print(arr[i])
# This code is contributed by Manas Misra
| true |
45d1f94946fb66eb792a8dbc8cbdb84c216d381c | ZoranPandovski/al-go-rithms | /math/leapyear_python.py | 491 | 4.25 | 4 | '''Leap year or not'''
def leapyear(year):
if (year % 4 == 0) and (year % 100 != 0) or (year % 400==0) : #checking for leap year
print(year," is a leap year") #input is a leap year
else:
print(year," is not a leap year") #input is not a leap year
year=int(input("Enter the year: "))
while year<=999 or year>=10000: #check whether the year is four digit number or not
print("Enter a year having four digits.")
year=int(input("Enter the year: "))
leapyear(year) | true |
533b8c91219f7c4a2e51f952f88581edb8446fd5 | ZoranPandovski/al-go-rithms | /sort/python/merge_sort.py | 1,809 | 4.25 | 4 | """
This is a pure python implementation of the merge sort algorithm
For doctests run following command:
python -m doctest -v merge_sort.py
or
python3 -m doctest -v merge_sort.py
For manual testing run:
python merge_sort.py
"""
from __future__ import print_function
def merge_sort(collection):
"""Pure implementation of the merge sort algorithm in Python
:param collection: some mutable ordered collection with heterogeneous
comparable items inside
:return: the same collection ordered by ascending
Examples:
>>> merge_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3, 5]
>>> merge_sort([])
[]
>>> merge_sort([-2, -5, -45])
[-45, -5, -2]
"""
length = len(collection)
if length > 1:
midpoint = length // 2
left_half = merge_sort(collection[:midpoint])
right_half = merge_sort(collection[midpoint:])
i = 0
j = 0
k = 0
left_length = len(left_half)
right_length = len(right_half)
while i < left_length and j < right_length:
if left_half[i] < right_half[j]:
collection[k] = left_half[i]
i += 1
else:
collection[k] = right_half[j]
j += 1
k += 1
while i < left_length:
collection[k] = left_half[i]
i += 1
k += 1
while j < right_length:
collection[k] = right_half[j]
j += 1
k += 1
return collection
if __name__ == '__main__':
try:
raw_input # Python 2
except NameError:
raw_input = input # Python 3
user_input = input('Enter numbers separated by a comma:\n').strip()
unsorted = [int(item) for item in user_input.split(',')]
print(merge_sort(unsorted))
| true |
0fbd0364c4afb58c921db8d3a036916e69b5a2b1 | ZoranPandovski/al-go-rithms | /sort/bubble_sort/python/capt-doki_bubble_sort.py | 652 | 4.3125 | 4 | # Python program for implementation of Bubble Sort
# TIME COMPLEXITY -- O(N^2)
# SPACE COMPLEXITY -- O(1)
def bubbleSort(arr):
n = len(arr)
# Traverse through all array elements
for i in range(n):
# Last i elements are already in place
for j in range(0, n-i-1):
# traverse the array from 0 to n-i-1
# Swap if the element found is greater
# than the next element
if arr[j] > arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]
arr = [64, 34, 25, 12, 22, 11, 90]
bubbleSort(arr)
print ("Sorted array is:")
for i in range(len(arr)):
print (arr[i]) | true |
0b275806d4228c967856b0ff6995201b7af57e5e | ZoranPandovski/al-go-rithms | /data_structures/Graphs/graph/Python/closeness_centrality.py | 1,585 | 4.28125 | 4 | """
Problem :
Calculate the closeness centrality of the nodes of the given network
In general, centrality identifies the most important vertices of the graph.
There are various measures for centrality of a node in the network
For more details : https://en.wikipedia.org/wiki/Closeness_centrality
Formula :
let C(x) be the closeness centrality of the node x.
C(x) = (N-1) / (sum of shortest paths between x & all nodes in the graph)
"""
def bfs(x: int) -> int:
"""
Does BFS traversal from node x
Returns the sum of all shortest distances
"""
sum_d = 0
# store the shortest distance from x
d = [-1 for _ in range(len(adj))]
# queue
queue = []
queue.append(x)
d[x] = 0
while len(queue) != 0:
front = queue[0]
queue.pop(0)
for v in adj[front]:
if d[v] == -1:
queue.append(v)
d[v] = d[front] + 1
sum_d += d[v]
return sum_d
def closeness_centrality():
"""
calculates the closeness centrality
Returns:
A list containing the closeness centrality of all nodes
"""
n = len(adj)
closeness_centrality = []
for i in range(len(adj)):
closeness_centrality.append((n - 1) / bfs(i))
return closeness_centrality
if __name__ == "__main__":
global adj
adj = [[] for _ in range(5)]
adj[0] = [1, 3]
adj[1] = [0, 2, 4]
adj[2] = [1]
adj[3] = [0, 4]
adj[4] = [1, 3]
closeness_centrality = closeness_centrality()
print("Closeness centrality : {}".format(closeness_centrality))
| true |
9b8696686283cf9e7afea3bf7b1ac976c3233a54 | ZoranPandovski/al-go-rithms | /dp/EditDistance/Python/EditDistance.py | 1,017 | 4.15625 | 4 | from __future__ import print_function
def editDistance(str1, str2, m , n):
# If first string is empty, the only option is to
# insert all characters of second string into first
if m==0:
return n
# If second string is empty, the only option is to
# remove all characters of first string
if n==0:
return m
# If last characters of two strings are same, nothing
# much to do. Ignore last characters and get count for
# remaining strings.
if str1[m-1]==str2[n-1]:
return editDistance(str1,str2,m-1,n-1)
# If last characters are not same, consider all three
# operations on last character of first string, recursively
# compute minimum cost for all three operations and take
# minimum of three values.
return 1 + min(editDistance(str1, str2, m, n-1), # Insert
editDistance(str1, str2, m-1, n), # Remove
editDistance(str1, str2, m-1, n-1) # Replace
)
# Driver program to test the above function
str1 = "sunday"
str2 = "saturday"
print(editDistance(str1, str2, len(str1), len(str2)))
| true |
044b06fda913253faaa6ac13b30308aa18c7aa47 | th3n0y0u/C2-Random-Number | /main.py | 577 | 4.4375 | 4 | import random
print("Coin Flip")
# 1 = heads, 2 = tails
coin = random.randint(1,2)
if(coin == 1):
print("Heads")
else:
print("Tails")
# Excecise: Create a code that mimics a dice roll using random numbers. The code of the print what number is "rolled", letting the user what it is.
dice = random.randint(1,6)
if(dice == 1):
print("You rolled a 1")
elif(dice == 2):
print("You rolled a 2")
elif(dice == 3):
print("You rolled a 3")
elif(dice == 4):
print("You rolled a 4")
elif(dice == 5):
print("You rolled a 5")
elif(dice == 6):
print("You rolled a 6") | true |
869a95eb86410b60b95c95c08ab58a93193b55e1 | thevarungrovers/Area-of-circle | /Area Of Circle.py | 209 | 4.25 | 4 | r = input("Input the radius of the circle:") # input from user
r = float(r) # typecasting
a = 3.14159265 * (r**2) # calculating area
print(f'The area of circle with radius {r} is {a}') # return area
| true |
2c969e27e178cb286b98b7e320b5bbdcaee3b8f7 | ProximaDas/HW06 | /HW06_ex09_04.py | 1,579 | 4.53125 | 5 | #!/usr/bin/env python
# HW06_ex09_04.py
# (1)
# Write a function named uses_only that takes a word and a string of letters,
# and that returns True if the word contains only letters in the list.
# - write uses_only
# (2)
# Can you make a sentence using only the letters acefhlo? Other than "Hoe
# alfalfa?"
# - write function to assist you
# - type favorite sentence(s) here:
# 1: reproachful coalfishes
# 2: coalfishes reproachfully
# 3: coalfishes reproachfulnesses
##############################################################################
# Imports
import itertools
# Body
def uses_only(word,letters):
flag = False
for letter in word.lower():
if letter in letters.lower():
flag = True
else:
flag = False
break
return flag
def make_sentence():
letters = "acefhlo"
flag = False
word_list = []
with open("words.txt","r") as handler:
words = handler.read().split()
for word in words:
for letter in letters:
if letter in word:
flag = True
else:
flag = False
break
if flag == True:
word_list.append(word)
print ' '.join(word_list)
# def combination():
# list_ = list('acefhlo')
# new = itertools.chain.from_iterable(itertools.combinations(list_,i) for i in range(len(list_)+1))
# # print list(new)
# while True:
# try:
# print ''.join(new.next())
# except:
# break
##############################################################################
def main():
print uses_only("banana","aBn")
make_sentence()
combination()
if __name__ == '__main__':
main()
| true |
308a96b56534d587575e0be55f037bdcbeb5c06e | subbul/python_book | /lists.py | 2,387 | 4.53125 | 5 | simple_list = [1,2,3]
print "Simple List",simple_list
hetero_list = [1,"Helo",[100,200,300]]# can containheterogenous values
print "Original List",hetero_list
print "Type of object hetero_list",type(hetero_list) # type of object, shows its fundamental data type, for e.g., here it is LIST
print "Item at index 0 ",hetero_list[0] #first index
print "Item at index -1",hetero_list[-1] #negative index start from end so here the last elemtn in LIST
print "Length -->", len(hetero_list)
print "#############################################"
big_list = [1,2,3,4,5,6,7,8,9]
print " big List", big_list
print "lets slice from index [2:]",big_list[2:] # start, end index, includes start, ends before end-index
print " slice till [:4]", big_list[:4] # stops before index 4 , 0-1-2-3
new_list = big_list[:] #from beginning to end
print "New list is a copy of big list", new_list
print "##############################################"
big_list = [1,2,3,4,5,6,7,8,9]
big_list[2]="x"
print " Index 2 is modified to x-->"
print big_list
big_list[len(big_list):] = [11,12,13] # adding at the end appending
print "Appended list", big_list
print " Append vs Extend list"
list_a = [1,2,3]
list_b = ['a','b','c']
print "list a", list_a
print "list b", list_b
list_a.append(list_b)
print "Append b to a", list_a
list_a = [1,2,3]
list_a.extend(list_b)
print "Extend b to a", list_a
list_a = [1,2,3]
print "Original list", list_a
list_a.insert(1,"x")
print " x insert before index 1",list_a
list_a = [1,2,3]
list_a.reverse()
print "reverse list", list_a
print "1 in list_a", (1 in list_a)
print "10 in list_a", (10 in list_a)
print "###################################################"
def custom_sort(string1):
return len(string1)
list_a = ["I am","good","World","Very big statement"]
list_a.sort()
print "Sorted naturally alphabetical", list_a
list_a = ["I am","good","World","Very big statement"]
list_a.sort(key=custom_sort)
print "Sorted using custom key", list_a
list_a = [10] * 4
print "list with initialization using *", list_a
list_a = [1,11] * 4
print "list with initialization using *", list_a
list_a = [10,20,30,40,50,60]
print "List -->", list_a
print "Index of 40-->", list_a.index(40)
list_a = [20,2,442,3,2,67,3]
print "List -->", list_a
print "Count occurance of 3 in list ==",list_a.count(3) | true |
6a8aa8ce16427dab54ddc650747a5fcb306b86ba | twilliams9397/eng89_python_oop | /python_functions.py | 897 | 4.375 | 4 | # creating a function
# syntax def name_of_function(inputs) is used to declare a function
# def greeting():
# print("Welcome on board, enjoy your trip!")
# # pass can be used to skip without any errors
#
# greeting() # function must be called to give output
#
# def greeting():
# return "Welcome on board, enjoy your trip!"
#
# print(greeting())
# def greeting(name):
# return "Welcome on board " + name
#
# print(greeting("Tom"))
# def greeting(name):
# return "Welcome on board " + name + "!"
#
# print(greeting(input("What is your name? ").capitalize()))
# functions can have multiple arguments and data types
# def add(num1, num2):
# return num1 + num2
#
# print(add(2, 3))
def multiply(num1, num2):
return num1 * num2
print("this is the required outcome of two numbers") # this line will not execute as it is after return statement
print(multiply(3, 5))
| true |
27c6ec9e71d1d1cdd87ae03180937f2d798db4b2 | leocjj/0123 | /Python/python_dsa-master/recursion/int_to_string.py | 393 | 4.125 | 4 | #!/usr/bin/python3
"""
Convert an integer to a string
"""
def int_to_string(n, base):
# Convert an integer to a string
convert_string = '0123456789ABCDEF'
if n < base:
return convert_string[n]
else:
return int_to_string(n // base, base) + convert_string[n % base]
if __name__ == '__main__':
print(int_to_string(1453, 16))
print(int_to_string(10, 2))
| true |
e81c76e31dd827790d6b98e739763201cfc618ab | tlepage/Academic | /Python/longest_repetition.py | 1,121 | 4.21875 | 4 | __author__ = 'tomlepage'
# Define a procedure, longest_repetition, that takes as input a
# list, and returns the element in the list that has the most
# consecutive repetitions. If there are multiple elements that
# have the same number of longest repetitions, the result should
# be the one that appears first. If the input list is empty,
# it should return None.
def longest_repetition(i):
count = 0
largest_count = 0
curr = None
largest = None
for e in i:
if curr == None:
curr = e
largest = e
count = 1
else:
if e == curr:
count += 1
if count > largest_count:
largest_count = count
largest = curr
else:
curr = e
count = 1
return largest
#For example,
print longest_repetition([1, 2, 2, 3, 3, 3, 2, 2, 1])
# 3
print longest_repetition(['a', 'b', 'b', 'b', 'c', 'd', 'd', 'd'])
# b
print longest_repetition([1,2,3,4,5])
# 1
print longest_repetition([])
# None
print longest_repetition([2, 2, 3, 3, 3])
| true |
9682bdce76206453617d5b26c2c219becb5d4001 | yougov/tortilla | /tortilla/formatters.py | 444 | 4.125 | 4 | # -*- coding: utf-8 -*-
def hyphenate(path):
"""Replaces underscores with hyphens"""
return path.replace('_', '-')
def mixedcase(path):
"""Removes underscores and capitalizes the neighbouring character"""
words = path.split('_')
return words[0] + ''.join(word.title() for word in words[1:])
def camelcase(path):
"""Applies mixedcase and capitalizes the first character"""
return mixedcase('_{0}'.format(path))
| true |
d817d8f491e23137fd24c3184d6e594f1d8381b0 | GaneshManal/TestCodes | /python/practice/syncronous_1.py | 945 | 4.15625 | 4 | """
example_1.py
Just a short example showing synchronous running of 'tasks'
"""
from multiprocessing import Queue
def task(name, work_queue):
if work_queue.empty():
print('Task %s nothing to do', name)
else:
while not work_queue.empty():
count = work_queue.get()
total = 0
for x in range(count):
print('Task %s running' % name)
total += 1
print('Task %s total: %s' %(name, str(total)))
def main():
"""
This is the main entry point for the program
"""
# create the queue of 'work'
work_queue = Queue()
# put some 'work' in the queue
for work in [15, 10, 5, 2]:
work_queue.put(work)
# create some tasks
tasks = [
(task, 'One', work_queue),
(task, 'Two', work_queue)
]
# run the tasks
for t, n, q in tasks:
t(n, q)
if __name__ == '__main__':
main()
| true |
5a9161c4f8f15e0056fd425a5eee58de16ec45bf | beb777/Python-3 | /003.py | 417 | 4.28125 | 4 | #factorial n! = n*(n-1)(n-2)..........*1
number = int(input("Enter a number to find factorial: "))
factorial = 1;
if number < 0:
print("Factorial does not defined for negative integer");
elif (number == 0):
print("The factorial of 0 is 1");
else:
while (number > 0):
factorial = factorial * number
number = number - 1
print("factorial of the given number is: ")
print(factorial) | true |
1c922b07b6b1f011b91bc75d68ece9b8e2958576 | Leah36/Homework | /python-challenge/PyPoll/Resources/PyPoll.py | 2,168 | 4.15625 | 4 | import os
import csv
#Create CSV file
election_data = os.path.join("election_data.csv")
#The list to capture the names of candidates
candidates = []
#A list to capture the number of votes each candidates receives
num_votes = []
#The list to capture the number of votes each candidates gather
percent_votes = []
#The counter for the total number of votes
total_votes = 0
with open(election_data, newline = "") as csvfile:
csvreader = csv.reader(csvfile, delimiter = ",")
csv_header = next(csvreader)
for row in csvreader:
#Add to our vote-countr
total_votes += 1
#If the candidate is not on our list, add his/her name to our list, along with
#a vote in his/her name.
#If he/she is already on our list, we will simply add a vote in his/her name.
if row[2] not in candidates:
candidates.append(row[2])
index = candidates.index(row[2])
num_votes.append(1)
else:
index = candidates.index(row[2])
num_votes[index] += 1
#Add to percent_votes list
for votes in num_votes:
percentage = (votes/total_votes) * 100
percentage = round(percentage)
percentage = "%.3f%%" % percentage
percent_votes.append(percentage)
#Find the winning candidate
winner = max(num_votes)
index = num_votes.index(winner)
winning_candidate = candidates[index]
#Display the results
print("Election Results")
print("------------")
print(f"Total Votes:{str(total_votes)}")
print("------------")
for i in range(len(candidates)):
print(f"{candidates[1]}: {str[percent_votes[i])} ({str(num_votes[i])})")
print("-----------")
print(f"Winner: {winning_candidate}")
print("----------")
#Print to a text file
output = open("output.txt", "w")
line1 = "Election Results"
line2 = "----------"
line3 = str(f"Total Votes: {str(total_votes)}")
line4 = str("----------")
output.write('{}\n{}\n{}\n{}\n'.formate(line1, line2, line3, line4))
for i in range(len(candidates)):
line = str(f"{candidate[i]}: {str(percent_votes[i])} ({str(num_votes[i])})")
output.write('{}\n'.format(line))
line5 = "-----------"
line6 = str(f"Winner: {winning_candidate}")
line7 = "-----------"
output.write('{}\n{}\n{}\n'.format(line5, line6,line7))
| true |
faaf4b222a3b9e120d0197c218bcd6e25c3422a4 | bwblock/Udacity | /CS101/quiz-median.py | 621 | 4.21875 | 4 | #! /usr/bin/env python
# Define a procedure, median, that takes three
# numbers as its inputs, and returns the median
# of the three numbers.
# Make sure your procedure has a return statement.
def bigger(a,b):
if a > b:
return a
else:
return b
def biggest(a,b,c):
return bigger(a,bigger(b,c))
def median(a,b,c):
big1 = bigger(a,b)
big2 = bigger(b,c)
big3 = bigger(a,c)
max = biggest(a,b,c)
if big1 == big2:
return big3
if max == big1:
return big2
else:
return big1
print(median(1,3,2))
#>>> 2
print(median(9,3,6))
#>>> 6
print(median(7,8,7))
#>>> 7
| true |
a759beda8dd1ef2309a0c200c3442bed4228f455 | naotube/Project-Euler | /euler7.py | 616 | 4.21875 | 4 | #! /usr/bin/env python
# By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13,
# we can see that the 6th prime is 13.
# What is the 10001st prime number?
primes = [2,3]
def is_prime(num):
"""if num is a prime number, returns True, else returms False"""
for i in primes:
if num % i == 0:
return False
return True
def next_prime(num):
"""returns a first prime number larger than num"""
while 1:
num = num + 1
if is_prime(num):
return num
i = 2
while len(primes) < 10002:
i = next_prime(i)
primes.append(i)
print(primes[10000])
| true |
cd9902d851dd5f7d4527d6bb80fa8abf13ef59c7 | ubaidahmadceh/python_beginner_to_expert | /isdigit_function.py | 218 | 4.25 | 4 | number = input("Enter your number : ")
if number.isdigit():
print("this is numeric (0-9)")
elif number.isalpha():
print("this is string !!")
else:
print("This is not numeric , this is symbol or alphabet")
| true |
95a17e11a79f68563c393524c22b6f45b0365599 | rob256/adventofcode2017 | /python3/day_2/day_2_part_1.py | 977 | 4.15625 | 4 | from typing import List
def checksum_line(numbers_list: iter) -> int:
"""
Given a list of numbers, return the value of the maximum - minimum values
"""
min_number = max_number = numbers_list[0]
for number in numbers_list[1:]:
min_number = min(min_number, number)
max_number = max(max_number, number)
return max_number - min_number
def get_number_list_from_line(number_list_string: str) -> List[int]:
return list(map(int, number_list_string.split()))
def checksum_spreadsheet(spreadsheet_string: str) -> int:
total_checksum = 0
for number_list_string in spreadsheet_string.split('\n'):
number_list = get_number_list_from_line(number_list_string)
total_checksum += checksum_line(number_list)
return total_checksum
def main():
with open('input.txt') as input_file:
input_text = input_file.read().rstrip()
print(checksum_spreadsheet(input_text))
if __name__ == '__main__':
main() | true |
e6886af2f0373dea4fac1f974cfca7574bca353b | daniel-cretney/PythonProjects | /primality_functions.py | 481 | 4.4375 | 4 | # this file will take a number and report whether it is prime or not
def is_primary():
number = int(input("Insert a number.\n"))
if number <= 3:
return True
else:
divisor = 2
counter = 0
for i in range(number):
if number % divisor == 0:
counter += 1
if counter > 0:
return False
else:
return True
if __name__ == "__main__":
print(is_primary()) | true |
48ea70aaf45047d633f7469efd286ddcfb1a4ec3 | jamesjakeies/python-api-tesing | /python3.7quick/5polygon.py | 347 | 4.53125 | 5 | # polygon.py
# Draw regular polygons
from turtle import *
def polygon(n, length):
"""Draw n-sided polygon with given side length."""
for _ in range(n):
forward(length)
left(360/n)
def main():
"""Draw polygons with 3-9 sides."""
for n in range(3, 10):
polygon(n, 80)
exitonclick()
main()
| true |
29362f4276d7ac83c520b89417bed94d2a771a4f | jamesjakeies/python-api-tesing | /python_crash_tutorial/Ch1/randomwalk.py | 352 | 4.25 | 4 | # randomwalk.py
# Draw path of a random walk.
from turtle import *
from random import randrange
def random_move(distance):
"""Take random step on a grid."""
left(randrange(0, 360, 90))
forward(distance)
def main():
speed(0)
while abs(xcor()) < 200 and abs(ycor()) < 200:
random_move(10)
exitonclick()
main()
| true |
51578c97eb0b4a7478be114fa2eca98b713613ca | WillDutcher/Python_Essential_Training | /Chap05/bitwise.py | 674 | 4.375 | 4 | #!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
# Completed Chap05: Lesson 21 - Bitwise operators
x = 0x0a
y = 0x02
z = x & y
# 02x gives two-character string, hexadecimal, with leading zero
# 0 = leading zero
# 2 = two characters wide
# x = hexadecimal display of integer value
# 08b gives eight-character string, binary, with leading zeroes
# 0 = leading zeroes, where applicable
# 8 = 8 characters wide
# b = binary display of integer value
print(f'(hex) x is {x:02x}, y is {y:02x}, z is {z:02x}')
print(f'(bin) x is {x:08b}, y is {y:08b}, z is {z:08b}')
print("&\tAnd")
print("|\tOr")
print("^\tXor")
print("<<\tShift left")
print(">>\tShift right")
| true |
1ce0280f860821796f022583f2b5b96950f587b9 | WillDutcher/Python_Essential_Training | /Chap05/boolean.py | 670 | 4.1875 | 4 | #!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
# Completed Chap05: Lesson 23 - Comparison operators
print("\nand\t\tAnd")
print("or\t\tOr")
print("not\t\tNot")
print("in\t\tValue in set")
print("not in\t\tValue not in set")
print("is\t\tSame object identity")
print("is not\t\tNot same object identity\n")
print("*"*50,"\n")
a = True
b = False
x = ( 'bear', 'bunny', 'tree', 'sky', 'rain' )
y = 'tree'
if a and b:
print('expression is true')
else:
print('expression is false')
if y in x:
print("Yep, it is.")
else:
print("Nope, it's not.")
if y is x[0]:
print("Yes, that's the same.")
else:
print("No, they're different.")
| true |
9be5e6cad8942160830e3d4bcca8c66dcac52370 | Avinashgurugubelli/python_data_structures | /linked_lists/singly_linked_list/main.py | 2,546 | 4.46875 | 4 | from linked_list import LinkedList
from node import Node
# Code execution starts here
if __name__ == '__main__':
# Start with the empty list
linked_list_1 = LinkedList()
# region nodes creation
first_node, second_node, third_node = Node(), Node(), Node()
first_node.data = 5
second_node.data = 10
third_node.data = 36
# endregion
# region assigning nodes to linked list
linked_list_1.head = first_node
'''
Three nodes have been created.
We have references to these three blocks as first,
second and third
linked_list_1.head second_node third_node
| | |
| | |
+----+------+ +----+------+ +----+------+
| 5 | None | | 10 | None | | 36 | None |
+----+------+ +----+------+ +----+------+
'''
linked_list_1.head.next = second_node # Link first node with second
'''
Now next of first Node refers to second. So they
both are linked.
linked_list_1.head second_node third_node
| | |
| | |
+----+------+ +----+------+ +----+------+
| 5 | o-------->| 10 | null | | 36 | null |
+----+------+ +----+------+ +----+------+
'''
second_node.next = third_node # Link second node with the third node
'''
Now next of second Node refers to third. So all three
nodes are linked.
linked_list_1.head second third
| | |
| | |
+----+------+ +----+------+ +----+------+
| 5 | o-------->| 10 | o-------->| 36 | null |
+----+------+ +----+------+ +----+------+
'''
lst_Length = linked_list_1.get_list_length
print('length of linked List: '+ str(lst_Length))
linked_list_1.print_list()
# endregion
# region Node insertion
linked_list_1.insert_node_at_position(0, 112) # Insertion at beginning
linked_list_1.insert_node_at_position(linked_list_1.get_list_length, 236) # Insertion at end
linked_list_1.insert_node_at_position(3, 99)
# endregion
# region node deletion
linked_list_1.delete_node_at_position(0)
linked_list_1.delete_node_at_position(3)
linked_list_1.delete_node_at_position(linked_list_1.get_list_length)
# end region | true |
6413f86569da08a37374f72a6c330b1fd67ff02e | DayGitH/Python-Challenges | /DailyProgrammer/DP20170705B.py | 896 | 4.21875 | 4 | """
[2017-07-05] Challenge #322 [Intermediate] Largest Palindrome
https://www.reddit.com/r/dailyprogrammer/comments/6ldv3m/20170705_challenge_322_intermediate_largest/
# Description
Write a program that, given an integer input n, prints the largest integer that is a palindrome and has two factors
both of string length n.
# Input Description
An integer
# Output Description
The largest integer palindrome who has factors each with string length of the input.
# Sample Input:
1
2
# Sample Output:
9
9009
(9 has factors 3 and 3. 9009 has factors 99 and 91)
# Challenge inputs/outputs
3 => 906609
4 => 99000099
5 => 9966006699
6 => ?
# Credit
This challenge was suggested by /u/ruby-solve, many thanks! If you have a challenge idea, please share it in
/r/dailyprogrammer_ideas and there's a good chance we'll use it.
"""
def main():
pass
if __name__ == "__main__":
main()
| true |
9843b352194d21f8a67d7de52ba0b2c59c27bc2f | DayGitH/Python-Challenges | /DailyProgrammer/DP20160916C.py | 2,259 | 4.25 | 4 | """
[2016-09-16] Challenge #283 [Hard] Guarding the Coast
https://www.reddit.com/r/dailyprogrammer/comments/5320ey/20160916_challenge_283_hard_guarding_the_coast/
# Description
Imagine you're in charge of the coast guard for your island nation, but you're on a budget. You have to minimize how
many boats, helicopters and crew members to adequately cover the coast. Each group is responsible for a square area of
coastline.
It turns out this has a mathematical relationship to some interesting mathematics. In fractal geometry, the
[Minkowski–Bouligand Dimension](https://en.wikipedia.org/wiki/Minkowski%E2%80%93Bouligand_dimension), or box counting
dimension, is a means of counting the fractal geometry of a set *S* in Euclidian space R^n. Less abstractly, imagine
the set *S* laid out in an evenly space grid. The box counting dimension would be the minimum number of square tiles
required to cover the set.
More realistically, when doing this counting you'll wind up with some partial tiles and have to overlap, and that's OK
- overlapping boxes are fine, gaps in coastal coverage are not. What you want to do is to minimize the number of tiles
overall. It's easy over estimate, it's another to minimize.
# Input Description
You'll be given two things: a tile size N representing the side of the square, and an ASCII art map showing you the
coastline to cover.
Example:
2
*****
* *
* *
* *
*****
# Output Description
Your program should emit the minimum number of tiles of that size needed to cover the boundary.
From the above example:
8
# Challenge Input
4
**
* **
* *
** *
* *
** *
* *
* *
** **
* *
** ***
* *
* *
** *
* **
** *
** *
* **
* **
* ***
** *
* *
** **
* ****
** ******
*********
"""
def main():
pass
if __name__ == "__main__":
main()
| true |
78237d17e529cdd02fe42dd409c705b22e255eb8 | DayGitH/Python-Challenges | /DailyProgrammer/20120403B.py | 1,081 | 4.46875 | 4 | """
Imagine you are given a function flip() that returns a random bit (0 or 1 with equal probability). Write a program that
uses flip to generate a random number in the range 0...N-1 such that each of the N numbers is generated with equal
probability. For instance, if your program is run with N = 6, then it will generate the number 0, 1, 2, 3, 4, or 5 with
equal probability.
N can be any integer >= 2.
Pseudocode is okay.
You're not allowed to use rand or anything that maintains state other than flip.
Thanks to Cosmologicon for posting this challenge to /r/dailyprogrammer_ideas!
"""
import random
import matplotlib.pyplot as plt
from bitarray import bitarray
def flip():
return random.getrandbits(1)
def binary_to_int(n):
out = 0
for bit in n:
out = (out << 1) | bit
return out
def randomize(a):
for n, i in enumerate(a):
a[n] = flip()
return a
number = 200
binary = bin(number)[2:]
a = len(binary) * bitarray('0')
while True:
a = randomize(a)
if binary_to_int(a) <= number:
break
print(binary_to_int(a))
| true |
0b541c06a55954a41a1cf02de616696c28d9abf8 | DayGitH/Python-Challenges | /DailyProgrammer/DP20121023B.py | 1,571 | 4.1875 | 4 | """
[10/23/2012] Challenge #106 [Intermediate] (Jugs)
https://www.reddit.com/r/dailyprogrammer/comments/11xjfd/10232012_challenge_106_intermediate_jugs/
There exists a problem for which you must get exactly 4 gallons of liquid, using only a 3 gallon jug and a 5 gallon
jug. You must fill, empty, and/or transfer liquid from either of the jugs to acquire exactly 4 gallons.
The solution to this particular problem is the following:
- Fill the 5 gallon jug
- Transfer from the 5 gallon jug to the 3 gallon jug, leaving 2 gallons in the 5 gallon jug and 3 gallons in the 3
gallon jug
- Empty the 3 gallon jug
- Transfer from the 5 gallon jug to the 3 gallon jug, leaving 0 gallons in the 5 gallon jug and 2 gallons in the 3
gallon jug
- Fill the 5 gallon jug
- Transfer from the 5 gallon jug to the 3 gallon jug, leaving 4 gallons in the 5 gallon jug and 3 gallons in the 3
gallon jug
- Empty the 3 gallon jug (optional)
The challenge will be to output a set of instructions to achieve an arbitrary final volume given 2 arbitrary sized
gallon jugs. Jugs should be sized in a whole number (integer) amount of gallons. The program must also determine if the
desired volume is impossible with this method (i.e. 2 - 4 gallon jugs to make 3 gallons). The program should be
deterministic, meaning that running with the same inputs always produces the same solution (preventing a random pouring
algorithm). The program should also consider outputting the most optimal set of instructions, but is not necessary.
"""
def main():
pass
if __name__ == "__main__":
main()
| true |
b268c2242ac7769abf8155f8299f3222452c706c | DayGitH/Python-Challenges | /DailyProgrammer/DP20120702A.py | 1,509 | 4.28125 | 4 | """
Before I get to today's problem, I'd just like to give a warm welcome to our two new moderators, nooodl and Steve132! We
decided to appoint two new moderators instead of just one, because rya11111 has decided to a bit of a break for a while.
I'd like to thank everyone who applied to be moderators, there were lots of excellent submissions, we will keep you in
mind for the next time. Both nooodl and Steve132 have contributed some excellent problems and solutions, and I have no
doubt that they will be excellent moderators.
Now, to today's problem! Good luck!
If a right angled triangle has three sides A, B and C (where C is the hypothenuse), the pythagorean theorem tells us
that A**2 + B**2 = C**2
When A, B and C are all integers, we say that they are a pythagorean triple. For instance, (3, 4, 5) is a pythagorean
triple because 3**2 + 4**2 = 5**2 .
When A + B + C is equal to 240, there are four possible pythagorean triples: (15, 112, 113), (40, 96, 104),
(48, 90, 102) and (60, 80, 100).
Write a program that finds all pythagorean triples where A + B + C = 504.
Edit: added example.
"""
def pyth_triples(n):
for a in range(n//2):
for b in range(a+1, n//2):
for c in range(b+1, n//2):
if a+b+c == n and (a**2) + (b**2) == (c**2):
print([a, b, c])
elif a+b+c > n:
break
if a+b > n:
break
def main():
pyth_triples(504)
if __name__ == "__main__":
main()
| true |
08e590ff030b1b2a50b3a0caadd086f4def3630c | DayGitH/Python-Challenges | /DailyProgrammer/20120611B.py | 2,005 | 4.40625 | 4 | """
You can use the reverse(N, A) procedure defined in today's easy problem [20120611A] to completely sort a list. For
instance, if we wanted to sort the list [2,5,4,3,1], you could execute the following series of reversals:
A = [2, 5, 4, 3, 1]
reverse(2, A) (A = [5, 2, 4, 3, 1])
reverse(5, A) (A = [1, 3, 4, 2, 5])
reverse(3, A) (A = [4, 3, 1, 2, 5])
reverse(4, A) (A = [2, 1, 3, 4, 5])
reverse(2, A) (A = [1, 2, 3, 4, 5])
And the list becomes completely sorted, with five calls to reverse(). You may notice that in this example, the list is
being built "from the back", i.e. first 5 is put in the correct place, then 4, then 3 and finally 2 and 1.
Let s(N) be a random number generator defined as follows:
s(0) = 123456789
s(N) = (22695477 * s(N-1) + 12345) mod 1073741824
Let A be the array of the first 10,000 values of this random number generator. The first three values of A are then
123456789, 752880530 and 826085747, and the last three values are 65237510, 921739127 and 926774748
Completely sort A using only the reverse(N, A) function.
"""
def s(n, sp):
if n == 0:
return 123456789
else:
return (22695477 * sp + 12345) % 1073741824
def reverse(n, a):
return a[:n][::-1] + a[n:]
def basic_revsort(a):
copy_a = a[:]
sort_loc = len(a)
count = 0
while copy_a:
num = max(copy_a)
copy_a.remove(num)
i = a.index(num)+1
if i == sort_loc:
pass
elif i == 0:
a = reverse(sort_loc, a)
count += 1
else:
a = reverse(i, a)
a = reverse(sort_loc, a)
count += 2
sort_loc -= 1
print(count)
return a
def main():
generate = 10000
result = -1
out = []
for i in range(generate):
result = s(i, result)
out.append(result)
# out = [2, 5, 4, 3, 1]
out = basic_revsort(out)
print(sorted(out))
print(out)
if __name__ == "__main__":
main()
| true |
8be851749005732519c82b72d3b7796187b59edc | DayGitH/Python-Challenges | /DailyProgrammer/DP20160408C.py | 2,212 | 4.15625 | 4 | """
[2016-04-08] Challenge #261 [Hard] magic square dominoes
https://www.reddit.com/r/dailyprogrammer/comments/4dwk7b/20160408_challenge_261_hard_magic_square_dominoes/
# Description
An NxN magic square is an NxN grid of the numbers 1 through N^2 such that each row, column, and major diagonal adds up
to M = N(N^(2)+1)/2. [See this week's Easy problem for an
example.](https://www.reddit.com/r/dailyprogrammer/comments/4dccix/20160404_challenge_261_easy_verifying_3x3_magic/)
For some even N, you will be given the numbers 1 through N^2 as N^(2)/2 pairs of numbers. You must produce an NxN magic
square using the pairs of numbers like dominoes covering a grid. That is, your output is an NxN magic square such that,
for each pair of numbers in the input, the two numbers in the pair are adjacent, either vertically or horizontally. The
numbers can be swapped so that either one is on the top or left.
For the input provided, there is guaranteed to be at least one magic square that can be formed this way. (In fact there
must be at least eight such magic squares, given reflection and rotation.)
Format the grid and input it into your function however you like.
# Efficiency
An acceptable solution to this problem must be significantly faster than brute force. (This is Hard, after all.) You
don't need to get the optimal solution, but you should run your program to completion on at least one challenge input
before submitting. Post your output for one of the challenge inputs along with your code (unless you're stuck and
asking for help).
Aim to finish one of the three 4x4 challenge inputs within a few minutes (my Python program takes about 11 seconds for
all three). I have no idea how feasible the larger ones are. I started my program on a 6x6 input about 10 hours ago and
it hasn't finished. But I'm guessing someone here will be more clever than me, so I generated inputs up to 16x16.
Good luck!
# Example input
1 9
2 10
3 6
4 14
5 11
7 15
8 16
12 13
# Example output
9 4 14 7
1 12 6 15
16 13 3 2
8 5 11 10
# Challenge inputs
[Challenge inputs](http://pastebin.com/6dkYxvrM)
"""
def main():
pass
if __name__ == "__main__":
main()
| true |
0b0a585867ad3f4081fb6734d314797ad4dfe6e3 | DayGitH/Python-Challenges | /DailyProgrammer/20120310A.py | 363 | 4.1875 | 4 | """
Write a program that will compare two lists, and append any elements in the second list that doesn't exist in the first.
input: ["a","b","c",1,4,], ["a", "x", 34, "4"]
output: ["a", "b", "c",1,4,"x",34, "4"]
"""
inp1 = ["a","b","c",1,4,]
inp2 = ["a", "x", 34, "4"]
final = inp1[:]
for a in inp2:
if a not in final:
final.append(a)
print(final) | true |
cedde37647701d970cc14b091dd084966a18d480 | DayGitH/Python-Challenges | /DailyProgrammer/DP20120808A.py | 1,026 | 4.1875 | 4 | """
[8/8/2012] Challenge #86 [easy] (run-length encoding)
https://www.reddit.com/r/dailyprogrammer/comments/xxbbo/882012_challenge_86_easy_runlength_encoding/
Run-Length encoding is a simple form of compression that detects 'runs' of repeated instances of a symbol in a string
and compresses them to a list of pairs of 'symbol' 'length'. For example, the string
"Heeeeelllllooooo nurse!"
Could be compressed using run-length encoding to the list of pairs
[(1,'H'),(5,'e'),(5,'l'),(5,'o'),(1,'n'),(1,'u'),(1,'r'),(1,'s'),(1,'e')]
Which seems to not be compressed, but if you represent it as an array of 18bytes (each pair is 2 bytes), then we save 5
bytes of space compressing this string.
Write a function that takes in a string and returns a run-length-encoding of that string. (either as a list of pairs
or as a 2-byte-per pair array)
BONUS: Write a decompression function that takes in the RLE representation and returns the original string
"""
def main():
pass
if __name__ == "__main__":
main()
| true |
679d823627f1fc41e7027d234a4ae51b9ba3868d | DayGitH/Python-Challenges | /ProjectEuler/pr0019.py | 1,393 | 4.15625 | 4 | """
You are given the following information, but you may prefer to do some research for yourself.
* 1 Jan 1900 was a Monday.
* Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
* A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
"""
MONTHS = 12
m_dict = {1:31,2:28,3:31,4:30,5:31,6:30,7:31,8:31,9:30,10:31,11:30,12:31}
year = 1900
day = 1
sun_count = 0
# loop through years
while year < 2001:
# loop through months
for m in range(1,MONTHS+1):
# get number of days in month from dictionary
DAYS = m_dict[m]
# make adjustment for leap years
if m == 2:
if year%400 == 0:
DAYS += 1
elif year%100 == 0:
pass
elif year%4 == 0:
DAYS += 1
#loop through days
for n in range(1,DAYS+1):
# count for first sunday of a month
if n == 1 and day == 7 and year > 1900:
sun_count += 1
# day of the week count
day = day + 1 if day < 7 else 1
year += 1
print(sun_count) | true |
dca128ba4183ba191a980e31fbe857280b70450f | DayGitH/Python-Challenges | /DailyProgrammer/20120331A.py | 502 | 4.125 | 4 | """
A very basic challenge:
In this challenge, the
input is are : 3 numbers as arguments
output: the sum of the squares of the two larger numbers.
Your task is to write the indicated challenge.
"""
"""
NOTE: This script requires three input arguments!!!
"""
import sys
arguments = len(sys.argv)
if arguments != 4:
print('Invalid number of arguments:\t{}'.format(arguments - 1))
print('Required number of arguments:\t3')
else:
l = sorted(list(map(int, sys.argv[1:])))
print(sum(l[1:])) | true |
ff0d12abcd0f3b346d1da0bb9b0ac5aa0c25f473 | DayGitH/Python-Challenges | /DailyProgrammer/20120216C.py | 975 | 4.125 | 4 | '''
Write a program that will take coordinates, and tell you the corresponding number in pascals triangle. For example:
Input: 1, 1
output:1
input: 4, 2
output: 3
input: 1, 19
output: error/nonexistent/whatever
the format should be "line number, integer number"
for extra credit, add a function to simply print the triangle, for the extra credit to count, it must print at least
15 lines.
'''
old_list = []
new_list = [1]
print('Line number?')
line_number = int(input('> '))
print('Integer number?')
int_number = int(input('> '))
# print(new_list)
#generates a pascal triangle tier in each loop
for i in range(line_number - 1):
new_list, old_list = [], new_list
new_list.append(1)
if i > 0:
for e in range(0,len(old_list)-1):
new_list.append(old_list[e] + old_list[e + 1])
new_list.append(1)
# print(new_list)
try:
print('The integer is: {}'.format(new_list[int_number - 1]))
except IndexError:
print('Nonexistent!!!') | true |
e468767ef3ec92629303e5c294e393f29ae6ee83 | DayGitH/Python-Challenges | /DailyProgrammer/20120218A.py | 906 | 4.34375 | 4 | '''
The exercise today asks you to validate a telephone number, as if written on an input form. Telephone numbers can be
written as ten digits, or with dashes, spaces, or dots between the three segments, or with the area code parenthesized;
both the area code and any white space between segments are optional.
Thus, all of the following are valid telephone numbers: 1234567890, 123-456-7890, 123.456.7890, (123)456-7890,
(123) 456-7890 (note the white space following the area code), and 456-7890.
The following are not valid telephone numbers: 123-45-6789, 123:4567890, and 123/456-7890.
source: programmingpraxis.com
'''
import re
l = ['1234567890', '123-456-7890', '123.456.7890', '(123)456-7890', '(123) 456-7890', '456-7890', '123-45-6789',
'123:4567890', '123/456-7890']
s = re.compile('(([(]*)([0-9]{3})([)]*)([.-]*)([ ]*))*([0-9]{3})([.-]*)([0-9]{4})')
for a in l:
print(s.match(a)) | true |
f8ce35aa7a18e0b7a6febbd227e0b7a16f2fd832 | DayGitH/Python-Challenges | /DailyProgrammer/DP20120629B.py | 1,232 | 4.25 | 4 | """
Implement the hyperoperator [http://en.wikipedia.org/wiki/Hyperoperation#Definition] as a function hyper(n, a, b), for
non-negative integers n, a, b.
hyper(1, a, b) = a + b, hyper(2, a, b) = a * b, hyper(3, a, b) = a ^ b, etc.
Bonus points for efficient implementations.
thanks to noodl for the challenge at /r/dailyprogrammer_ideas ! .. If you think yo have a challenge worthy for our
sub, do not hesitate to submit it there!
Request: Please take your time in browsing /r/dailyprogrammer_ideas and helping in the correcting and giving suggestions
to the problems given by other users. It will really help us in giving quality challenges!
Thank you!
"""
def hyper(n, a, b, cache):
# expect n >= 0
args = list(map(str, [n, a, b]))
if ','.join(args) in cache:
return cache[','.join(args)]
if not n:
answer = b + 1
elif n == 1:
answer = a + b
elif n == 2:
answer = a * b
elif n == 3:
answer = a ** b
elif not b:
answer = 1
else:
answer = hyper(n-1, a, hyper(n, a, b-1, cache), cache)
cache[','.join(args)] = answer
return answer
def main():
print(hyper(5, 3, 2, {}))
if __name__ == "__main__":
main()
| true |
db322807d137276219ecaab479af539fe4088cb5 | DayGitH/Python-Challenges | /DailyProgrammer/DP20170619A.py | 1,147 | 4.125 | 4 | """
[2017-06-19] Challenge #320 [Easy] Spiral Ascension
https://www.reddit.com/r/dailyprogrammer/comments/6i60lr/20170619_challenge_320_easy_spiral_ascension/
# Description
The user enters a number. Make a spiral that begins with 1 and starts from the top left, going towards the right, and
ends with the square of that number.
# Input description
Let the user enter a number.
# Output description
Note the proper spacing in the below example. You'll need to know the number of digits in the biggest number.
You may go for a CLI version or GUI version.
# Challenge Input
5
4
# Challenge Output
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
# Bonus
As a bonus, the code could take a parameter and make a clockwise or counter-clockwise spiral.
# Credit
This challenge was suggested by /u/MasterAgent47 (with a bonus suggested by /u/JakDrako), many thanks to them both. If
you would like, submit to /r/dailyprogrammer_ideas if you have any challenge ideas!
"""
def main():
pass
if __name__ == "__main__":
main()
| true |
dea6624c859356ed196474cbb7f746f5d5b44dd8 | DayGitH/Python-Challenges | /DailyProgrammer/DP20120808C.py | 1,199 | 4.1875 | 4 | """
[8/8/2012] Challenge #86 [difficult] (2-SAT)
https://www.reddit.com/r/dailyprogrammer/comments/xx970/882012_challenge_86_difficult_2sat/
Boolean Satisfiability problems are problems where we wish to find solutions to boolean equations such as
(x_1 or not x_3) and (x_2 or x_3) and (x_1 or not x_2) = true
These problems are notoriously difficult, and k-SAT where k (the number of variables in an or expression) is 3 or
higher is known to be
NP-complete.
However, [2-SAT](http://en.wikipedia.org/wiki/2-satisfiability) instances (like the problem above) are NOT NP-complete
(if P!=NP), and even have linear time solutions.
You can encode an instance of 2-SAT as a list of pairs of integers by letting the integer represent which variable is
in the expression, with a negative integer representing the negation of that variable. For example, the problem above
could be represented in list of pair of ints form as
[(1,-3),(2,3),(1,-2)]
Write a function that can take in an instance of 2-SAT encoded as a list of pairs of integers and return a boolean for
whether or not there are any true solutions to the formula.
"""
def main():
pass
if __name__ == "__main__":
main()
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.