blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
b8f6125de3b647d2b8c3c6a8fee82d258c6b8731 | minaeid90/pycourse | /advanced/example0.py | 2,923 | 4.53125 | 5 | #-*- coding: utf-8 -*-
u'''
DESCRIPTORS EXAMPLE 0: How attributes look up works
'''
# Let's define a class with 'class' and 'instance' attributes
class MyClass(object):
class_attr = "Value of class attrib"
def __init__(self):
self.instance_attr = "Value of instance of {0} attrib".format(self.__class__.__name__)
def a_method(self):
print "A method was called on", self
# Let's instantiate it and access the attributes
inst = MyClass()
print inst.class_attr
print inst.instance_attr
# Let's access attributes in a different way
print inst.__getattribute__("class_attr") # http://docs.python.org/2/reference/datamodel.html#more-attribute-access-for-new-style-classes
print getattr(inst, "instance_attr")
print getattr(inst, "unknown_attr", "This attribute was not found!!") # http://docs.python.org/2/library/functions.html#getattr
# Let's check the instance and class __dict__
print inst.__dict__
print MyClass.__dict__
#===========================================================================
# _ __dict__ is the object dictionary. All (new style) Python objects have it
# - So there is instance and class __dict__
# - Class attributes are stored in class __dict__
#===========================================================================
# Let's change the attributes values
new_inst = MyClass()
inst.class_attr = 12345
inst.instance_attr = 67890
new_inst.instance_attr = "BBBB"
# Let's check what was changed
print inst.__dict__
print MyClass.__dict__
print new_inst.__dict__
#===========================================================================
# - Instance __dict__ overrides the classes __dict__ (or is looked up in first place)
# - Changed attributes value is stored in the instance __dict__
#===========================================================================
# Let's see how inheritance works
class MyClassInh(MyClass):
pass
inst_inh = MyClassInh()
print inst_inh.class_attr
print inst_inh.instance_attr # Note that now it prints a different message
# Let's check their __dict__
print inst_inh.__dict__
print MyClassInh.__dict__
#===========================================================================
# - Each superclass holds its own __dict__
# - They are looked up in order
#===========================================================================
# Let's try to list all __dict__ elements for an instance
lst = MyClass.__dict__.keys()
lst.extend(MyClassInh.__dict__.keys())
lst.extend(inst_inh.__dict__.keys())
print sorted(list(set(lst)))
# Trick: http://docs.python.org/2/library/functions.html#dir
print dir(inst_inh)
# Let's manually add a new instance attribute
inst_inh.__dict__['new_instance_attr'] = "New value of instance of MyClassInh attrib"
print inst_inh.new_instance_attr
print inst_inh.__dict__
# Let's try to go a bit further
try:
MyClassInh.__dict__['new_class_attr'] = 9
except TypeError, e:
print e
| true |
6692a0b469278f6c6d13eabadab36a6e426b2936 | hydrophyl/Python-1.0 | /TricksnTips/loop2.py | 333 | 4.21875 | 4 | names = ['Cory','Chris', 'Dave', 'Trad']
heroes = ['Peru','Christie', 'David', 'Tradition']
""" for index, name in enumerate(names):
hero = heroes[index]
print(f"{name} is actually {hero}") """
for name, hero in zip(names,heroes):
print(f'{name} is actually {hero}')
for value in zip(names, heroes):
print(value) | false |
e4598a7212964d5dc6440bb57d16342e46b1fd95 | usfrank02/pythonProjects | /project3.py | 288 | 4.34375 | 4 | #! python
import sys
name = input("Enter your name:")
print (name)
#Request user to input the year he was born
year_of_born = int(input("What's the year you were born?"))
#Calculate the age of the user
age = 2020 - year_of_born
print("You will be {} years old this year!".format(age))
| true |
2e046c0d4fc1e243a8ae9e85b56d10f9195e473b | Regato/exersise12 | /Romanov_Yehor_Exercise14.py | 582 | 4.15625 | 4 | # Entering input and making from string all UPPER case:
input_string = input('[!] INPUT: Please enter your value (only string type): ')
upper_string = input_string.upper()
# Function that count letters in string:
def letter_counter(x):
return upper_string.count(x)
# For cycle that check every letter for duplicates by the previous function:
for i in upper_string:
if (letter_counter(i) > 1):
output_value = True
break
else:
output_value = False
# Printing output (the result of program):
print('[/] OUTPUT: Your result is: ', output_value)
| true |
38582bca142960e852de0445e04d76afb018a1fb | Jattwood90/DataStructures-Algorithms | /1. Arrays/4.continuous_sum.py | 435 | 4.25 | 4 | # find the largest continuous sum in an array. If all numbers are positive, then simply return the sum.
def largest_sum(arr):
if len(arr) == 0:
return 0
max_sum = current = arr[0] # sets two variables as the first element of the list
for num in arr[1:]:
current = max(current+num, num)
max_sum = max(max_sum, current)
return max_sum
print(largest_sum([1,3,-1,5,6,-10])) # 14
| true |
9b9b07556cc95ec055af0e3ae93af5d7ace7a120 | jvillamarino/python | /Platforms_courses/Platzi/factorial.py | 339 | 4.3125 | 4 |
def calculate_factorial(number):
if number == 1:
return 1;
return number * calculate_factorial(number-1)
if __name__ == '__main__':
number = int(input("Escribe un número a multiplicar: "))
result = calculate_factorial(number)
print(f'El resultado del factorial para el número {number} es: {result}') | false |
088a600b0d851da9345a6ef2e336bdf32c9dddb8 | rhaydengh/IS211_Assignment1 | /assignment1_part2.py | 614 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Assignment 1, Part 2"""
class Book:
"""Class for books"""
def __init__(self, author, title):
"""this function returns a book by author and title based on variables"""
self.author = author
self.title = title
def display(self):
"""This function provides instructions on printing format and displays 2 books"""
print(self.title, 'written by', self.author)
Book1 = Book('John Steinbeck', 'Of Mice and Men')
Book2 = Book('Harper Lee', 'To Kill a Mockingbird')
print(Book1.display(),Book2.display())
| true |
0197bce6a32e97761dce10deb57290cb666b78a7 | y1212/myslite | /tuple.py | 979 | 4.28125 | 4 | # tuple1=(1,2,3,"hello tom",False)
# print(tuple1,type(tuple1))
# list1=[1,2,3,4]
# print(list1,type(list1))
# #列表转换
# tuple2=tuple(list1)
# print(tuple2,type(tuple2))
# #对元组的遍历索引号
# for i in range(len(tuple1)):
# print(tuple1[i])
# #元组遍历
# for element in tuple1:
# print(element)
# print(len(tuple1))
# print(tuple1[1:3])
# print(str[1:4])
# tuple3=(1,1,1,2,33,4,4,4,2)
# print(tuple3)
# #找到所传的索引号
# index =tuple3.index(2)
# print(index)
# #统计数量
# number=tuple3.count(1)
# print(number)
# tuple4=(7,9)
# tuple5=(8,10)
# tuple6=tuple4+tuple5
# print(tuple6)
# print(tuple6 * 4)
# list = [23,12,15,11,29,24,57,21,80,99,45]
# for m in range(len(list)-1):
# for n in range(m+1, len(list)):
# if list[m]> list[n]:
# temp = list[n]
# list[n] = list[m]
# list[m] = temp
# print(list)
# list=["this is my house"]
# list.reverse()
# for i in (10,-1,-1):
# print(i) | false |
6e29c29f32d27aa1e76cc0a3ead78b2b3cca6515 | sachlinux/python | /exercise/strings/s3.py | 369 | 4.15625 | 4 | #embedding value in string
value = "500"
message = "i hav %s rupees"
print(message % value)
#we can do without variable also
print(message % 1000)
#more example
var1 = "sachin"
var2 = "dentist"
message1 = "%s: is in love with %s"
message2 = "%s is so %s"
print(message1 % (var1,var2))
print(message2 % ('she','pretty'))
#multiplying string
print(5 * var1)
| true |
658ec398f352a09390fd9534cb448e2a91bffc9c | debakshmi-hub/Hacktoberfest2021-2 | /checkPrime.py | 756 | 4.21875 | 4 | # //your code here
# Program to check if a number is prime or not
num = int(input("Enter a Number "))
flag = False
if num > 1:
for i in range(2, num):
if (num % i) == 0:
flag = True
break
if flag:
print(num, "is not a prime number")
else:
print(num, "is a prime number")
# Program to check if a number is prime or not
num = 407
# To take input from the user
#num = int(input("Enter a number: "))
if num > 1:
# check for factors
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
print(i,"times",num//i,"is",num)
break
else:
print(num,"is a prime number")
else:
print(num,"is not a prime number")
| true |
fb54c0d63382752c3c9a3feb327321a2c77492cc | gautamk/ProjectEuler | /problem1.py | 528 | 4.25 | 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.
MAX = 1000
def mul_of(multiple_of, max=MAX):
multiplier = 1
multiple = multiple_of * multiplier
while multiple < MAX:
yield multiple
multiple = multiple_of * multiplier
multiplier += 1
multiples_of_3_or_5 = set(mul_of(3)).union(mul_of(5))
print multiples_of_3_or_5
print sum(multiples_of_3_or_5)
| true |
250aaa13de0944d78fc6f7a6083c5413ea1961e5 | KhallilB/Tweet-Generator | /Code/practice_code/sampling.py | 1,731 | 4.125 | 4 | import random
import sys
import histograms
def random_word(histogram):
'''Generates a random word without using weights'''
random_word = ''
random_index = random.randrange(len(histogram))
random_word += histogram[random_index][0]
return random_word
def weighted_random_word(histogram):
'''Generates random words based on how often they appear'''
random_word = ''
weights = 0
for items in histogram:
weights += items[1]
random_weight = random.randrange(weights)
index = 0
while random_weight >= 0:
random_word = histogram[index][0]
random_weight -= histogram[index][1]
index += 1
return random_word
def test_probability(histogram):
'''
Tests the probability of word ocurrances in
the histogram that gets passed through
'''
words = ''
for i in range(10000):
words += ' ' + weighted_random_word(histogram=histogram)
test_histogram = histograms.histogram_counts(words)
sample_amount = 25
index = len(test_histogram) - 1
while sample_amount > 0 and index >= 0:
for entry in test_histogram[index][1]:
if sample_amount > 0:
printline = entry + ' = '
printline += str(test_histogram[index][0])
print(printline)
sample_amount -= 1
index -= 1
if __name__ == '__main__':
path = sys.argv[1]
with open(path, 'r') as file:
source_text = file.read()
source_histogram = histograms.histogram_tuples(source=source_text)
word = weighted_random_word(histogram=source_histogram)
print(word)
print('^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^')
test_probability(source_histogram)
| true |
79ec249c78604d85bf5612da0d597d41c39214e3 | qcl643062/leetcode | /110-Balanced-Binary-Tree.py | 1,730 | 4.15625 | 4 | #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.
"""
class TreeNode(object):
def __init__(self, x, left = None, right = None):
self.val = x
self.left = left
self.right = right
class Solution(object):
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
#统计节点深度
def numofnode(root):
if root == None:
return 0
def priorder(root):
if not root:
return 0
return 1 + max(priorder(root.left), priorder(root.right))
return priorder(root)
#判断一个节点是否符合
def nodetrue(root):
if not root:
return True
numofleft = numofnode(root.left)
numofright = numofnode(root.right)
if abs(numofright - numofleft) <= 1:
return True
else:
return False
#对每个节点进行判断
result = nodetrue(root)
if result == False:
return False
boo1 = True
boo2 = True
if root:
if root.left:
boo1 = self.isBalanced(root.left)
if boo1 == False:
return False
if root.right:
boo2 = self.isBalanced(root.right)
if boo2 == False:
return False
return True
s = Solution()
print s.isBalanced(TreeNode(0, TreeNode(1, TreeNode(2))))
| true |
1f1529473302b02d543365662b5ea486c153d200 | EngrDevDom/Everyday-Coding-in-Python | /ToLeftandRight.py | 422 | 4.125 | 4 | # ToLeftandRight.py
nums = []
num_of_space = 0
current_num = int(input("Enter a number: "))
nums.append(current_num)
while True:
num = int(input("Enter a number: "))
if num > current_num: num_of_space += 1
elif num == current_num: continue
else: num_of_space -= 1
current_num = num
nums.append(" " * num_of_space + str(num))
if num_of_space == 0: break
for num in nums: print(num)
| false |
a2f10d28828b2fe43054860554e2915bbe1a3e13 | EngrDevDom/Everyday-Coding-in-Python | /Distance.py | 379 | 4.25 | 4 | # File : Distance.py
# Desc : This program accepts two points and determines the distance between them.
import math
def main():
x1, y1 = eval(input("Enter first coordinate.(x1, y1): "))
x2, y2 = eval(input("Enter second coordinate.(x2, y2): "))
distance = math.sqrt((x2-x1)**2 + (y2-y1)**2)
print("The distance between two points is:", distance)
main() | true |
38af1cc91d8307cf8d0adfb77e19b558ad5b6bb5 | EngrDevDom/Everyday-Coding-in-Python | /SciPy/polynomials.py | 830 | 4.25 | 4 | from numpy import poly1d
# We'll use some functions from numpy remember!!
# Creating a simple polynomial object using coefficients
somePolynomial = poly1d([1,2,3])
# Printing the result
# Notice how easy it is to read the polynomial this way
print(somePolynomial)
# Let's perform some manipulations
print("\nSquaring the polynomial: \n")
print(somePolynomial*somePolynomial)
# How about integration, we just have to call a function
# We just have to pass a constant say 3
print("\nIntegrating the polynomial: \n")
print(somePolynomial.integ(k=3))
# We can also find derivatives in similar way
print("\nFinding derivative of the polynomial: \n")
print(somePolynomial.deriv())
# We can also solve the polynomial for some value,
# let's try to solve it for 2
print("\nSolving the polynomial for 2: \n")
print(somePolynomial(2)) | true |
d43dcc1e99425696cdaeff16dc969344a3205a95 | EngrDevDom/Everyday-Coding-in-Python | /Identify_triangle.py | 496 | 4.4375 | 4 | # This program identifies what type of triangle it is
# based on the measure of it's angle
angle = int(input("Give an angle in degrees: "))
type = ""
if angle > 0 and angle < 90:
type = "ACUTE"
elif angle == 90:
type = "RIGHT"
elif angle > 90 and angle < 180:
type = "OBTUSE"
elif angle == 180:
type = "STRAIGHT"
elif angle > 180 and angle < 360:
type = "REFLEX"
elif angle == 360:
type = "COMPLETE"
else:
type = "UNIDENTIFIED"
print("The triangle is a/an: ", type) | true |
96ff1baf71e2a5f8e24a0985a95a4cf52e2d14b4 | EngrDevDom/Everyday-Coding-in-Python | /Ladder.py | 447 | 4.46875 | 4 | # File : Ladder.py
# Desc : This program determine the length of the ladder required to
# reach a given height leaned.
import math
def main():
angle = float(input("Enter the value of angle in degrees: "))
radians = math.radians(angle) # Convert degrees to radians
height = float(input("Enter the value of height: "))
length = height/math.sin(angle)
print("The length of the ladder is", length)
main()
| true |
0cea260a3dcf1852cbd66920e3aa23e94e7d26b7 | EngrDevDom/Everyday-Coding-in-Python | /quadratic_5.py | 702 | 4.1875 | 4 | # File : quadratic_5.py
# Desc : A program that computes the real roots of a quadratic equation. Version 5.0
# Note: This program catches the exception if the equation has no real roots.
import math
def main():
print("This program finds the real solutions to a quadratic\n")
try:
a = float(input("Enter coefficient a: "))
b = float(input("Enter coefficient b: "))
c = float(input("Enter coefficient c: "))
discRoot = math.sqrt(b**2 - 4*a*c)
root1 = (-b + discRoot) / (2*a)
root2 = (-b - discRoot) / (2*a)
print("\nThe solutions are:", root1, root2)
except ValueError:
print("\nNo real roots.")
main()
| true |
de25351bfb982437ac08ebd4d1c7ba94ffd86490 | EngrDevDom/Everyday-Coding-in-Python | /quizzes_2.py | 549 | 4.1875 | 4 | # File : quizzes_2.py
# Desc : A program that accepts a quiz score as an input and uses a decision
# structure to calculate the corresponding grade.
def main():
grade = int(input("Enter your grade: "))
scale = ''
if grade <= 100 or grade >= 90: scale = 'A'
elif grade <= 89 or grade > 80: scale = 'B'
elif grade <= 79 or grade > 70: scale = 'C'
elif grade <= 69 or grade > 60: scale = 'D'
elif grade <= 60: scale = 'F'
print("Your scale is", scale, "\nDone!")
main()
| true |
f05e35fdc63cfcb45bb19620d0478dfc7b91ab8c | EngrDevDom/Everyday-Coding-in-Python | /Eq_of_Motion.py | 261 | 4.28125 | 4 | # Program for computing the height of a ball in vertical motion
v0 = 5 # Initial velocity (m/s)
g = 9.81 # Acceleration of gravity (m/s^2)
t = 0.6 # Time (s)
y = v0*t - 0.5*g*t**2 # Vertical position
print("Height of the ball: ", y, " m")
| true |
0db588fb91a034b200427bc709206e201947fc9f | EngrDevDom/Everyday-Coding-in-Python | /Algorithms/Sorting Algorithms/Tim_sort.py | 2,652 | 4.28125 | 4 | # Tim_sort Algorithm
from random import randint
from timeit import repeat
def timsort(array):
min_run = 32
n = len(array)
# Start by slicing and sorting small portions of the
# input array. The size of these slices is defined by
# your `min_run` size.
for i in range(0, n, min_run):
insertion_sort(array, i, min((i + min_run - 1), n - 1))
# Now you can start merging the sorted slices.
# Start from `min_run`, doubling the size on
# each iteration until you surpass the length of
# the array.
size = min_run
while size < n:
# Determine the arrays that will
# be merged together
for start in range(0, n, size * 2):
# Compute the `midpoint` (where the first array ends
# and the second starts) and the `endpoint` (where
# the second array ends)
midpoint = start + size - 1
end = min((start + size * 2 - 1), (n-1))
# Merge the two subarrays.
# The `left` array should go from `start` to
# `midpoint + 1`, while the `right` array should
# go from `midpoint + 1` to `end + 1`.
merged_array = merge(
left=array[start:midpoint + 1],
right=array[midpoint + 1:end + 1])
# Finally, put the merged array back into
# your array
array[start:start + len(merged_array)] = merged_array
# Each iteration should double the size of your arrays
size *= 2
return array
# This is the timing algorithm
def run_sorting_algorithm(algorithm, array):
# Set up the context and prepare the call to the specified
# algorithm using the supplied array. Only import the
# algorithm function if it's not the built-in `sorted()`.
setup_code = f"from __main__ import {algorithm}" \
if algorithm != "sorted" else ""
stmt = f"{algorithm}({array})"
# Execute the code ten different times and return the time
# in seconds that each execution took
times = repeat(setup=setup_code, stmt=stmt, repeat=3, number=10)
# Finally, display the name of the algorithm and the
# minimum time it took to run
print(f"Algorithm: {algorithm}. Minimum execution time: {min(times)}")
ARRAY_LENGTH = 0
if __name__ == "__main__":
# Generate an array of `ARRAY_LENGTH` items consisting
# of random integer values between 0 and 999
array = [randint(0, 1000) for i in range(ARRAY_LENGTH)]
# Call the function using the name of the sorting algorithm
# and the array we just created
run_sorting_algorithm(algorithm="timsort", array=array) | true |
4fc7f95567c554cd669dc0ef802228a9ed290040 | EngrDevDom/Everyday-Coding-in-Python | /Algorithms/Sorting_from_StackAbuse/Python_sort.py | 584 | 4.28125 | 4 | # Python Built-in Sort Functions
# Sort
apples_eaten_a_day = [2, 1, 1, 3, 1, 2, 2]
apples_eaten_a_day.sort()
print(apples_eaten_a_day) # [1, 1, 1, 2, 2, 2, 3]
# Sorted
apples_eaten_a_day_2 = [2, 1, 1, 3, 1, 2, 2]
sorted_apples = sorted(apples_eaten_a_day_2)
print(sorted_apples) # [1, 1, 1, 2, 2, 2, 3]
# Reverse
# Reverse sort the list in-place
apples_eaten_a_day.sort(reverse=True)
print(apples_eaten_a_day) # [3, 2, 2, 2, 1, 1, 1]
# Reverse sort to get a new list
sorted_apples_desc = sorted(apples_eaten_a_day_2, reverse=True)
print(sorted_apples_desc) # [3, 2, 2, 2, 1, 1, 1] | false |
88f6afcf9589102e21cd694e2ce4f9104d61b08e | EngrDevDom/Everyday-Coding-in-Python | /Resistor_Color_Coding.py | 508 | 4.21875 | 4 | '''
Resistor Color Coding
- This program calculates the value of a resistor based on the colors
entered by the user.
'''
# Initialize the values
black = 0
brown = 1
red = 2
orange = 3
yellow = 4
green = 5
blue = 6
violet = 7
grey = 8
white = 9
gold = 0
silver = 0
bands = input('Enter the color bands: ')
code = bands.split(" ")
print('1st Band\t', '2nd Band\t', 'Multiplier\t', 'Tolerance\t', 'Reliability')
print(code[0], '\t\t', code[1], '\t\t', code[2], '\t\t', code[3], '\t\t', code[4])
| true |
7d5ad562c1fd4fd490af54eeca2429e41b04e95c | sreedhr92/Computer-Science-Laboratory | /Design And Analysis of Algorithms/power_iterative.py | 251 | 4.28125 | 4 | def power_iterative(x,n):
result =1
for i in range(0,n):
result = x*result
return result
x = int(input("Enter the base:"))
y = int(input("Enter the exponent:"))
print("The value of",x,"to the power of",y,"=",power_iterative(x,y)) | true |
910d9d682ef9a8c258b3395b0226a5a4c2039b43 | UzairIshfaq1234/python_programming_PF_OOP_GUI | /list using if statment.py | 551 | 4.15625 | 4 |
print("________________________________________")
list1=[input("enter name 1: "),int(input("Enter any number: ")),input("enter name 2: "),int(input("Enter any number: "))]
print("________________________________________")
for item in list1:
if str(item).isalpha():
print(item)
print("________________________________________")
for item in list1:
if str(item).isnumeric() and item<10:
print(item)
print("________________________________________")
for item in list1:
if str(item).endswith("ais") :
print(item) | false |
15544b46b10a29d6f235de86dbf6a1af00bae4bd | UzairIshfaq1234/python_programming_PF_OOP_GUI | /07_color_mixer.py | 891 | 4.46875 | 4 | colour1 = input("Enter the first primary colour: ")
colour2 = input("Enter the second primary colour: ")
mixed_colour = ""
if (colour1 == "red" or colour1 == "blue" or colour1 == "yellow") and (colour2 == "red" or colour2 == "blue" or colour2 == "yellow"):
if (colour1 == "red" and colour2 == "blue") or (colour2 == "red" and colour1 == "blue"):
mixed_colour = "purple"
elif (colour1 == "red" and colour2 == "yellow") or (colour2 == "red" and colour1 == "yellow"):
mixed_colour = "orange"
elif (colour1 == "blue" and colour2 == "yellow") or (colour2 == "blue" and colour1 == "yellow"):
mixed_colour = "green"
else:
print("-----------")
print("Invalid mixing of colours!")
if mixed_colour:
print("-----------")
print("Your mixed color is:", mixed_colour)
else:
print("Your colour is not a primary colour!")
| true |
f8d641ea4352a27b00c1d30c84545fd5e5c7744c | nirakarmohanty/Python | /controlflow/IfExample.py | 248 | 4.375 | 4 | print('If Example , We will do multiple if else condition')
value =int(input('Enter one integer value: '))
print('You entered the value as : ',value)
if value>0:
print('value is an integer')
else:
print('Please enter one integer number')
| true |
9a107acee38a1fc5a4632d6ed1c20b5b81408161 | nirakarmohanty/Python | /datatype/ListExample.py | 513 | 4.46875 | 4 | #Define simple List and print them
nameList=['Stela','Dia','Kiara','Anna']
print(nameList)
#List indexing
print(nameList[1],nameList[2],nameList[3])
print(nameList[-1],nameList[-2])
#length of List
print(len(nameList))
#Add a new list to the original list
nameList= nameList + ['Budapest','Croatia','Prague']
print(nameList)
print("Length of the List =", len(nameList))
# Slicing of list
print("print upto 3",nameList[:3])
#Assign values to list
nameList[3]='XXXX'
print("Assign at 3rd position ",nameList)
| true |
b9ec0f8c814393ce080abe964c5c59f417dfc897 | dspwithaheart/blinkDetector | /modules/read_csv.py | 2,833 | 4.1875 | 4 | '''
csv module for reading csv file to the 2D list
Default mode is 'rb'
Default delimiter is ',' and the quotechar '|'
# # #
arguments:
csv_file - read csv file name
coma - if True replaces all the comas with dots (in all cells)
header - specify how many lines (from the begining) are removed
to_float - if set all
transpose - if True transposes the data
transposition - switch columns with rows
e.g.
list =
[1, 2, 3
4, 5, 6
7, 8, 9]
list.T:
[1, 4, 7
2, 5, 8
3, 6, 8]
# # #
example use:
import read_csv
some_list = read_csv.read(example.csv)
other_list = read_csv.read(example.csv, header=5)
'''
import csv
import numpy as np
def read(
csv_file,
comas=True,
delimiter=',',
header=None,
mode='rb',
to_float=True,
transpose=True,
quotechar='|'
):
data = []
print('init')
if len(delimiter) > 1:
data = advanced(
csv_file,
comas=comas,
data=data,
delimiter=delimiter,
mode=mode)
else:
data = basic(
csv_file=csv_file,
comas=comas,
data=data,
delimiter=delimiter,
mode=mode,
quotechar=quotechar
)
if header is not None:
data = data[header:]
if transpose or to_float:
data = np.array(data)
if transpose:
data = data.T
if to_float:
data = data.astype(np.float)
data = data.tolist()
return data
def basic(
csv_file,
data,
comas=False,
delimiter=',',
mode='rb',
quotechar='|'
):
with open(csv_file, mode) as csv_file:
csv_reader = csv.reader(
csv_file,
delimiter=delimiter,
quotechar=quotechar
)
for row_list in csv_reader:
if comas:
# change comas to dots
row_list = [i.replace(',', '.') for i in row_list]
data.append(row_list)
return data
def advanced(
csv_file,
data,
delimiter=', ',
comas=True,
mode='rb'
):
with open(csv_file, mode) as f:
for line in f:
# remove new line character
line = line.rstrip('\n')
# split to cells accordingly to the double delimiter
line = line.split(delimiter)
if comas:
# change comas to dots
line = [i.replace(',', '.') for i in line]
data.append(line)
return data
| true |
8ad9166fa06a4959d3f4ed1001eebb28ca0a59a8 | fullVinsent/lab_Pyton_1 | /1_level.py | 447 | 4.125 | 4 | import math
frustrumHeight = float(input("Input H:"))
smallRadius =float(input("Input r:"))
bigRadius = float(input("Input R:"))
frustrumLenght = math.sqrt(math.pow(frustrumHeight,2) + (math.pow(bigRadius - smallRadius,2)))
frustrumSideArea = math.pi * frustrumLenght * (bigRadius + smallRadius)
frustrumAllAreaSum = frustrumSideArea + (math.pi * math.pow(smallRadius,2)) + (math.pi * math.pow(bigRadius,2))
print(round(frustrumAllAreaSum,3)) | false |
1c43a8a8cccb45600465dc2389894102763ad40b | a-bl/counting | /task_1.py | 243 | 4.15625 | 4 | # What is FOR loop?
sum = 0
while True:
n = int(input('Enter N:'))
if n > 0:
for num in range(1, n + 1):
sum += num
print(sum)
break
else:
print('Enter positive integer!')
| true |
53490c2c6e9feba29d73cb1024895eda79298a2e | rollbackzero/projects | /ex30.py | 458 | 4.1875 | 4 | people = 40
cars = 30
trucks = 45
if cars > people:
print("We should take cars")
elif cars < people:
print("We should not take cars")
else:
print("We can't decide")
if trucks > cars:
print("Thats too many trucks")
elif trucks < cars:
print("Maybe we could take the trucks")
else:
print("We still cant decide")
if people > trucks:
print("Alright, lets just take the trucks")
else:
print("Fine, lets stay home then")
| true |
009d63fffab9020cf7c8ebc4b9deec98b0f656a9 | UVvirus/frequency-analysis | /frequency analysis.py | 1,099 | 4.4375 | 4 | from collections import Counter
non_letters=["1","2","3","4","5","6","7","8","9","0",":",";"," ","/n",".",","]
key_phrase_1=input("Enter the phrase:").lower()
#Removing non letters from phrase
for non_letters in non_letters:
key_phrase_1=key_phrase_1.replace(non_letters,'')
total_occurences=len(key_phrase_1)
#Counter object
"""""A Counter is a collection where elements are stored as dictionary keys and their
counts are stored as dictionary values. Counts are allowed to be any integer
value including zero or negative counts.
"""
letter_count=Counter(key_phrase_1)
print("frequency analysisfrom the phrase:")
for key,value in sorted(letter_count.items()):
percentage=100 * value/total_occurences
percentage=round(percentage,2)
print("\t \t"+key+"\t\t"+str(value)+"\t\t"+str(percentage))
ordered_letter_count=letter_count.most_common()
key_phrase_1_ordered_letters=[]
for pair in ordered_letter_count:
key_phrase_1_ordered_letters.append(pair[0])
print("letters from high occurence to lower occurence:")
for letter in key_phrase_1_ordered_letters:
print(letter, end='') | true |
5845f21ac973ca16b7109f843771c0490633c8fc | guilhermemaas/guanabara-pythonworlds | /exercicios/ex022.py | 1,124 | 4.34375 | 4 | """
Crie um programa que leia o nome completo de uma pessoa e mostre:
O nome com todas as letras maiusculas
O nome com todas as letras minusculas
Quantas letras ao todo sem considerar espacos
Quantas letras tem o primeiro nome
"""
nome_completo = input('Digite seu nome completo: ').strip() #Pra pegar ja sem espacos no comeco e no fim
maiusculas = nome_completo.upper()
minusculas = nome_completo.lower()
letras_sem_espacos = len(nome_completo.replace(' ', ''))
letras_sem_espacos2 = len(nome_completo) - nome_completo.count(' ')
nome_em_lista = nome_completo.split()
tamanho_primeiro_nome = len(nome_em_lista[0])
tamanho_primeiro_nome2 = nome_completo.find(' ') #O find encontra a posicao do primeiro espaco, logo mostra o tamanho do primeiro nome antes deste.
print("""
Seu nome em minusculuas: {}.
Seu nome em maiusculas: {}.
Seu nome possui {} letras sem considerar espacos.
Seu nome possui {} letras sem considerar espacos.
Seu primeiro nome tem {} letras.
Seu primeiro nome tem {} letras.
""".format(maiusculas, minusculas, letras_sem_espacos, letras_sem_espacos2, tamanho_primeiro_nome, tamanho_primeiro_nome2))
| false |
ffff8f3b99def5e98b3bf54fb24a5e1b63a08b03 | guilhermemaas/guanabara-pythonworlds | /exercicios/ex018.py | 1,075 | 4.125 | 4 | """
Faca um programa que leia um angulo qualquer e mostre na tela o valor de seno, cosseno, e tangente desse angulo.
"""
import math
cateto_oposto = float(input('Informe o comprimento do cateto oposto: '))
cateto_adjacente = float(input('Informe o comprimento do cateto adjacente: '))
hipotenusa = math.hypot(cateto_oposto, cateto_adjacente)
seno = cateto_oposto / hipotenusa
cosseno = cateto_adjacente / hipotenusa
tangente = cateto_oposto / cateto_adjacente
print('O valor do cateto oposto e {}.\nO valor do cateto adjacente e {}.\nO valor da hipotenusa e {}.'.format(cateto_oposto, cateto_adjacente, hipotenusa))
print('O valor do seno e {}.\nO valor do cosseno e {}.\nO valor da tangente e {}.'.format(seno, cosseno, tangente))
angulo = float(input('Informe um angulo para calcuar seu seno, cosseno, tangente'))
seno = math.asin(math.radians(angulo))
cosseno = math.acos(math.radians(angulo))
tangente = math.atan(math.radians(angulo))
print('Angulo informado: {}.\nO seno e {:.2f}. O cosseno e {:.2f}. E a tangente e{:.2f}.'.format(angulo, seno, cosseno, tangente)) | false |
c44172d241d35968253acb2fbe2fef16bc779331 | guilhermemaas/guanabara-pythonworlds | /exercicios/ex063.py | 603 | 4.3125 | 4 | """
Escreva um programa que leia um numero n inteiro qualquer e mostre na tela
os n primeiros elementos de uma sequencia de Fibonacci.
Ex.: 0 -> 1 -> 1 -> 2 -> 3 -> 5 -> 8
"""
print('-'*30)
print('Sequencia de Fibonacci')
print('-'*30)
"""
n = int(input('Informe um numero inteiro inicial: '))
"""
qt = int(input('Informe a quantidade de termos da sequencia de Fibonacci deseja visualizar: '))
t1 = 0
t2 = 1
print('~'*30)
cont = 3
print(' {} -> {}'.format(t1, t2), end='')
while cont <= qt:
t3 = t1 + t2
print(' -> {}'.format(t3), end='')
t1 = t2
t2 = t3
cont += 1
print(' -> FIM')
| false |
5445d08db0f152cba9a08f2f6d176a071d61c080 | habbyt/python_collections | /challenge_1.py | 292 | 4.15625 | 4 | #Challenge #1
#function takes a single string parameter and
#return a list of all the indexes in the string that have capital letters.
def capital_indexes(word):
word="HeLlO"
x=[]
for i in range(len(word)):
if word[i].isupper()==True:
x.append(i)
return x
| true |
cd2ae708b13c6359cbbcefa0b957fa58d304f722 | okazkayasi/03_CodeWars | /14_write_in_expanded_form.py | 682 | 4.375 | 4 | # Write Number in Expanded Form
#
# You will be given a number and you will need to return it as a string in Expanded Form. For example:
#
# expanded_form(12) # Should return '10 + 2'
# expanded_form(42) # Should return '40 + 2'
# expanded_form(70304) # Should return '70000 + 300 + 4'
#
# NOTE: All numbers will be whole numbers greater than 0.
#
# If you liked this kata, check out part 2!!
def expanded_form(num):
aList = []
digs = len(str(num))
div = 10 ** (digs-1)
for i in range(digs):
x = (num / div) * div
div /= 10
num -= x
if x > 0:
aList.append(str(x))
return " + ".join(aList)
print expanded_form(70304)
| true |
4f7cbb96396df971f262b7faecee06a8be3a23a9 | okazkayasi/03_CodeWars | /24_car_park_escape_5kyu.py | 2,297 | 4.15625 | 4 | # Your task is to escape from the carpark using only the staircases provided to reach the exit. You may not jump over the edge of the levels (youre not Superman) and the exit is always on the far right of the ground floor.
# 1. You are passed the carpark data as an argument into the function.
# 2. Free carparking spaces are represented by a 0
# 3. Staircases are represented by a 1
# 4. Your parking place (start position) is represented by a 2
# 5. The exit is always the far right element of the ground floor.
# 6. You must use the staircases to go down a level.
# 7. You will never start on a staircase.
# 8. The start level may be any level of the car park.
# Returns
# Return an array of the quickest route out of the carpark
# R1 = Move Right one parking space.
# L1 = Move Left one parking space.
# D1 = Move Down one level.
# Example
# Initialise
#
# carpark = [[1, 0, 0, 0, 2],
# [0, 0, 0, 0, 0]]
#
# Working Out
#
# You start in the most far right position on level 1
# You have to move Left 4 places to reach the staircase => "L4"
# You then go down one flight of stairs => "D1"
# To escape you have to move Right 4 places => "R4"
#
# Result
#
# result = ["L4", "D1", "R4"]
#
# Good luck and enjoy!
def escape(carpark):
# in case we didnt park the car on top
for k in range(len(carpark)):
if 2 in carpark[k]:
carpark = carpark[k:]
pos = [0, carpark[0].index(2)]
ret = []
for i in range(len(carpark)-1):
# check where the stair is
stair = carpark[i].index(1)
# go to the stair and go down
if stair < pos[1]:
ret.append("L" + str(pos[1]-stair))
ret.append("D1")
elif stair > pos[1]:
ret.append("R" + str(stair-pos[1]))
ret.append("D1")
# if two stair is same column
else:
num = int(ret.pop()[1])+1
ret.append("D" + str(num))
pos = [pos[0]+1, stair]
# go to the rightmost place
stair = len(carpark[0])-1
if stair > pos[1]:
ret.append("R" + str(stair-pos[1]))
return ret
carpark = [[1, 0, 0, 0, 2],
[0, 0, 0, 0, 1],
[0, 0, 0, 0, 1],
[1, 0, 0, 0, 0],
[0, 0, 0, 0, 0]]
print escape(carpark)
| true |
8b79cb22ebf59ff6dd2b8f1efbe840c8d519beb3 | okazkayasi/03_CodeWars | /06_title_case.py | 1,651 | 4.375 | 4 | # A string is considered to be in title case if each word in the string is either (a) capitalised (that is, only the first letter of the word is in upper case) or (b) considered to be an exception and put entirely into lower case unless it is the first word, which is always capitalised.
#
# Write a function that will convert a string into title case, given an optional list of exceptions (minor words). The list of minor words will be given as a string with each word separated by a space. Your function should ignore the case of the minor words string -- it should behave in the same way even if the case of the minor word string is changed.
#
# ###Arguments (Haskell)
#
# First argument: space-delimited list of minor words that must always be lowercase except for the first word in the string.
# Second argument: the original string to be converted.
#
# ###Arguments (Other languages)
#
# First argument (required): the original string to be converted.
# Second argument (optional): space-delimited list of minor words that must always be lowercase except for the first word in the string. The JavaScript/CoffeeScript tests will pass undefined when this argument is unused.
def title_case(title, minor_words = 'uk'):
if title == '':
return ''
title = title.lower()
exception = minor_words.lower().split()
listed = title.split()
titled = listed[0].capitalize()
del listed[0]
for word in listed:
if word not in exception:
titled += " " + word.capitalize()
else:
titled += " " + word
return titled
print title_case('a clash of KINGS', 'a an the of')
| true |
1df122ea8c6cbe2473ffa0be8626f86c38d65760 | abby2407/Data_Structures-and-Algorithms | /PYTHON/Graph/Graph_Finding_Mother_Vertex.py | 1,339 | 4.15625 | 4 |
''' A mother vertex in a graph G = (V,E) is a vertex v such that all
other vertices in G can be reached by a path from v.'''
from collections import defaultdict
class Graph:
def __init__(self, vertices):
self.vertices = vertices
self.graph = defaultdict(list)
def addEdge(self, src, dest):
self.graph[src].append(dest)
def DFS(self, node, visited):
visited[node] = True
for n in self.graph[node]:
if visited[n] == False:
self.DFS(n, visited)
# ------------------ Method to find a Mother Vertex in a Graph -------------------
def findMother(self):
visited = [False] * self.vertices
v = 0
for i in range(self.vertices):
if visited[i] == False:
self.DFS(i, visited)
v = i
visited = [False] * self.vertices
self.DFS(v, visited)
if any(i == False for i in visited):
return -1
else:
return v
# ------------------ Testing the Program -----------------
g = Graph(7)
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 3)
g.addEdge(4, 1)
g.addEdge(6, 4)
g.addEdge(5, 6)
g.addEdge(5, 2)
g.addEdge(6, 0)
print("Mother vertex is: {} ".format(g.findMother())) | true |
04245a627a81d206fd76d72a9808524609498db9 | S-Tim/Codewars | /python/sudoku_solver.py | 1,926 | 4.1875 | 4 | """
Write a function that will solve a 9x9 Sudoku puzzle. The function will take one argument
consisting of the 2D puzzle array, with the value 0 representing an unknown square.
The Sudokus tested against your function will be "easy" (i.e. determinable; there will be
no need to assume and test possibilities on unknowns) and can be solved with a brute-force approach.
"""
import itertools
def sudoku(puzzle):
"""return the solved puzzle as a 2d array of 9 x 9"""
for i in range(len(puzzle)):
for j in range(len(puzzle)):
# Find next not filled out square
if puzzle[i][j] == 0:
# Test all the numbers
for num in range(1, 10):
copy_puzzle = [row[:] for row in puzzle]
copy_puzzle[i][j] = num
if check_sudoku(copy_puzzle):
# If this number works in this square so far
# then keep working with it and fill in next
solution = sudoku(copy_puzzle)
if solution is not None:
# only get here when all fields are filled in
return solution
# No number worked so backtrack
return None
return puzzle
# Credit to StackOverflow for the checking.
def sudoku_ok(line):
return (len(line) == 9 and sum(line) == sum(set(line)))
def check_sudoku(grid):
bad_rows = [row for row in grid if not sudoku_ok(row)]
grid = list(zip(*grid))
bad_cols = [col for col in grid if not sudoku_ok(col)]
squares = []
for i in range(0, 9, 3):
for j in range(0, 9, 3):
square = list(itertools.chain(*[row[j:j+3] for row in grid[i:i+3]]))
squares.append(square)
bad_squares = [square for square in squares if not sudoku_ok(square)]
return not (bad_rows or bad_cols or bad_squares)
| true |
4e2f0756383f20a076086fb655e6ed4b9c76f7ab | xeohyeonx/python-practice | /format and etc.py | 2,656 | 4.1875 | 4 | year = 2019
month = 10
day = 29
print("오늘은 " + str(year) + "년 " + str(month) + "월 " + str(day) + "일입니다.")
# 이렇게 하면 너무 번거로우니까 문자열 포맷팅을 통해서 하면 더 편함
print("오늘은 {}년 {}월 {}일입니다.".format(year, month, day)) # 이렇게 해주면 중괄호 안에 format 뒤의 파라미터들이 순서대로 들어감.
# 이렇게도 가능.
date_string = "오늘은 {}년 {}월 {}일입니다."
print(date_string.format(year, month, day))
print(date_string.format(year, month, day + 1)) # 그 다음날이 출력됨
print("저는 {}, {}, {}를 좋아합니다!".format("박지성", "유재석", "빌게이츠"))
# to change the order, 중괄호 안에 번호를 쓰면 됨. numbering starts from 0
print("저는 {1}, {0}, {2}를 좋아합니다!".format("박지성", "유재석", "빌게이츠"))
num_1 = 1
num_2 = 3
print("{0} 나누기 {1}은 {2:.2f}입니다.".format(num_1, num_2, num_1 / num_2)) # .2f는 f = floating pt, .2 = 소숫점 2째자리까지 반올림하라는 뜻. .0f라고 쓰면 정수형이 나옴.
# Boolean = 불린. 참/거짓 (따옴표 없이 True or False)
print(True and True)
print(True and False)
print(False and True)
print(False and False)
print(True or True)
print(True or False)
print(False or True)
print(False or False)
print(not True)
print(not False)
print(2 > 1)
print(2 < 1)
print(3 >= 2)
print(2 == 2) # 2는 2와 같다 라는 뜻
print(2 != 2) # 2는 2와 같지 않다는 뜻
print("Hello" == "Hello")
print(2 > 1 and "Hello" == "Hello") # = True and True
print(not not True) # = not false
print(not not False) # = not true
print(7 == 7 or (4 < 3 and 12 > 10)) # = True or (False and True) 가 되니까 값은 True
x = 3
print(x > 4 or not (x < 2 or x == 3)) # = False or not (False or True) 니까 False or (not True) = False or False = False
# 꿀팁이라네. type 이라는 함수 : 자료형을 알려줌
print(type(3))
print(type(3.0))
print(type("3"))
print(type("True"))
print(type(True)) # bool = boolean 의 줄임말
def hello():
print("Hello world!")
print(type(hello)) # 함수도 하나의 자료형
print(type(print)) # 내장되어있는 함수라는 뜻.
# practice : ()안의 수가 짝수이면 True, 홀수이면 False 가 출력되게끔 하는 함수 만들기
def is_evenly_divisible(number):
return number % 2 == 0
# 테스트 코드
print(is_evenly_divisible(3))
print(is_evenly_divisible(7))
print(is_evenly_divisible(8))
print(is_evenly_divisible(218))
print(is_evenly_divisible(317)) | false |
58ddbfe8f4eca1b019b54c2dcac4c73c94f145e9 | clarkmp/CSCI215_Assignment_1 | /portfolio/csci220/Assignment03/assignment03.py | 2,218 | 4.15625 | 4 | from math import *
def checkIfPrime():
userNumber = eval(input("Give me a number: "))
if userNumber > 1: #this makes sure the number is greater than 1 which is not a prime number
while userNumber > 1: #this only loops if the number is greater than 1
if userNumber % 2 == 0: #this will determine if the number is a prime number or not by seeing if it is a multiple of 2
print('Your number is not a prime number!')
break
else:
print('Your number is a prime number!')
break
else:
print('Your number is prime!')
checkIfPrime()
def checkIfEven():
userValue = eval(input('Give me a value: '))
while userValue > -1: #this runs the loop only if the number is not a negative number
if userValue % 2 == 0: #if the remainder is 0 then the number is even because it is divisible by 2
print('The number is even')
else: #if the remainder is not 0, then it is odd because it is not divisible by 2
print('The number is odd')
userValue = eval(input('Give me a value: ')) #since this line is still in the loop it will ask the user for a value again and restarts the loop
#checkIfEven()
def messageEncrypter(list):
for el in (list): #takes a list and goes through each letter in the list
if ord(el) > ord('Z'):
newCharacter = ord(el) - 25
print(chr(newCharacter), end='')
elif ord(el) < ord('Z'):
newCharacter = ord(el) + 25
print(chr(newCharacter), end='')
firstList = 'M[h[@e^ddo#Yec[#bWj[b_[i$M[b_l[_dj^[Yeic_YXeedZeYai$M[[c[h][Z\hecc_YheX[iWdZckYa$7f[iWh[ekhYeki_di$Ekhj^ek]^jiWdZ\[[b_d]iWh[dej\kbbokdZ[hekhemdYedjheb$J^[h[cWoX[ckY^icWhj[hWdZl[hoZ_\\[h[djX[_d]i[bi[m^[h[$7dZedjefe\Wbbj^_i"m[h[cWa_d]Wc[iie\ekhfbWd[jWdZX[Yec_d]WZWd][hjeekhi[bl[i$'
#secondList = '=djgjbdnonjao`io\gf\]jpooc`"`^jgjbt"ja\ijmb\idnh5oc`o\gg`noj\fdioc`ajm`nodnoc`o\gg`noijoepno]`^\pn`dobm`ramjhoc`c\m_d`no\^jmi6dodnoc`o\gg`no\gnj]`^\pn`ijjoc`mom``n]gj^f`_donnpigdbco'oc`njdg\mjpi_dor\n_``k\i_md^c'ijm\]]do^c`r`_ocmjpbcdon]\mf\n\n\kgdib'\i_ijgph]`me\^f^podo_jri]`ajm`doh\opm`_)'
#messageEncrypter(firstList)
| true |
0678f44e86e93fdef14ff4f35e8b6e5b7fe3ad31 | gkc23456/BIS-397-497-CHANDRATILLEKEGANA | /Assignment 2/Assignment 2 - Excercise 3.16.py | 477 | 4.15625 | 4 | # Exercise 3.16
largest = int(input('Enter number: '))
number = int(input('Enter number: '))
if number > largest:
next_largest = largest
largest = number
else:
next_largest = number
for counter in range(2, 10):
number = int(input('Enter number: '))
if number > largest:
next_largest = largest
largest = number
elif number > next_largest:
next_largest = number
print(f'Largest is {largest}\nSecond largest is {next_largest}') | true |
d368e0f0e8acbbf8dbecb6a5e6a9a64f8f3efdd7 | fmojica30/learning_python | /Palindrome.py | 2,851 | 4.21875 | 4 | # File: Palindrome.py
# Description:
# Student Name: Fernando Martinez Mojica
# Student UT EID: fmm566
# Course Name: CS 313E
# Unique Number: 50725
# Date Created: 2/20/19
# Date Last Modified: 2/20/19
def is_palindrome(s): #define if a string is a palindrome
for i in range(len(s)//2):
if s[i] != s[-i-1]:
return False
return True
def make_palindrome(s): #function for making a palindrome out of a word
newWord = '' #initial counter for the new word to see where to do the
#palindrome
if len(s) == 1: #single letter palindrome case
return s
elif len(s) == 2: #2 letter palindrome case easy solve
if s[0] == s[1]:
return s
else: #append the last letter to the front
newWord += s[1]
newWord += s
newPalindrome = newWord
return newPalindrome
else: #all other length cases
if is_palindrome(s) == True: #if the word is already a palindrome
return s
else:
for i in range(len(s)):
newWord += s[i]
#determine if the set of letters we are looking at is a palindrome
if (is_palindrome(newWord)) and (len(newWord) > 3):
if i == len(s): #the whole word is a palindrome
return newPalindrome
else: #creating a palindrome shortest
appender = '' #define letters to append at the front
adders = s[i+1:] #all of the letters required to append
adders = list(adders)
order = list(reversed(adders)) #putting them in order
for j in order:
newLetter = j
appender += newLetter
newPalindrome = appender + s
return newPalindrome
elif newWord == s: #case where the word does not include a
#palindrome
adder = ''
for i in range(-1,(-len(s) - 1),-1):
adder += s[i] #adding letters to the front from the back
#of the word until we get a palindrome
newPalindrome = adder + newWord
if is_palindrome(newPalindrome):
return newPalindrome
else:
continue
else:
continue
def main():
inf = open('palindrome.txt','r')
line = inf.readline()
line = line.strip()
while line != '':
print(make_palindrome(line))
line = inf.readline()
line = line.strip()
main()
| true |
086131ab344102d2b8f8591b21314f68ab7eef72 | manjusha18119/manju18119python | /function/d5.py | 437 | 4.5 | 4 | # Python's program to iterating over dictionaries using 'for' loops
x = {'z': 10, 'l': 50, 'c': 74, 'm': 12, 'f': 44, 'g': 19}
for key, val in x.items():
print(key, "=>", val)
print("\n------------------------\n")
for key in x:
print(key, "=>", x[key])
print("\n------------------------\n")
for key in x.keys():
print(key, "=>", x[key])
print("\n------------------------\n")
for val in x.values():
print(val)
| false |
1807e2597e8d8c7ac920d57a3dd53ed7d5e14033 | manjusha18119/manju18119python | /python/swap.py | 207 | 4.3125 | 4 | #2.Write a program to swap two variables.
a=input("Enter the value of a :")
#a=int(a)
b=input("Enter the value of b :")
#b=int(b)
temp=a
a=b
b=temp
print("swap value of a=",a)
print("swap value of b=",b)
| true |
3e0c9760a73a7629837f54f67d86ac97157cfa32 | PriceLab/STP | /chapter4/aishah/challenges.py | 575 | 4.25 | 4 | #1 ------write function that takes number as input and returns it squared
def func1(x):
return x ** 2
print(func1(2))
#2---- write a program with 2 functions-- first one takes an int
#and returns the int by 2. second one returns an integer * 4.
#call the first function, save the number, then pass to the second one
def divideBy2(x):
return x/2
y = divideBy2(6)
def multiplyBy4(u):
return u *4
print(multiplyBy4(divideBy2(6)))
#3----a function that can convert a string to a float
def convert(g):
return toFloat(g)
c = convert("3.3")
print(c)
| true |
6f2f3648576cdf8da47ca0dc88ee1a8d9ea4d80d | Kotuzo/Python_crash_course | /Follow_Up/OOP.py | 1,284 | 4.34375 | 4 | import math
# This is examplary class
class Point:
# This is constructor
# Every method from class, needs to have self, as a first argument
# (it tells Python that this method belongs to the class)
def __init__(self, x, y):
self.x = x # attributes
self.y = y
# typical method
def distance_from_origin(self):
return math.hypot(self.x, self.y)
# override of ==
def __eq__(self, other):
return self.x == other.x and self.y == other.y
# override of str(X)
def __str__(self):
return "Pxy = ({0.x}, {0.y})".format(self)
# override of +
def __add__(self, other):
return self.x + other.x, self.y + other.y
# Now Point is a base class, so Circle inherits from Point
class Circle(Point):
def __init__(self, radius, x=0, y=0):
super().__init__(x, y)
self.radius = radius
def area(self):
return math.pi * (self.radius ** 2)
if __name__ == '__main__':
P1 = Point(3, 4)
P2 = Point(8, 10)
print("Distance from (0,0): %f" % P1.distance_from_origin())
print("Is P1 equal to P2? %s" % (P1 == P2))
print(str(P1))
print("P1 + P2 (as vectors) = " + str((P1 + P2)))
C1 = Circle(2)
print("Area of circle with r=2 is %f" % C1.area())
| true |
713459f79b180b49c44dec9a671f1a08558f58ce | tonytamsf/hacker-rank | /algo/reverse.py | 297 | 4.25 | 4 | #!/usr/bin/env python3
print('''This will take an array and reverse it by
swaping items in place.
''');
def reverse(s):
for i in range (0, int(len(s) / 2)):
tmp = s[i]
s[i] = s[len(s) - 1 - i]
s[len(s) - 1 - i] = tmp
return s
print (reverse ([400,300,200,100]))
| false |
3c9d22585fbe44b08c62171c6147fbaf899cd832 | neethupauly/Luminarmaybatch | /python collections/List/lists.py | 1,191 | 4.1875 | 4 | # supports duplicates elements
# order keeps
# supports hetrogenous data
# nesting is possible
# mutable - can be updated
# lst=[1,2,3,1,2,3,"hello",True]
# print(lst)
# print(type(lst))
# lst1=[] #empty list creation
# print(lst1)
# print(type(lst1))
# lst1.append("hello")
# lst1.append(8)
# print(lst1)
# iterating
# for i in lst1:
# print(i)
#
# # removing elements
# lst.remove(1)
# print(lst)
# lst.clear() #for clear all elements
# print(lst)
# del lst #for deleting the list
# integer list
# lstin=[1,8,9,7,6,5,544,3,2,44]
# add=0
# mul=1
# for i in lstin:
# add=add+i
# mul=mul*i
# print("Added list",add)
# print("Multiplied list",mul)
#
# l1=[7,8,[9,0]]
# print(l1) #nested list
#
# # nested list iterating
# l2=[[1,2,3],[8,9,7]]
# for i in l2:
# for j in i:
# print(j)
#
# # odd even lists
# l3=[1,2,4,3,66,54,37,87,9,8]
# odd=[]
# even=[]
# for i in l3:
# if i%2==0:
# even.append(i)
# else:
# odd.append(i)
# print(odd)
# print(even)
l3=[1,8,9,0,5,6,37,23,89,99]
el=int(input("enter the element to search"))
for i in l3:
if el in l3:
print("present")
break
else:
print("not present")
| false |
66ec4ee68f6db85940fd3bd9e22f91179507e5c2 | sushidools/PythonCrashCourse | /PythonCrashCourse/Ch.4/try it yourself ch4.py | 1,434 | 4.28125 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 5 15:55:17 2018
@author: aleksandradooley
"""
spc = "\n"
pizzas = ['Hawaiin', 'BBQ chickcen', 'pepperoni']
friend_pizzas = pizzas[:]
for pizza in pizzas:
print "I like " + pizza + " pizza."
print "I really love pizza!"
pizzas.append('cheese')
print "My favorite pizzas are:"
print pizzas
print spc
print "My friend's favorite pizzas are:"
print friend_pizzas
print spc
for pizza in friend_pizzas:
print "I love " + pizza + " pizza."
print spc
# 4-2
animals = ['cat', 'dog', 'rabbit']
for animal in animals:
print "A " + animal + " would make a great pet."
print "Any of these animals would make a great pet!"
#Try it yourself pg 64
numbers = range(1,21)
print numbers
# use a for loop this time
for value in range(1,21):
print value
#look at how it printed the values. the for loop gives a new number on each new line
#the other one will print a list instead
#for value in range(1,100000000):
# print value
#you have to be careful doing whats above only because it takes time
numbers = range(1,100000001)
print min(numbers)
print max(numbers)
print sum(numbers)
print spc
odd_numbers = range(1,20,2)
print odd_numbers
print spc
numbers = range(3,31)
for number in numbers:
print number * 3
print spc
numbers = range(1,11)
for number in numbers:
print number ** 3
print spc
cubes = [value**3 for value in range(1,11)]
print cubes | true |
dea18ed1dcc6504cf5d31352a5f76485418e18d6 | catalanjrj/Learning-Python | /exercises/ex19.py | 1,560 | 4.21875 | 4 | # create a function named chees_and_crackers with two arguments.
def cheese_and_crackers(cheese_count, boxes_of_crackers):
# print the amount of cheeses.
print(f"You have {cheese_count} cheeses!")
# print the number of boxes of crackers.
print(f"You have {boxes_of_crackers} boxes of crackers!")
# print "Man that's enough for a party!".
print("Man that's enough for a party!")
# print "Get a blanket." and add a new line.
print("Get a blanket. \n")
# give the function values for the two arguments.
print("We can just give the function numbers directly:")
cheese_and_crackers(20,30)
# give amount_of_cheese and amount_of_crackers values
print("OR, we can use variable from our script:")
amount_of_cheese = 10
amount_of_crackers = 50
# give cheese_and_crackers the value of amount_of_cheese and amount_of_crackers.
cheese_and_crackers(amount_of_cheese, amount_of_crackers)
# Do some math inside cheese_and_crackers.
print("We can even do math inside too:")
cheese_and_crackers(10 + 20, 5 + 6)
# Do math with both variables and numbers.
print("And we can combine the two, variables and math:")
cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)
def sandwiches(with_cheese, without_cheese):
# print("We also have sandwiches")
print(f"We have {with_cheese} sandwiches with cheese")
print(f"We have {without_cheese} sandwiches without cheese")
print("How many sandwiches do we have?");sandwiches(30,40)
print("How many sandwiches do we have?");sandwiches(input("With cheese?"), input("No cheese?"))
| true |
5bbf167d0de558186b79ad5aade880d6119973fb | catalanjrj/Learning-Python | /exercises/ex4.py | 1,232 | 4.15625 | 4 | # Assign a value of 100 to cars
cars = 100
# Assign a value of 4 to space_in_a_car
space_in_a_car = 4
# Assign a value of 30 to drivers
drivers = 30
# Assign a value of 90 to passengers
passengers = 90
# Assign the result of cars minus drivers to cars_not_driven
cars_not_driven = cars - drivers
# Assign the value of drivers to cars_driven
cars_driven = drivers
# Assign the result of cars_driven multiplied by space_in_a_car to carpool_capactiy
carpool_capacity = cars_driven * space_in_a_car
# Assign the result of passengers divided by cars_driven to average_passengers_per_car
average_passengers_per_car = passengers / cars_driven
# Number of available cars
print("There are", cars, "cars available.")
# Number of available drivers
print("There are only", drivers, "drivers available.")
# The number of empty cars that there will be today
print("There will be", cars_not_driven, "empty cars today.")
# The number of people that we can transport today
print("We can transport", carpool_capacity, "people today.")
# The number of passengers to carpool today
print("We have", passengers, "to carpool today.")
# The number of passengers per car
print("We need to put about", average_passengers_per_car, "in each car.")
| true |
322bdb0b3381a696bc3b088f015f2e3c1b5e2665 | himeshnag/Ds-Algo-Hacktoberfest | /Python/ArrayRotation.py | 569 | 4.28125 | 4 |
from Arrays import Array
def rotation(rotateBy, myArray):
for i in range(0, rotateBy):
rotateOne(myArray)
return myArray
def rotateOne(myArray):
for i in range(len(myArray) - 1):
myArray[i], myArray[i + 1] = myArray[i + 1], myArray[i]
if __name__ == '__main__':
myArray = Array(10)
for i in range(len(myArray)):
myArray.insert(i, i)
print('Before Rotation:',myArray)
print('After Rotation:',rotation(3, myArray))
# OUTPUT:
# Before Rotation: 0 1 2 3 4 5 6 7 8 9
# After Rotation: 3 4 5 6 7 8 9 0 1 2 | false |
3d33eb6cadd1028c81b2190b91fb3cdde5763a7c | sewald00/Pick-Three-Generator | /pick_three.py | 951 | 4.28125 | 4 | """Random pick three number generator
Seth Ewald
Feb. 16 2018"""
import tkinter as tk
from tkinter import ttk
from random import randint
#Define the main program function to run
def main():
#Define function to change label text on button click
def onClick():
a = randint(0, 9)
b = randint(0, 9)
c = randint(0, 9)
d=(a,b,c)
label.config(text=d)
#Create app window
root = tk.Tk()
root.minsize(width=300, height=75)
root.maxsize(width=300, height=75)
root.title("Pick Three Generator")
#Create button to generate a random pick three
button = tk.Button(root, text='Generate Numbers',
width=25, command=onClick)
button.pack()
#Create a label to display the random pick three
label = tk.Label(root, text='')
label.pack()
root.mainloop()
if __name__ =='__main__':
main()
| true |
7d3279e79e140c6feffd735171703b00a5310377 | katcosgrove/data-structures-and-algorithms | /challenges/binary-search/binary_search.py | 321 | 4.21875 | 4 |
def BinarySearch(arr, val):
"""
Arguments: A list and value to search for
Output: The index of the matched value, or -1 if no match
"""
if len(arr) == 0:
return -1
counter = 0
for item in arr:
counter += 1
if item == val:
return counter - 1
return -1
| true |
3cbb921b6d67b3811de9e9e117d3013dd03bb5bc | renefueger/cryptex | /path_util.py | 980 | 4.4375 | 4 | def simplify_path(path: str, from_separator='/', to_separator='/') -> str:
"""Returns the result of removing leading/trailing whitespace and
consecutive separators from each segment of the given path."""
path_parts = path.split(from_separator)
stripped_parts = map(lambda x: x.strip(), path_parts)
valid_parts = filter(lambda x: x, stripped_parts)
return to_separator + to_separator.join(valid_parts)
def encode_path(path: str) -> str:
"""Converts a standard *nix/URL-style path to one which uses the '+'
character for path separators. Before making this replacement, the path
is simplified, using simplify_path(). For example, given the path /foo/bar/,
this function will return +foo+bar.
"""
return simplify_path(path, to_separator='+')
def decode_path(path: str) -> str:
"""Performs the reverse of encode_path(), namely, replacing '+' with
'/' in the given path."""
return simplify_path(path, from_separator='+')
| true |
da73cd924c0b1e5b33b8a47a882815fb8c232b3a | nramiscal/spiral | /spiral.py | 1,598 | 4.25 | 4 | '''
Given a N by M matrix of numbers, print out the matrix in a clockwise spiral.
For example, given the following matrix:
[[1, 2, 3, 4, 5], <-- matrix[0]
[6, 7, 8, 9, 10], <-- matrix[1]
[11, 12, 13, 14, 15], <-- matrix[2]
[16, 17, 18, 19, 20]] <-- matrix[3]
You should print out the following:
1
2
3
4
5
10
15
20
19
18
17
16
11
6
7
8
9
14
13
12
'''
def spiral(m):
Xmin = 0
minY = 0
Xmax = len(m)-1
maxY = len(m[0])-1
size = len(m) * len(m[0])
# print(size)
count = 0
while size > 0:
for i in range(minY, maxY+1, 1):
size -= 1
# print(m[Xmin][i], size)
print(m[Xmin][i])
if size == 0:
return
for i in range(Xmin+1, Xmax+1, 1):
size -= 1
# print(m[i][maxY], size)
print(m[i][maxY])
if size == 0:
return
for i in range(maxY-1, minY-1, -1):
size -= 1
# print(m[Xmax][i], size)
print(m[Xmax][i])
if size == 0:
return
for i in range(Xmax-1, Xmin, -1):
size -= 1
# print(m[i][minY], size)
print(m[i][minY])
if size == 0:
return
Xmin += 1
minY += 1
Xmax -= 1
maxY -=1
matrix = [
[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25],
[26, 27, 28, 29, 30],
[31, 32, 33, 34, 35],
[36, 37, 38, 39, 40]
]
spiral(matrix)
| true |
2047056b45017b5284555de99a086a164252e82c | Mattdinio/Code-at-GU-2019 | /Assignment 1.py | 1,303 | 4.1875 | 4 | # Question 1
def divisibleByThree ():
for i in range(1,101):
if i % 3 == 0:
print (i)
# Question 2
def shakespeare ():
quote = ""
# Question 3
def numberThing():
for i in range (1,11):
if i % 3 == 0:
print (i**3)
elif i % 2 == 0:
print (i**2)
else:
print (i)
# Please feel free this main which has a simple interface for testing
def main():
questionNumber = input("what question do you want to run? ")
while questionNumber.isdigit() == False:
questionNumber = input("what question do you want to run? ")
questionNumber = int(questionNumber)
if questionNumber == 1:
divisibleByThree()
elif questionNumber == 2:
print ("question Incomplete")
elif questionNumber == 3:
numberThing()
else:
print("question not found")
yesResponses = ["Yes","yes","YEs","YES","yEs","yES"]
noResponses = ["no","No","NO","nO"]
userContinue = input("do you want to pick another question to run? (yes / no)")
while userContinue not in yesResponses and userContinue not in noResponses:
userContinue = input("do you want to pick another question to run? (yes / no)")
if userContinue in yesResponses:
main()
else:
quit() | false |
04e6251f38a87afe8d52bcc270898de75aa45b44 | Lyondealpha-hub/Python-Programs | /FizzBuzz.py | 325 | 4.15625 | 4 | #A program that changes multiple of 3 to fizz, multiple of 5 to buzz and multiple of
#both 3 and 5 to fizzbuzz
print("A program for a FIZZBUZZ ")
for i in range(1,101):
if i%3==0:
print( i, "\t","Fizz")
if i%5 == 0:
print(i, "\t","Buzz")
if i%3==0 and i%5==0:
print(i, "\t","FizzBuzz")
| false |
adf804c78c165f98bff660077784aeca3bbc1932 | BryantCR/FunctionsBasicII | /index.py | 2,717 | 4.3125 | 4 | #1 Countdown - Create a function that accepts a number as an input. Return a new list that counts down by one, from the number (as the 0th element) down to 0 (as the last element).
# Example: countdown(5) should return [5,4,3,2,1,0]
def countDown(num):
result = []
for i in range(num, -1, -1):
result.append(i)
print(result)
countDown(5)
#2 Print and Return - Create a function that will receive a list with two numbers. Print the first value and return the second.
# Example: print_and_return([1,2]) should print 1 and return 2
def printAndReturn(myList):
# for i in range(0, len(myList), 1):
print(myList[0])
# break
return myList[1]
print(printAndReturn([1, 2]))
print(printAndReturn([5, 8]))
#3 First Plus Length - Create a function that accepts a list and returns the sum of the first value in the list plus the list's length.
# Example: first_plus_length([1,2,3,4,5]) should return 6 (first value: 1 + length: 5)
def first_plus_length(arr):
for i in range(0, len(arr), 1):
sum = 0
sum = arr[0] + len(arr)
return sum
print(first_plus_length([1, 2, 3, 4, 5]))
#4 Values Greater than Second - Write a function that accepts a list and creates a new list containing only the values from the original list that are greater than its 2nd value. Print how many values this is and then return the new list. If the list has less than 2 elements, have the function return False
# Example: values_greater_than_second([5,2,3,2,1,4]) should print 3 and return [5,3,4]
# Example: values_greater_than_second([3]) should return False
def values_greater_than_second(arr):
greaterValues = []
if len(arr) < 2:
return False
else:
for i in range (0 ,len(arr), 1):
if arr[i] > arr[1]:
greaterValues.append(arr[i])
print(len(greaterValues))
return greaterValues
print(values_greater_than_second([5, 2, 3, 2, 1, 4]))
#5 This Length, That Value - Write a function that accepts two integers as parameters: size and value. The function should create and return a list whose length is equal to the given size, and whose values are all the given value.
# Example: length_and_value(4,7) should return [7,7,7,7]
# Example: length_and_value(6,2) should return [2,2,2,2,2,2]
def length_and_value(a,b):
newlist = []
for i in range (0 ,a, 1):
newlist.append(b)
print(newlist)
length_and_value(4,7)
length_and_value(6,2)
# newlist.append(arr[1])
# return newlist
# def length_and_value(arr):
# newlist = []
# for i in range (0 , arr[0], 1):
# newlist.append(arr[1])
# return newlist
# print(length_and_value([7,2]))
# print(length_and_value([4,3])) | true |
1ef6cc0dd575247f5b227eca08802a0f623744f1 | dhilankp/GameDesign2021 | /Python2021/VarAndStrings.py | 902 | 4.15625 | 4 | #Dhilan Patel
# We are learning how to work with Srtings
# While loop
# Different type of var
num1=19
num2=3.5
num3=0x2342FABADCDACFACEEDFA
#How to know what type of data is a variable
print(type(num1))
print(type(num2))
print(type(num3))
phrase='Hello there!'
print(type(phrase))
#String functions
num=len(phrase)
print(num)
print(phrase[3:7]) #print from 3 to 6
print(phrase[6:]) #from index to the end
print(phrase *2) #Print it twice
#concadenation --> joining strings
phrase = phrase + " "+ "Goodbye"
print(phrase[2:num-2])
while "there" in phrase:
print("there" in phrase)
phrase="changed"
print(phrase)
# make 3 string variables print them individualy
#"print s1+s2"
#print st2+st3
#print st1+st2 +st3
string= "Good Morning!"
string2="Good Afternoon!"
string3="Have a good day!"
print(string +" " + string2 )
print(string2 +" "+ string3)
print(string +" " + string2 +" " +string3)
| true |
c866c92036fbd6d45abb7efc3beca71b065abda9 | DNA-16/LetsUpgrade-Python | /Day3Assign.py | 679 | 4.21875 | 4 | #Assignment1:Sum of N numbers using while
sum=0
N=eval(input("Enter the number "))
flag=0
n=0
while n!=N+1:
if(type(N)==float):
flag=1
break
sum=sum+n
n+=1
if(flag==1):
print(N,"is not a natural number")
else:
print("Sum of first",N,"natural number is ",sum)
#Assignment2:To check whether the number is prime or not
num=int(input("Enter the number "))
flag1=0
for each in range(2,int((num+1)/2)):
if(num%each==0):
flag1=1
break
if(num==1):
print("1 is neither prime nor composite.")
elif(flag1==1):
print(num,"is not a prime number.")
else:
print(num,"is a prime number.") | true |
594cd76e835384d665f0a8390f82265616e34359 | stackpearson/cs-project-time-and-space-complexity | /csSortedTwosum.py | 667 | 4.1875 | 4 | # Given a sorted array (in ascending order) of integers and a target, write a function that finds the two integers that add up to the target.
# Examples:
# csSortedTwoSum([3,8,12,16], 11) -> [0,1]
# csSortedTwoSum([3,4,5], 8) -> [0,2]
# csSortedTwoSum([0,1], 1) -> [0,1]
# Notes:
# Each input will have exactly one solution.
# You may not use the same element twice.
def csSortedTwoSum(numbers, target):
for i in range(len(numbers)):
for j in range (i + 1, len(numbers)):
if numbers[i] + numbers[j] == target:
return [i, j]
return "no valid solution found"
print(csSortedTwoSum([3,7,12,16], 11)) ## should bwe [0, 1] | true |
263e35c47464a3fee4967b212ac0b7ba6a2c286e | maheshbabuvanamala/Python | /LinkedList.py | 839 | 4.15625 | 4 | class Node:
""" Node in Linked List """
def __init__(self,value):
self.data=value
self.next=None
def set_data(self,data):
self.data=data
def get_data(self):
return self.data
def set_next(self,next):
self.next=next
def get_next(self):
return self.next
def hasNext(self):
return self.next!=None
class LinkedList:
def __init__(self, head=None):
self.head = head
def insert(self, data):
new_node = Node(data)
new_node.set_next(self.head)
self.head = new_node
""" Traversing Element """
def traverse(self):
current=self.head
while current is not None:
print(current.get_data())
current=current.get_next()
a=LinkedList()
a.insert(10)
a.insert(11)
a.insert(12)
a.traverse()
| true |
4952a6ac5f3d8f91bd165603355c75eb68450fcf | muthoni12/ppython_listsandforloops | /dictionary.py | 614 | 4.125 | 4 | #student = {
# "name" : "pal",
# "age" : 19,
# "gender" : "F"
#}
#
#student["name"] = "val"
#print(student["name"])
'''
combined list with dictionary to have all that same data but for more than one item.
'''
users = [
{
"name" : "hal",
"age" : 19,
"gender" : "F"
},
{
"name" : "mal",
"age" : 9,
"gender" : "M"
},
{
"name" : "sal",
"age" : 10,
"gender" : "F"
}
]
for user in users:
print(user["name"])
for user in users:
if user["name"] == "sal":
print(user["name"])
print(user["age"])
print(user["gender"])
| false |
12f482950563599c33857c3264b4ce5c56e6a64d | xwinxu/foobar | /p1/cake.py | 2,679 | 4.1875 | 4 | """
The cake is not a lie!
======================
Commander Lambda has had an incredibly successful week: she completed the first test run of her LAMBCHOP doomsday device, she captured six key members of the Bunny Rebellion, and she beat her personal high score in Tetris. To celebrate, she's ordered cake for everyone - even the lowliest of minions! But competition among minions is fierce, and if you don't cut exactly equal slices of cake for everyone, you'll get in big trouble.
The cake is round, and decorated with M&Ms in a circle around the edge. But while the rest of the cake is uniform, the M&Ms are not: there are multiple colors, and every minion must get exactly the same sequence of M&Ms. Commander Lambda hates waste and will not tolerate any leftovers, so you also want to make sure you can serve the entire cake.
To help you best cut the cake, you have turned the sequence of colors of the M&Ms on the cake into a string: each possible letter (between a and z) corresponds to a unique color, and the sequence of M&Ms is given clockwise (the decorations form a circle around the outer edge of the cake).
Write a function called solution(s) that, given a non-empty string less than 200 characters in length describing the sequence of M&Ms, returns the maximum number of equal parts that can be cut from the cake without leaving any leftovers.
Languages
=========
To provide a Python solution, edit solution.py
To provide a Java solution, edit solution.java
Test cases
==========
Inputs:
(string) s = "abccbaabccba"
Output:
(int) 2
Inputs:
(string) s = "abcabcabcabc"
Output:
(int) 4
"""
def is_valid(pattern: str, s: str, parts: int) -> bool:
"""
Essentially to do this more efficiently:
pattern = s[0:i] * parts
if pattern == s:
return parts
"""
for i in range(1, parts):
start = i * len(pattern)
if pattern != s[start:start + len(pattern)]:
return False
return True
def solution(s: str) -> int:
n = len(s)
# technically don't need to think of this, because it wouldn't make sense
# to have an empty string for this question, what would you even do?
if n == 0:
return 0
for i in range(1, n // 2 + 1):
# check every substring divisible by n
if n % i == 0:
parts = n // i
pattern = s[0:i]
# check that the substring is a repetition for the entire string
if is_valid(pattern, s, parts):
return parts
# print("hit")
# eg can't divide, return the whole cake, so hence why we can just loop thru half of the string
return 1
if __name__ == '__main__':
s1 = "abcabcabcabc"
s2 = 'abccbaabccba'
print("s1: ", solution(s1))
print("s2: ", solution(s2)) | true |
f30a9c52b7223972fcacf450c8815820989f22a7 | AdamJDuggan/starter-files | /frontEndandPython/lists.py | 847 | 4.59375 | 5 | the_count = [1, 2, 3, 4, 5]
fruits = ["apples", "oranges", "pears", "apricots"]
change = [1, "pennies", 2, "dimes", 3, "quarters"]
#this kind of for loop goes through a list
for number in the_count:
print("This is count {}".format(number))
#same as above
for adam in fruits:
print("A fruit of type {}".format(adam))
#we can also go through mixed lists to:
#we have to use {} because we dont yet know what i is
for i in change:
print("I got {}". format(i))
#we can also build lists. First start with an empty one:
elements = []
#then do a range function to do 0 to 5 counts
for i in range(0, 6):
print("Adding {} to the list".format(i))
#append is a function that lists Understand
elements.append(i)
#we can now print them out to:
for i in elements:
print("Element was: {}".format(i))
| true |
a8e5e788a73225147820189ea73a638e1547345e | sherrymou/CS110_Python | /Mou_Keni_A52_Assignment4/1. gradeChecker.py | 1,188 | 4.125 | 4 | '''
Keni Mou
Kmou1@binghamton.edu
Assignment 4, Exercise 1
Lab Section 52
CA Kyle Mille
'''
'''
Analysis
Get grade from mark
Output to monitor:
grade(str)
Input from keyboard:
mark(float)
Tasks allocated to Functions:
gradeChecker
Check the mark, determine the mark belongs to which grade
'''
# Constants
A_LINE = 90
B_LINE = 80
C_LINE = 70
D_LINE = 60
# Check the mark, determine the mark belongs to which grade
# param mark(float)
# param grade(str)
# return the grade of the mark
def gradeChecker(mark):
if mark >= A_LINE:
grade = "A"
elif mark >= B_LINE:
grade = "B"
elif mark >= C_LINE:
grade = "C"
elif mark >= D_LINE:
grade = "D"
else:
grade = "F"
return grade
# let user input a mark and check the grade.
def main():
print("This program is to check your grade from your mark.\n"\
"The rule is: A(>=90), B(>=80), C(>=70), D(>=60),F(<60)")
# Take in user input and convert
markStr = input ("Please enter your mark")
mark = float(markStr)
# Compute
grade = gradeChecker(mark)
# Display
print("Your mark is ", mark, ",and your grade is ",grade)
main()
| true |
c438c3f44c1a2e9b7e12d3a8289e058361f99228 | sherrymou/CS110_Python | /Mou_Keni_A52_Lab9/#1-2.py | 1,729 | 4.21875 | 4 | '''
Keni Mou
Kmou1@binghamton.edu
Lab9, Excerise 1-2
Lab Section 52
CA Kyle Mille
'''
'''
Analyze
To compute the max rain fall, min rain fall, and average rain fall
use the readline() method
Output to the monitor:
maxrain(float)
minrain(float)
average(float)
Input from keyboard:
filename(str)
Tasks:
getMax
to get the max rainfall
getMin
to get the min rainfall
getAverage
to get the average rainfall
'''
#Constants
READ="r"
#get the max rainfall
#param rainValue(float)
#param maxrain(float)
#return maxrain(float)
def getMax(rainValue,maxrain):
if rainValue > maxrain:
maxrain = rainValue
return maxrain
#get the min rainfall
#param rainValue(float)
#param minrain(flaot)
#return minrain(float)
def getMin(rainValue,minrain):
if rainValue < minrain:
minrain = rainValue
return minrain
#get the average rainfall
#param theSum(float)
#param theCounter(int)
#return average(flaot)
def getAverage(theSum,theCounter):
return theSum/theCounter
#Get the file, compute the needed values with the readline method
def main():
filename=input("Please enter file name containing rainfall data: ")
rainfall=open(filename,READ)
#initialization
maxrain=0
minrain=1000000000
theSum=0
theCounter=0
#read lines and compute
line=rainfall.readline()
while line:
values=line.split()
rainValue=float(values[1])
maxrain=getMax(rainValue, maxrain)
minrain=getMin(rainValue, minrain)
theSum+=rainValue
theCounter+=1
#start another line
line=rainfall.readline()
average=getAverage(theSum, theCounter)
#display
print("Max rain fall is %.2f"%(maxrain), "Min rain fall is %.2f"%(minrain),'\n'\
"The average is %.2f"%(average))
main()
| true |
cc2d9b75be11f392906fab1f1e840f0865773c87 | vicasindia/programming | /Python/even_odd.py | 376 | 4.5 | 4 | # Program to check whether the given number is Even or Odd.
# Any integer number that can be exactly divided by 2 is called as an even number.
# Using bit-manipulation (if a number is odd than it's bitwise AND(&) with 1 is equal to 1)
def even_or_odd(n):
if n & 1:
print(n, "is Odd number")
else:
print(n, "is Even number")
even_or_odd(int(input("Enter a number ")))
| true |
419411b48b60121fec7809cb902b8f5ad027a6d2 | PDXDevCampJuly/john_broxton | /python/maths/find_prime.py | 813 | 4.1875 | 4 | #
# This program inputs a number prints out the primes of that number in a text file
#
###################################################################################
import math
maximum = eval(input("Please enter a number. >>> "))
primes = []
if maximum > 1:
for candidate in range(2, maximum + 1):
is_prime = True
for factor in range(2, candidate):
if candidate % factor == 0:
is_prime = False
break
if is_prime:
primes.append(candidate)
newFile = "\n".join(map(str, primes))
with open('primes.txt', 'w') as f:
f.write(newFile)
def factors(n):
fact=[1,n]
check=2
rootn=math.sqrt(n)
while check<rootn:
if n%check==0:
fact.append(check)
fact.append(n/check)
check+=1
if rootn==check:
fact.append(check)
fact.sort()
return fact
print(fact)
factors(100) | true |
e80520fea7160878811113027d0483d028041d82 | PDXDevCampJuly/john_broxton | /python/sorting/insertion_sort.py | 1,441 | 4.25 | 4 | def list_swap(our_list, low, high):
insIst[low], insIst[high] = insIst[high], insIst[low]
return insIst
pass
def insertion_sort(insIst):
numbers = len(insIst)
for each in range(numbers - 1):
start = each
minimum = insIst[each]
for index in range(1, len(insIst)):
candidate = insIst[index]
comparison_index = index - 1
while index >= 0:
if candidate < insIst[comparison_index]:
list_swap(insIst, comparison_index, comparison_index + 1)
comparison_index =- 1
else:
break
return insIst
pass
#This type of sort goes through the list and compares the two values that are next to each other. n and n+1.
#If n+1 is smaller than n, then it swaps the values. Then it moves on to the next position.
#create an index of this list
#iterate through the list while comparing each value in the list to the one before it
#run the listSwap algorithm on each pair of values from the current to the first
def insertSort(myList):
for index in range(1, len(myList)):
currentvalue = myList[index]
position = index
while position>0 and myList[position-1]>currentvalue:
myList[position]=myList[position-1]
position = position-1
myList[position]=currentvalue
myList = [54,26,93,17,77,31,44,55,20]
insertSort(myList)
print(myList)
| true |
31ea7b76addea2e6c4f11acd957550a69c864ef1 | DKNY1201/cracking-the-coding-interview | /LinkedList/2_3_DeleteMiddleNode.py | 1,263 | 4.125 | 4 | """
Delete Middle Node: Implement an algorithm to delete a node in the middle (i.e., any node but
the first and last node, not necessarily the exact middle) of a singly linked list, given only access to
that node.
EXAMPLE
Input: the node c from the linked list a -> b -> c -> d -> e -> f
Result: nothing is returned, but the new linked list looks like a -> b -> d -> e -> f
"""
import unittest
from LinkedList import LinkedList
def delete_middle_node(ll, middle_node):
if not ll or not ll.head or not middle_node:
return
next = middle_node.next
middle_node.val = next.val
middle_node.next = next.next
next.next = None
class Test(unittest.TestCase):
def test_delete_middle_node(self):
ll = LinkedList()
vals = [7, 3, 4, 5, 6, 7, 10, 100, 4, 7]
ll.add_nodes_to_tail(vals)
expect = [7, 3, 4, 6, 7, 10, 100, 4, 7]
delete_middle_node(ll, ll.get_k_th_node(3))
self.assertEqual(expect, ll.to_list(), "Should remove provided middle node")
ll = LinkedList()
vals = [7, 3, 4]
ll.add_nodes_to_tail(vals)
expect = [7, 4]
delete_middle_node(ll, ll.get_k_th_node(1))
self.assertEqual(expect, ll.to_list(), "Should remove provided middle node") | true |
bb3f4cde389b50ffa4157e4310c764f66d7f9cb0 | KUSH2107/FIrst_day_task | /17.py | 237 | 4.125 | 4 | # Please write a program to shuffle and print the list [3,6,7,8]
import random
a1_list = [1, 4, 5, 6, 3]
print ("The original list is : " + str(a1_list))
random.shuffle(a1_list)
print ("The shuffled list is : " + str(a1_list))
| true |
bd4fb7517823537a46ff3d5b28ff2f5fe36efc32 | ethanschafer/ethanschafer.github.io | /Python/PythonBasicsPart1/labs/mathRunner.py | 957 | 4.125 | 4 | from mathTricks import *
inst1 = "Math Trick 1\n\
1. Pick a number less than 10\n\
2. Double the number\n\
3. Add 6 to the answer\n\
4. Divide the answer by 2\n\
5. Subtract your original number from the answer\n"
print (inst1)
# Get input for the first math trick
num = input("Enter a number less than 10: ")
num = int(num)
# Call the trick1 method and print the result
print ("Your answer is", str(trick1(num)), "\n\n")
inst2 = "Math Trick 2\n\
1. Pick any number\n\
2. Multiply the number by 3\n\
3. Add 45 to the answer\n\
4. Multiple the answer by 2\n\
5. Divide the answer by 6\n\
6. Subtract your original number from the answer\n"
print (inst2)
num = input("Enter a number less than 10: ")
num = int(num)
print ("Your answer is", str(trick2(num)), "\n\n")
# Get input for the second math trick
# Call the trick2 method and print the result
| true |
8e80b1006bc765ff53493073f34731554ff52c27 | yuliaua1/algorithms | /RandomList_01.py | 382 | 4.3125 | 4 | # This is a simple program to generate a random list of integers as stated below
import random
def genList(s):
randomList = []
for i in range(s):
randomList.append(random.randint(1, 50))
return randomList
print(genList(30))
#This is creating the list using list comprehensions
#randomList = [ random.randint(1, 50) for i in range(20) ]
#print(randomList)
| true |
37aaf1fd82c0ded9d0578e8a971eb146463ba95f | testlikeachamp/codecademy | /codecademy/day_at_the_supermarket.py | 1,874 | 4.125 | 4 | # from collections import Counter
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
# Write your code below!
def compute_bill(food):
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
assert isinstance(food, (list, tuple, set)), "{} error enter type".format(food)
total = 0
for item in food:
if item not in stock:
print(str(item) + " not in price")
elif stock[item] > 0:
total += prices[item]
stock[item] -= 1
else:
print(str(item) + " out of stock")
print("total: " + str(total))
return total
# 4 Lists + Functions
def fizz_count(x):
"""The function counts str 'fizz' in the input list"""
assert isinstance(x, list), "{} error enter type".format(x)
count = 0
for item in x:
if item == 'fizz':
count += 1
return count
# 11 Making a Purchase
def compute_bill_11(food):
"""Calculate the sum of prices for fruit's list"""
assert isinstance(food, (list, tuple, set)), "{} error enter type".format(food)
total = 0
for item in food:
try:
total += prices[item]
except KeyError as e:
print("The item {} is not in price-list".format(e))
return total
# 13 Let's check out
def compute_bill_13(food):
"""Finalize A day at the supermarket"""
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
assert isinstance(food, (list, tuple, set)), "{} error enter type".format(food)
total = 0
for item in food:
try:
if stock[item] > 0:
total += prices[item]
stock[item] -= 1
except KeyError as e:
print("The item {} is not in price-list".format(e))
return total
| true |
20849ee4f75e876464e380437d45a5b0f8835f4d | shedaniel/python_3 | /Lesson4.2.py | 235 | 4.5 | 4 | #Range
#It is used for loops
#it will run the loop form %start% to %stop% which each time added it by %plus%
#range(start, stop)
for x in range(1 , 6):
print(x)
#range(start, stop, plus)
for x in range(100, 107, 3):
print(x)
| true |
18c656d4e69e8c6ee881c0c9a4bd9af8908196c9 | GlenboLake/DailyProgrammer | /C204E_remembering_your_lines.py | 2,868 | 4.21875 | 4 | '''
I didn't always want to be a computer programmer, you know. I used to have
dreams, dreams of standing on the world stage, being one of the great actors
of my generation! Alas, my acting career was brief, lasting exactly as long as
one high-school production of Macbeth. I played old King Duncan, who gets
brutally murdered by Macbeth in the beginning of Act II. It was just as well,
really, because I had a terribly hard time remembering all those lines! For
instance: I would remember that Act IV started with the three witches brewing
up some sort of horrible potion, filled will all sorts nasty stuff, but except
for "Eye of newt", I couldn't for the life of me remember what was in it! Today,
with our modern computers and internet, such a question is easy to settle: you
simply open up the full text of the play and press Ctrl-F (or Cmd-F, if you're
on a Mac) and search for "Eye of newt".
And, indeed, here's the passage:
Fillet of a fenny snake,
In the caldron boil and bake;
Eye of newt, and toe of frog,
Wool of bat, and tongue of dog,
Adder's fork, and blind-worm's sting,
Lizard's leg, and howlet's wing,-
For a charm of powerful trouble,
Like a hell-broth boil and bubble.
Sounds delicious!
In today's challenge, we will automate this process. You will be given the full
text of Shakespeare's Macbeth, and then a phrase that's used somewhere in it.
You will then output the full passage of dialog where the phrase appears.
'''
import re
def get_line_number(lines, phrase):
for row in range(len(lines)):
if lines[row].find(phrase) >= 0:
return row
def get_passage(lines, phrase):
start = get_line_number(lines, phrase)
end = start + 1
while lines[start - 1].startswith(' '):
start -= 1
while lines[end].startswith(' '):
end += 1
passage = '\n'.join(lines[start:end])
speaker = "Spoken by {}:".format(lines[start - 1].strip(' .'))
sceneline = start
while not lines[sceneline].startswith("SCENE"):
sceneline -= 1
scene = lines[sceneline][0:lines[sceneline].index('.')]
actline = sceneline
while not lines[actline].startswith("ACT"):
actline -= 1
act = lines[actline].rstrip('.')
chars = set()
row = sceneline + 1
while not (lines[row].startswith("ACT") or lines[row].startswith("SCENE")):
match = re.match('^ (\w[^.]+)', lines[row])
if match: chars.add(match.group(1))
row += 1
characters = "Characters in scene: " + ', '.join(chars)
return '\n'.join([act, scene, characters, speaker, passage])
macbeth = [row.strip('\n') for row in open('input/macbeth.txt', 'r').readlines()]
# print get_passage(macbeth, 'break this enterprise')
# print get_passage(macbeth, 'Yet who would have thought')
print(get_passage(macbeth, 'rugged Russian bear'))
| true |
26d5df3fd92ed228fb3b46e32b1372a0eb5e9664 | UIHackyHour/AutomateTheBoringSweigart | /07-pattern-matching-with-regular-expressions/dateDetection.py | 2,902 | 4.46875 | 4 | #! python3
# Write a regular expression that can detect dates in the DD/MM/YYYY format.
## Assume that the days range from 01 to 31, the months range from 01 to 12, and the years range
## from 1000 to 2999. Note that if the day or month is a single digit, it’ll have a leading zero.
# The regular expression doesn’t have to detect correct days for each month or for leap years;
## it will accept nonexistent dates like 31/02/2020 or 31/04/2021.
# Then store these strings into variables named month, day, and year,
## and write additional code that can detect if it is a valid date.
# April(4), June(6), September(9), and November(11) have 30 days, February has 28 days,
## and the rest of the months have 31 days. February has 29 days in leap years.
# Leap years are every year evenly divisible by 4, except for years evenly divisible by 100,
## unless the year is also evenly divisible by 400.
import pyperclip, re
text = str(pyperclip.paste()) # Save whatever is on computer clipboard to text variable
dateRegex = re.compile(r'(\d+)/(\d+)/(\d+)') # Object for "number / number / number"
## with each number in its own group
allDates = dateRegex.findall(text) # This will find all date formats as a list of tuples [(day/month/year)]
validDates = [] # Valid dates will fill this list
for aTuple in allDates:
dateValid = True # Instantiate to reference later
shortMonths = [2, 4, 6, 9, 11] # Months: Feb, Mar, June, Sep, Nov
day, month, year = aTuple[0], aTuple[1], aTuple[2] # Creates an independant variable with all groups of tuple
if int(month) >12 or int(month) <1: # Is month a valid number?
dateValid = False
if int(day) >31 or int(day) <1: # Is day a valid number?
dateValid = False
if int(day) == 31 and int(month) in shortMonths: # Is day addionally valid in the context of Month?
dateValid = False
if int(day) >29 and int(month) == 2: # Is day valid in the context of February?
dateValid = False
if int(day) == 29 and int(month) == 2: # Is it a leap year (year divisible by 4 but not 100 unless also 400)?
if int(year) % 4 == 0:
if int(year) % 400 == 0:
pass
elif int(year) % 100 == 0:
dateValid = False
else:
pass
else:
dateValid = False
if dateValid == True: # If no checks find False
validDates.append([day, month, year])
datesString = "" # This string will be built a new string from the contents of validDates
for aList in validDates:
for item in aList:
datesString += item
if item != aList[-1]: # Add a slah or a space in respective place
datesString += "/"
else:
datesString += " "
pyperclip.copy("Valid dates: " + datesString) # Past new string | true |
24e238601bfe282712b8fbea574a98114ecf9b99 | omarBnZaky/python-data-structures | /check_palanced_parenthece.py | 1,231 | 4.3125 | 4 | """
Use a stack to check whether or not a string
has balanced usage of parnthesis.
"""
from stack import Stack
def is_match(p1,p2):
print("math func:" + str((p1,p2)))
if p1 == '(' and p2 == ')':
print("match")
return True
elif p1 == '{' and p2 == '}':
print("match")
return True
elif p1 == '[' and p2 == ']':
print("match")
return True
else:
print("never")
return False
def is_paren_balanced(paren_string):
s = Stack()
is_balanced = True
index = 0
# print(len(paren_string))
while index < len(paren_string) and is_balanced:
print(index)
paren = paren_string[index]
if paren in '([{':
s.push(paren)
else:
if s.is_empty():
is_balanced=False
else:
top = s.pop()
if not is_match(top,paren):
is_balanced = False
index+=1
print("items :" +str(s.get_stack()))
# return is_balanced
if s.is_empty() and is_balanced:
return True
else:
return False
print(is_paren_balanced('[()]]'))
# elif s.is_empty() or not is_match(s.stack_top_element(),paren):
| true |
dacd4f6e242c40d72e9f5a664828d26c576d457d | Katt44/dragon_realm_game | /dragon_realm_game.py | 1,195 | 4.1875 | 4 | import random
import time
# having the user pick between to caves, that randomly are friendly or dangerous
# printing text out slowly for suspense in checking the cave
# asking user if they want to play again
def display_intro():
print ('''Standing at the mouth of a cave you take one long inhale
and you exhale as you pass through the threshold.
The cave up ahead forks but both paths are damp, seeming to breathing, and onimnious. ''')
def choose_a_cave():
cave = ""
# i need help here
while cave != '1' and cave != '2': # what does this mean
cave = raw_input(("Do you go left or right?(1,2)"))
#
return cave
def check_cave(chosen_cave):
print (" The once narrow cave expands sharply..")
time.sleep(2)
print ("In the pitch black, you feel a rush of hot foul smelling air hit you.. ")
time.sleep(2)
friendly_cave = random.randint(1,2)
if chosen_cave == str(friendly_cave):
print(" dragon likes you ")
else:
print ("dragon eats you")
#def play_again():
play_again = "yes"
while play_again == "yes" or play_again == "y":
display_intro()
cave_number = choose_a_cave()
check_cave(cave_number)
play_again =raw_input("Do you want to play again?(yes or no)") | true |
9cea2b8c8abb1262791201e1d03b12e2684673ea | gsandoval49/stp | /ch5_lists_append_index_popmethod.py | 712 | 4.25 | 4 | fruit = ["Apple", "Pear", "Orange"]
fruit.append("Banana")
fruit.append("Tangerine")
#the append will always store the new at the end of the list
print(fruit)
#lists are not limited to storing strings
# they can store any data type
random = []
random.append(True)
random.append(100)
random.append(1.0)
random.append("hello")
print(random)
# i can use an index to retrieve it's place in a list
print(fruit[1])
### if you try to access an index that doesn't exist, python raises this exception
# print(fruit[8])
# you can change an item in a list by assigning it sindex to a new object
fruit[2] = 'kiwi'
print(fruit)
# you can remove the last item from a list using pop method
fruit.pop()
print(fruit)
| true |
cf8f18ec1b0e9ae0ee1bfce22be037b352681437 | afialydia/Intro-Python-I | /src/13_file_io.py | 982 | 4.1875 | 4 | """
Python makes performing file I/O simple. Take a look
at how to read and write to files here:
https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files
"""
# Open up the "foo.txt" file (which already exists) for reading
# Print all the contents of the file, then close the file
# Note: pay close attention to your current directory when trying to open "foo.txt"
# YOUR CODE HERE
def fooTest():
with open("./src/foo.txt") as fooOpen:
openfoo = fooOpen.read()
print(openfoo)
fooTest()
# Open up a file called "bar.txt" (which doesn't exist yet) for
# writing. Write three lines of arbitrary content to that file,
# then close the file. Open up "bar.txt" and inspect it to make
# sure that it contains what you expect it to contain
# YOUR CODE HERE
bars = ["Test me", "Twice" ,"Thrice"]
def barTest():
with open("bar.txt","w") as f:
for bar in bars:
f.write(bar)
f.write("\n")
barTest() | true |
d15f9b28307a2180cd2a1e7d6a6c7cf9deb6d85c | zuwannn/Python | /Tree based DSA/PerfectBinaryTree.py | 1,382 | 4.28125 | 4 | # perfect binary tree
'''
A perfect binary tree เป็น binary tree ชนิดหนึ่ง
โดยที่ทุกโหนดภายใน (internal node) ต้องมีโหนดย่อยสองโหนด
และ(leaf nodes) ทั้งหมดอยู่ในระดับเดียวกัน
'''
class Node:
def __init__(self, k):
self.k = k
self.right = self.left = None
# Calculate the depth
def calculateTheDepth(node):
depth = 0
while (node is not None):
depth += 1
node = node.left
return depth
# check if the tree is perfect binary tree
def isPerfect(root, depth, level=0):
# check if the tree is empty
if(root is None):
return True
# check the presence of trees
if(root.left is None and root.right is None):
return (depth == level+1)
if(root.left is None or root.right is None):
return False
return (isPerfect(root.left, depth, level+1) and
isPerfect(root.right, depth, level+1))
if __name__=="__main__":
root = None
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
if (isPerfect(root, calculateTheDepth(root))):
print("the tree is a perfect binary tree")
else:
print("the tree is not a perfect binary tree") | false |
c48dcb189abf82abb6bee0cac9b92777b6ab1380 | zuwannn/Python | /Tree based DSA/TreeTraversal.py | 1,029 | 4.21875 | 4 | # tree traversal - in-order, pre-order and post-order
class Node:
def __init__(self, item):
self.left = None
self.right = None
self.value = item
# left -> root -> right
def inorder(root):
if root:
# traverse left
inorder(root.left)
# traverse root
print(str(root.value), end=" ")
# traverse right
inorder(root.right)
# root -> left -> right
def preorder(root):
if root:
print(str(root.value), end=" ")
preorder(root.left)
preorder(root.right)
# left -> right -> root
def postorder(root):
if root:
postorder(root.left)
postorder(root.right)
print(str(root.value), end=" ")
if __name__ == "__main__":
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print("inorder traversal")
inorder(root)
print("\npreorder traversal")
preorder(root)
print("\npostorder traversal")
postorder(root) | true |
e367ed81791d2dfc42e60202b1c12e8d75d47de8 | zuwannn/Python | /Tree based DSA/binary_tree.py | 1,362 | 4.21875 | 4 | #Binary Tree
"""
Tree represents the nodes connected by edges(Left Node & Right Node). It is a non-linear data structure.
-One node is marked as Root node.
-Every node other than the root is associated with one parent node.
-Each node can have an arbiatry number of chid node.
We designate one node as root node and then add more nodes as child nodes.
"""
# this function present inorder traversal
class Node:
#create Root
def __init__(self, data):
self.left = None
self.right = None
self.data = data
#insert node
def insert(self, data):
#compare the new value with the parent
if self.data:
if data < self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
elif data > self.data:
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
else:
self.data = data
#print tree
def PrintTree(self):
if self.left:
self.left.PrintTree()
print(self.data,end=" ")
if self.right:
self.right.PrintTree()
# use insert method to add nodes
root = Node(10)
root.insert(6)
root.insert(14)
root.insert(3)
root.PrintTree()
| true |
eac9eea7860abcb3474cfa2c4599b31c3e2a0af1 | ayushiagarwal99/leetcode-lintcode | /leetcode/breadth_first_search/199.binary_tree_right_side_view/199.BinaryTreeRightSideView_yhwhu.py | 1,597 | 4.125 | 4 | # Source : https://leetcode.com/problems/binary-tree-right-side-view/
# Author : yhwhu
# Date : 2020-07-30
#####################################################################################################
#
# Given a binary tree, imagine yourself standing on the right side of it, return the values of the
# nodes you can see ordered from top to bottom.
#
# Example:
#
# Input: [1,2,3,null,5,null,4]
# Output: [1, 3, 4]
# Explanation:
#
# 1 <---
# / \
# 2 3 <---
# \ \
# 5 4 <---
#####################################################################################################
class Solution:
def rightSideView_bfs(self, root: TreeNode) -> List[int]:
res = []
if not root:
return res
queue = deque()
queue.append(root)
while queue:
is_first = True
for _ in range(len(queue)):
node = queue.popleft()
if is_first:
res.append(node.val)
is_first = False
if node.right:
queue.append(node.right)
if node.left:
queue.append(node.left)
return res
def rightSideView_dfs(self, root: TreeNode) -> List[int]:
res = []
self._dfs(res, 0, root)
return res
def _dfs(self, res, step, node):
if not node:
return
if len(res) == step:
res.append(node.val)
self._dfs(res, step + 1, node.right)
self._dfs(res, step + 1, node.left)
| true |
ebe8b1f54b32754316095c4e8f979c19f2b01e3e | rodrilinux/Python | /Python/_3.1-chamadaDeFuncao.py | 929 | 4.40625 | 4 | # coding: iso-8859-1_*_
# Voc j viu um exemplo de uma chamada de funo:
# >>> type(32)
# <class str>
# O nome da funo type e ela exibe o tipo de um valor ou varivel. O valor ou varivel, que chamado de
# argumento da funo, tem que vir entre parnteses. comum se dizer que uma funo recebe um valor ou mais
# valores e retorna um resultado. O resultado chamado de valor de retorno.
# Em vez de imprimir um valor de retorno, podemos atribui-lo a uma varivel:
s = type('32')
print('O valor de s do tipo:' , s)
n = type(10)
print('O valor de n do tipo:' ,n)
f = type(3.14159)
print('O valor de f do tipo:' ,f)
# Como outro exemplo, a funo id recebe um valor ou uma varivel e retorna um inteiro, que atua como um identificador
# nico para aquele valor:
identificador = id (3)
print('O id de 3 :' , identificador)
eu = identificador
print(eu)
| false |
d0a5e8fdbdaec96173164faf66143bfac359b689 | MarcoHuXHu/learningpython | /Algorithm/Heap.py | 1,541 | 4.15625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 如果一颗完全二叉树中, 每个父节点的值都大于等于(或者都小于等于)其左右子节点的值, 这样的完全二叉树称为堆.
# 此处以一个小根堆为例(即父节点的值小于等于左右子节点的值)
# 堆的插入, 弹出(删除根节点), 以及利用堆进行排序
class Heap(object):
def __init__(self):
self.data = []
def swap(self, indexA, indexB):
y = self.data[indexA]
self.data[indexA] = self.data[indexB]
self.data[indexB] = y
def add(self, value):
self.data.append(value)
# 上浮
c = len(self.data) - 1
p = (c - 1) // 2
while self.data[p] > self.data[c]: # 大根堆此处为<
self.swap(c, p)
c = p
p = (p - 1) // 2
def pop(self):
self.swap(0, len(self.data) - 1)
value = self.data.pop()
length = len(self.data)
# 下沉
p = 0
while (p * 2 + 1) < length:
c = p * 2 + 1
if ((p * 2 + 2) < length) and (self.data[p * 2 + 1] > self.data[p * 2 + 2]): # 大根堆此处为<
c = p * 2 + 2
if self.data[p] > self.data[c]: # 大根堆此处为<
self.swap(p, c)
p = c
else:
break
return value
def heapSort(l):
heap = Heap()
for i in l:
heap.add(i)
for i in l:
print(heap.pop(), end=" ")
heapSort([1,4,3,2,7,5,6,9,3])
| false |
331ba25d4f34c30d1ac418c0d05a0b9b1cce35bb | MarcoHuXHu/learningpython | /Function/filter.py | 1,520 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# filter传入一个返回True或False的函数,与一个Iterable对象,返回经过函数筛选为True的元素
# filter返回为iterator
def is_odd(n):
return n % 2 == 1
print(list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15])))
# 结果: [1, 5, 9, 15]
# 例1:筛选回文数
def is_palindrome(n):#0123456
digits = str(n)
length = len(digits)
for i in range(length//2):
if digits[i] != digits[length-i-1]:
return False
return True
print(list(filter(is_palindrome, range(100, 999))))
# 例2:筛选素数
# 方法1:直接筛选法
import math
def is_not_divisible(n):
def func(x):
return (x==n) or (x%n) > 0 # x==n 这个条件是为了方法1准备的,以免把素数本身筛选掉了,方法2中不需要这个
return func
def prime_number(n):
primes = range(2, n+1)
i = 2
for i in range(2, int(math.sqrt(n))):
primes = filter(is_not_divisible(i), primes)
print(list(primes))
prime_number(100)
# 方法2:素数生成器,可以产生无限序列
# 先定义一个初始iterator,生成奇数(素数除了2都是奇数)
def init_iter():
n = 1
while True:
n = n + 2
yield n
# 素数生成器
def prime_iter():
it = init_iter()
yield 2
while True:
n = next(it)
yield n
it = filter(is_not_divisible(n), it)
for i in prime_iter():
if (i < 100):
print(i, end=", ")
else:
break | false |
3e75a6666d33bc5965ff3df6d54f7eef487a9900 | sammienjihia/dataStractures | /Trees/inOrderTraversal.py | 2,293 | 4.15625 | 4 | class Node:
def __init__(self, val):
self.val = val
self.rightchild = None
self.leftchild = None
def insert(self, node):
# compare the data val of the nodes
if self.val == node.val:
return False
if self.val > node.val: # make the new node the left child of this
if self.leftchild: # check if the left child has a left child
self.leftchild.insert(node)
else:
self.leftchild = node
else:
if self.rightchild:
self.rightchild.insert(node)
else:
self.rightchild = node
return True
class Tree:
def __init__(self):
self.root = None
def insert(self, data):
if self.root: # Check whether the tree has a root node
return self.root.insert(Node(data))
else: # if it doesn't make it the root node
self.root = Node(data)
return True
# create a BST
bst = Tree()
items = [5,3,6,1,4,7,8,9,2,0]
for item in items:
print(bst.insert(item))
##############################################
# #
# INODER TRAVERSAL #
##############################################
ml = []
def inOrderTraversal(root_node):
if root_node == None:
return
inOrderTraversal(root_node.leftchild)
ml.append(root_node.val)
inOrderTraversal(root_node.rightchild)
return ml
print(inOrderTraversal(bst.root))
def inOrderTraversalIterative(root_node):
my_stack = [] # add to stack all the left children of the tree.
my_stack.append(root_node)
# first step is to add the root's left child/children
while root_node or len(my_stack):
root_node = root_node.leftchild if root_node != None else root_node
if root_node == None and len(my_stack):
# pop the stack, print it and make the right child of the current root node to be the root_node
node = my_stack.pop()
print(node.val)
root_node = node.rightchild
if root_node:
my_stack.append(root_node)
elif root_node != None:
my_stack.append(root_node)
inOrderTraversalIterative(bst.root) | true |
6cc412ee2ed4e71fd9aff6409db2434a64735ec2 | Chuxiaxia/python | /hm_10_列表基本使用.py | 955 | 4.21875 | 4 | name_list = ["xey", "ajl", "xx"]
# 1. 取值和取索引
print (name_list[2])
# 知道数据的内容,想确定数据在列表的位置
# 使用index方法需要注意,如果传递的数据不在列表中,程序会报错。
print(name_list.index("xey"))
# 2. 修改
# 注意: 列表指定的索引超出范围,程序会报错
name_list[1] = "安家樑"
# 3. 增加
# append方法可以向列表末尾增加数据
name_list.append("夏夏")
# insert方法可以在列表的指定索引位置插入数据
name_list.insert(1, "an")
# extend方法可以把另外一个列表中的完整内容追加在当前列表的末尾
temp_list = ["xu", "jiujiu"]
name_list.extend(temp_list)
# 4. 删除
# remove方法可以移除列表中任意一个数据
name_list.remove("xu")
# clear可以清空列表
name_list.clear()
# pop默认删除列表最后一个元素
name_list.pop()
# pop可以指定删除元素的索引
name_list.pop(1)
print (name_list) | false |
20ce3fc899aa6766a27dfe73c6dd0c14aa3d4099 | Julien-Verdun/Project-Euler | /problems/problem9.py | 711 | 4.3125 | 4 | # Problem 9 : Special Pythagorean triplet
def is_pythagorean_triplet(a,b,c):
"""
This function takes 3 integers a, b and c and returns whether or not
those three numbers are a pythagorean triplet (i-e sum of square of a and b equel square of c).
"""
return a**2 + b**2 == c**2
def product_pythagorean_triplet(N):
"""
This function returns 3 numbers, if they exist, such that, all 3 numbers are lesser than N, their sum equals
1000, and they are pythagorean numbers.
"""
for a in range(0,N):
for b in range(a+1,N):
for c in range(b+1,N):
if a+b+c == 1000 and is_pythagorean_triplet(a,b,c):
return a*b*c
return "N too small"
print(product_pythagorean_triplet(500))
# Resultat 31875000 | true |
ccee97b325a717c7031159ee1c4a7569ff0675d6 | digant0705/Algorithm | /LeetCode/Python/274 H-Index.py | 1,647 | 4.125 | 4 | # -*- coding: utf-8 -*-
'''
H-Index
=======
Given an array of citations (each citation is a non-negative integer) of a
researcher, write a function to compute the researcher's h-index.
According to the definition of h-index on Wikipedia: "A scientist has index h
if h of his/her N papers have at least h citations each, and the other N − h
papers have no more than h citations each."
For example, given citations = [3, 0, 6, 1, 5], which means the researcher has
5 papers in total and each of them had received 3, 0, 6, 1, 5 citations
respectively. Since the researcher has 3 papers with at least 3 citations each
and the remaining two with no more than 3 citations each, his h-index is 3.
Note: If there are several possible values for h, the maximum one is taken as
the h-index.
'''
class Solution(object):
'''算法思路:
将数组按照从大到小的顺序排序,然后从前往后遍历直到 index > 当前的 citation 值
Time: O(n*log(n))
'''
def hIndex(self, citations):
for i, num in enumerate(sorted(citations), 1):
if num < i:
return i - 1
return len(citations)
class Solution(object):
'''算法思路:
由于 h-index <= 数组的长度, 因此可以利用 couting sort
Time: O(n)
'''
def hIndex(self, citations):
n = len(citations)
count = [0] * (n + 1)
for num in citations:
count[min(n, num)] += 1
r = 0
for i in xrange(n, 0, -1):
r += count[i]
if r >= i:
return i
return 0
s = Solution()
print s.hIndex([3, 0, 6, 1, 5])
| true |
e8163d4faddd7f6abeacdea9c6ebbb86a57dd195 | digant0705/Algorithm | /LeetCode/Python/328 Odd Even Linked List.py | 1,532 | 4.28125 | 4 | # -*- coding: utf-8 -*-
'''
Odd Even Linked List
====================
Given a singly linked list, group all odd nodes together followed by the even
nodes. Please note here we are talking about the node number and not the value
in the nodes.
You should try to do it in place. The program should run in O(1) space
complexity and O(nodes) time complexity.
Example:
Given 1->2->3->4->5->NULL,
return 1->3->5->2->4->NULL.
Note:
- The relative order inside both the even and odd groups should remain as it
was in the input.
- The first node is considered odd, the second node even and so on ...
'''
class Solution(object):
'''算法思路:
用两个指针分别把奇偶串起来,然后连接起来即可
'''
def oddEvenList(self, head):
oddHead = oddTail = ListNode(None)
evenHead = evenTail = ListNode(None)
cnt = 1
while head:
if cnt & 1:
oddTail.next = oddTail = head
else:
evenTail.next = evenTail = head
head = head.next
cnt += 1
evenTail.next, oddTail.next = None, evenHead.next
return oddHead.next
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def __repr__(self):
return str(self.val)
a = ListNode(1)
b = ListNode(2)
c = ListNode(3)
d = ListNode(4)
e = ListNode(5)
a.next = b
b.next = c
c.next = d
d.next = e
s = Solution()
head = s.oddEvenList(a)
while head:
print head,
head = head.next
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.