blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
4841b02ca8b7361afb187483155db55eaa517979 | m-01101101/udacity-datastructures-algorithms | /4. recursion/tower_of_hanoi.py | 2,674 | 4.4375 | 4 | """
The Tower of Hanoi is a puzzle where we have three rods and n unique sized disks.
The three rods are - source, destination, and auxiliary (which sits between the other two)
The object is to move all the disk from source to destination.
The rules applicable to all rods;
1. Only one disk can be moved at a time.
2. A disk can be moved only if it is on the top of a rod.
3. No disk can be placed on the top of a smaller disk.
You will be given the number of disks num_disks as the input parameter.
Write a recursive function tower_of_Hanoi()
that prints the "move" steps in order to move num_disks number of disks
from Source to Destination using the help of Auxiliary rod.
Assume the disks are stacks currently from smallest first to largest at the bottom of a stack
You have to re-stack them and then move onto destination
"""
def tower_of_Hanoi(num_disks):
"""
:param: num_disks - number of disks
d1 # | |
d2 ### | |
d3 ##### | |
d4 ####### | |
1 2 3
move (dn, current, target, other) ->
- move(dn - 1, current, other, target)
- dn -> target
- move(dn - 1, other, current, target)
"""
return tower_of_Hanoi_func(
num_disks,
source=[d for d in range(1, num_disks + 1)][::-1],
auxiliary=[],
destination=[],
)
def tower_of_Hanoi_func(num_disks, source, auxiliary, destination):
if num_disks == 1: # base case
destination.append(source.pop())
print("S", "D")
else:
if num_disks % 2 != 0:
auxiliary.append(source.pop())
print("S", "A")
auxiliary = destination + auxiliary
print("D", "A") if len(destination) > 0 else None
destination = []
elif num_disks % 2 == 0:
destination.append(source.pop())
print("S", "D")
destination = auxiliary + destination
print("A", "D") if len(auxiliary) > 0 else None
auxiliary = []
return tower_of_Hanoi_func(num_disks - 1, source, auxiliary, destination)
return source, auxiliary, destination
# Udacity solution
def tower_of_Hanoi_soln(num_disks, source, auxiliary, destination):
if num_disks == 0:
return
if num_disks == 1:
print("{} {}".format(source, destination))
return
tower_of_Hanoi_soln(num_disks - 1, source, destination, auxiliary)
print("{} {}".format(source, destination))
tower_of_Hanoi_soln(num_disks - 1, auxiliary, source, destination)
def tower_of_Hanoi(num_disks):
tower_of_Hanoi_soln(num_disks, "S", "A", "D")
| true |
39f4963df458a609aaa1e6287253685bcf859e0b | m-01101101/udacity-datastructures-algorithms | /4. recursion/staircase.py | 1,306 | 4.21875 | 4 | """
Problem Statement
Suppose there is a staircase that you can climb in either 1 step, 2 steps, or 3 steps.
In how many possible ways can you climb the staircase if the staircase has n steps?
Write a recursive function to solve the problem.
Example:
n == 1 then answer = 1
n == 3 then answer = 4
The output is 4 because there are four ways we can climb the staircase:
1 step + 1 step + 1 step
1 step + 2 steps
2 steps + 1 step
3 steps
n == 5 then answer = 13
"""
"""
param: n - number of steps in the staircase
Return number of possible ways in which you can climb the staircase
"""
# not right
def staircase(n):
if n == 1:
return 1
else:
output = 0
for i in range(1, n):
# output.append([i % n + 1] * (n + 1 // i))
# output.append([i % n] * (n // i))
output += n // (i % n)
staircase(n - 1)
return output
def udacity_staircase(n):
"""
:param: n - number of steps in the staircase
Return number of possible ways in which you can climb the staircase
"""
if n == 0:
return 1
elif n < 0:
return 0
else:
climb_ways = 0
climb_ways += staircase(n - 1)
climb_ways += staircase(n - 2)
climb_ways += staircase(n - 3)
return climb_ways
| true |
02a89b26e052ce4632772d3f8e161640470b242c | haoshou/python_base | /second/number.py | 538 | 4.21875 | 4 | # 数字
# 1.整数
# 在Python中,可对整数执行加(+)减(-)乘(*)除(/)运算
data = 2 + 3
data = 3 - 2
data = 3 * 2
data = 3 / 2
print(data)
# 在终端会话中,Python直接返回运算结果。Python使用两个乘号表示乘方运算:
data = 3 ** 2
print(data)
# 2.浮点数 Python将带小数点的数字都称为浮点数。
data = 0.1 + 0.2
print(data)
# 3.使用函数 str()避免类型错误
age = 23
# 需要将数字转为字符串
message = "Happy" + str(age) + "Birthday"
print(message)
| false |
5231fb0aa9a33543fa839ffb938463c71e605fa1 | suhasini-viswanadha/basic-programs | /venv/find_circle_area_perimeter_keyboard_input.py | 244 | 4.25 | 4 | """Program to find area and perimeter of a circle by taking input from keyboard"""
pie=3.14
r=input("enter a value for radius")
a=int(r)
area=pie*a*a
b=float(area)
print(b)
#finding perimeter of a circle
perimeter=2*pie*a
print(perimeter)
| true |
5ad626f1da24e29f9b8f1b56c599afeca1ca4902 | CodeProgress/Useful_Methods | /avoidMaxRecursionDepth.py | 640 | 4.21875 | 4 |
def fact(x):
"""fact_recursive rewritten using a while True loop
to avoid reaching max recursion depth
tail recursion optimization
"""
ans = 1
while True:
if x <= 1:
return ans
x, ans = x - 1, x * ans
def fact_recursive(x):
if x <= 1:
return 1
return x * fact_recursive(x - 1)
def fact_iter(x):
ans = 1
while x > 1:
ans *= x
x -= 1
return ans
assert fact(10000) == fact_iter(10000)
#fact_recursive( 10000 )
#will reach max recursion depth after 1000 calls
#unless depth manually changed:
#import sys
#sys.setrecursionlimit( newMaxDepth )
| true |
6f28c6a408f7d2f371089d11cd239f26bbd08674 | jeremybwilson/codewars-python | /iq_test.py | 1,916 | 4.40625 | 4 | # IQ Test
"""
Bob is preparing to pass IQ test.
The most frequent task in this test is to find out which one of the given numbers differs from the others.
Bob observed that one number usually differs from the others in evenness.
Help Bob - to check his answers, he needs a program that among the given numbers
finds one that is different in evenness, and return a position of this number.
Keep in mind that your task is to help Bob solve a real IQ test,
which means indexes of the elements start from 1 (not 0)
"""
def iq_test(string):
#your code here
numbers = string.split()
noOdds = 0
noEvens = 0
position = 0
# for i in range from 0 to length of given numbers
for i in range (0, len(numbers)):
# if the integer value of index is even
if(int(numbers[i]) % 2 == 0):
# increment noEvens count + 1
noEvens = noEvens + 1
else:
# otherwise increment noOdds count + 1
noOdds = noOdds + 1
if(noOdds > noEvens):
# for i in range from 0 to length of given numbers
for i in range(0, len(numbers)):
# if the integer value of index is even
if (int(numbers[i]) % 2 == 0):
# set the position count to the index value + 1
position = i+1
else:
# for i in range from 0 to length of given numbers
for i in range(0, len(numbers)):
# if the integer value of index is even
if (int(numbers[i]) % 2 != 0):
# set the position count to the index value + 1
position = i+1
return position
print iq_test("2 4 7 8 10") #=> 3 // Third number is odd, while the rest of the numbers are even
print iq_test("1 2 1 1") # => 2 // Second number is even, while the rest of the numbers are odd
def iq_test_v2(numbers):
e = [int(i) % 2 == 0 for i in numbers.split()]
return e.index(True) + 1 if e.count(True) == 1 else e.index(False) + 1
print iq_test_v2("2 4 7 8 10")
print iq_test_v2("1 2 1 1") | true |
edf169d55fcb2883c8f254dfa61ee350e85bb85f | hammad-shaikh/Python-Basic | /Story Game/main.py | 617 | 4.125 | 4 |
print("Welcome to Treasure Island.")
print("Your mission is to find the treasure.")
input("Where would you like to go "Left" or "Right"")
if input == "Left".lower():
print("Good! How do you go?")
if input("What do you want to do Swim or Wait?") == "Wait":
print("Now you got there doors, which one would you like to choose")
if input("Which door") == "Yellow":
print("You Win")
else:
print("Game over")
else:
print("Game Over")
#if step_2 == "Wait" or step_2.lower() == "wait":
# print("Wow, now you got two doors, which one do you get?")
| true |
368885545c1b2281d8c3596f58ff0dfb1b1af390 | IdeaventionsAcademy7/chapter-1-part-1-beginnings-GoogleIsTerrible | /ch1_17.py | 491 | 4.25 | 4 | # Name
# Problem #
# Chapter 1 Problem Set Part 1
while(True):
a = input("Enter a number: ")
a_int = int(a)
a_float = float(a)
print(a, a_int, a_float)
#If you input something that isn't an integer
#(Any positive counting numbers and their negative oposites),
#It will spit out an error on the conversion of an integer
#Anything can be converted into a string
#Any positive counting numbers and their negative oposites, not including when you add ".0" at the end, will work.
| true |
74984ea657729ff3c08b8fcc48173cca330cea5e | Williesmith228/LeetCode | /array/88_merge_sorted_array.py | 456 | 4.125 | 4 | # !/usr/local/bin/python3
# -*- coding:utf-8 -*-
#***************************************#
# Author: zilong.wu@aispeech.com
# Created: 2020-06-09 06:50:55
# Last modified: 2020-06-09 06:50:55
# Filename: 88_merge_sorted_array.py
# Copyright © Aispeech
#***************************************#
def mergeSortedArray(nums1, m, nums2, n):
nums1[:] = nums1[:m] + nums2
return sorted(nums1)
print(mergeSortedArray([1,2,4], 3, [3,8,9], 3))
| false |
2aa348ee0110788dc3aa3003c3a9d2bc7eea9c8b | IESJacaranda/FranArroyo1DAW | /Bucles2/Bucles2/Ejercicio8-1.py | 1,279 | 4.25 | 4 | '''
8.Design a program that asks for a set of numbers. After inputting each number,
theprogram should ask “Do you want to enter more numbers (Y/N)?”.
If the answer is “Y”the program asks for other numbers.
When the user finishes to enter all the numbers,the program should say which one is the smallest.
The messages are the following:
“Enter one number:”
“Do you want to enter more number (Y/N)?”
“The smallest number is XX”'''
'''
'''
i=0
nummaschico=0
def introduccionnums():
numaintroducir=int(input("Introduce el numero a introducir"))
if numaintroducir<0:
print("EL numero no te vale bro")
introduccionnums()
return numaintroducir
def introducciondenums (numaintroducir):
if numaintroducir<0:
num=int(input("Introduce un numero"))
if num<0:
print("Ese numero no te vale bro")
introducciondenums(numaintroducir)
if num>0:
i+=1
if nummaschico<num:
nummaschico=num
introducciondenums(numaintroducir)
else:
introducciondenums(numaintroducir)
return nummaschico
def principal ():
introducccionnums()
introducciondenums(numaintroducir)
return nummaschico
print(principal) | true |
6a0616e5c714c49762fffb005c45472a03bf73b0 | IESJacaranda/FranArroyo1DAW | /bletin31/Ejercicio6.py | 597 | 4.125 | 4 | '''
Design a method called numberOfNumbers that receives one integer positive number as parameter.
The method should return the number of digits of the number that received by parameter.
If the parameter is not valid the method should return -1.
'''
def numberofnumbers(numbers):
i=0
if numbers<0:
return -1
else:
while (i!=numbers):
num=int(input("Introduce un numero"))
while num<0:
print("Solo numeros positivos")
num=int(input("Introduce un numero"))
i=+1
return i
print(numberofnumbers(2)) | true |
621b6993754277ef58198d59e24cca3e10e8da8b | atishjain9/Python_Practice | /ch3/14_customerbill.py | 766 | 4.3125 | 4 | #Program to Generate Bill for the customer
cost=int(input("Enter Cost of the Mobile...:"))
mode=input("Are You Paying cash(y/n):")
discount=extra=0
if mode=="y" or mode=="Y":
discount=cost*25/100
billamt=cost-discount
elif mode=="n" or mode=='N':
days=int(input("In How Many Days Will you Pay...:"))
if(days<7):
discount=cost*15/100
billamt=cost-discount
else:
extra=cost*10/100
billamt=cost+extra
else:
print("Please Provide Correct Input...")
if discount>0:
print("Discount Amount is:",discount)
print("Final Bill Amount is:",billamt)
elif extra>0:
print("Extra Amount is:",extra)
print("Final Bill Amount is:",billamt)
else:
print("No Bill to Generate") | true |
4733c1be948331ca739cec1efa517a0d75611bc5 | atishjain9/Python_Practice | /ch5/04_find_space.py | 222 | 4.1875 | 4 |
# Program to Detect double space from the inputted string
str=input("Enter a string....:")
pos=str.find(" ")
if pos>0:
print("Double Space found at Index %d "%pos)
else:
print("Double Space not Found") | true |
6f933d4f6da5cfb7ae779200d0e6ee96f3d37efb | mkgeorgiev/python_foundamentals_SoftUni | /Functions - Exercise/03. Characters in Range.py | 421 | 4.125 | 4 | character_1 = input()
character_2 = input()
def character_to_asci_number(a):
number_1_in_asci_table = ord(a)
return number_1_in_asci_table
first_number = character_to_asci_number(character_1)
second_number = character_to_asci_number(character_2)
for numbers in range(first_number+1, second_number):
if numbers < second_number-1:
print(chr(numbers), end =" ")
else:
print(chr(numbers))
| false |
d34ee572cd88f2a340fbf727fd2e65e526dd29ee | eking2/rosalind | /bins.py | 1,581 | 4.1875 | 4 | from pathlib import Path
def binary_search(to_search, val):
'''
1. input sorted array and value to search for
2. check middle element in array
- if match then return the middle index
3. if no match then compare middle element to target value to determine
which side to check next
- get first occurence by going backward on match
4. repeat until match or no more elements to check
'''
# start and end idx
first = 0
last = len(to_search) - 1
while (first <= last):
# get index of middle element
mid = (first + last) // 2
# val greater than mid, go right
if to_search[mid] < val:
first = mid + 1
# val less than mid, go left
elif to_search[mid] > val:
last = mid - 1
# get first occurence
# on match set end to current and check from first
elif first != mid:
last = mid
# 1-index solution
else:
return mid + 1
# no match
return -1
def bins():
# perform binary search
# find index for all vals in to_search
# return -1 if not found
n, m, to_search, vals = Path('data/rosalind_bins.txt').read_text().splitlines()
to_search = list(map(int, to_search.split()))
vals = list(map(int, vals.split()))
assert int(n) == len(to_search)
assert int(m) == len(vals)
results = [binary_search(to_search, val) for val in vals]
print(' '.join(map(str, results)))
#Path('bins_out.txt').write_text(' '.join(map(str, results)))
bins()
| true |
82ec6e5cd5be10df247461ebf0b8188eb43835eb | RAZAKNUR/PYTHON | /loopPractice.py | 937 | 4.21875 | 4 | import time
#Repeated steps with sleep delay
n = 10
while n > 0:
print(n)
n = n - 1
time.sleep(1)
print('Blastoff!')
#Simple definite loop and iteration variable with integers or strings
friends = ['Joey', 'Zoey', 'Chloe']
for x in [3, 2, 1] :
print(x)
time.sleep(1)
for friends in friends :
print('Happy new year, ',friends, '!')
#Infinite loop
while True:
print ('loop')
print('this print will never happen')
#Breaking out of loop and finishing an iteration with continue
while True:
line = input('> ')
if line == 'Stoppu!' :
break
else:
print("Wot, m8?")
continue
print(line)
print('I stopped!')
#Loop to find largest value
largest_so_far = 0
print('Before', largest_so_far)
for num in [2, 7, 3, 4, 8, 5] :
if num > largest_so_far :
largest_so_far = num
print(largest_so_far, num) #print so we can see the process
print('after', largest_so_far)
| true |
8a00221c84e824a6ef6b6d97db4392ec9eeaab08 | ptanoop/LearnPython3 | /fibonacci_seq.py | 421 | 4.3125 | 4 | # Fibonacci Sequence
"""
Author : ANOOP P T
Date : 23/06/2014
Problem : Enter a number and have the program generate the Fibonacci
sequence to that number or to the Nth number.
"""
try:
nth = int(input("Enter limit : "))
a = 1
b = 0
c = 0
for n in range(0,nth):
c = a + b
print(c)
a = b
b = c
except ValueError:
print("Invalid input")
| true |
a4c024e25e400079cacaaf0fa98cad485ac8d357 | andickinson/Practical-Ethical-Hacking | /Python/script.py | 2,630 | 4.125 | 4 | #!/bin/python3
# Variables and Methods
quote = "All is fair in love and war."
print(quote.upper()) # uppercase
print(quote.lower()) # lowercase
print(quote.title()) # title case
print(len(quote)) # string length
name = "Andrew" # String
age = 32 # int int(32)
GPA = 3.8 # float float(3.8)
print(int(age))
print(int(30.9))
print("My name is " + name + " and I am " + str(age) + " years old.")
age += 1
print(age)
birthday = 1
age += birthday
print(age)
print('\n')
# Functions
print("Here is an example function:")
def who_am_i(): # this is a function
name = "Andrew"
age = "32"
print("My name is " + name + " and I am " + str(age) + " years old.")
who_am_i()
# adding parameters
def add_one_hundred(num):
print(num + 100)
add_one_hundred(100)
# multiple parameters
def add(x, y):
print(x + y)
add(7, 7)
def multiply(x, y):
return x * y
print(multiply(7, 7))
def square_root(x):
print(x ** 0.5)
square_root(64)
def nl():
print('\n')
nl()
# Boolean expressions
print("Boolean expressions:")
bool1 = True
bool2 = 3*3 == 9
bool3 = False
bool4 = 3*3 != 9
print(bool1, bool2, bool3, bool4)
print(type(bool1))
nl()
# Relational and Boolean operators
greater_than = 7 > 5
less_than = 5 < 7
greater_than_equal_to = 7 >= 7
less_than_equal_to = 7 <= 7
test_and = (7 > 5) and (5 < 7) # True
test_and2 = (7 > 5) and (5 > 7) # False
test_or = (7 > 5) or (5 < 7) # True
test_or2 = (7 > 5) or (5 > 7) # True
test_not = not True # False
nl()
# Conditional Statements
def drink(money):
if money >= 2:
return "You've got yourself a drink!"
else:
return "No drink for you!"
print(drink(3))
print(drink(1))
def alcohol(age, money):
if (age >= 21) and (money >= 5):
return "We're getting a drink!"
elif (age >= 21) and (money < 5):
return "Come back with more money."
elif (age < 21) and (money >=5):
return "Nice try, kid!"
else:
return "You're too poor and too young."
print(alcohol(21, 5))
print(alcohol(21, 4))
print(alcohol(20, 4))
print(alcohol(20, 5))
nl()
# Lists - Have brackets []
movies = ["Coco", "Toy Story", "Up", "Soul"]
print(movies[0])
print(movies[1])
print(movies[1:4])
print(movies[1:])
print(movies[:1])
print(movies[-1])
print(len(movies))
movies.append("Wall-e")
print(movies)
movies.pop()
print(movies)
movies.pop(0)
print(movies)
nl()
# Tuples - Do not change, ()
grades = ("a", "b", "c", "d", "f")
print(grades[1])
nl()
# Looping
# For loop
vegetables = ["cucumber", "spinach", "cabbage"]
for x in vegetables:
print(x)
# While loop
i = 1
while i < 10:
print(i)
i += 1 | true |
e4bd931f2460bddd6be4306c242c64c191601b3a | Gyhhh28/cw-UCB-cs61a-18spring | /12 tree.py | 2,856 | 4.3125 | 4 | # Trees
def tree(label, branches=[]):
for branch in branches:
assert is_tree(branch), 'branches must be trees'
# print("tree: ", [label] + list(branches))
return [label] + list(branches)
def label(tree):
return tree[0]
def branches(tree):
return tree[1:]
def is_tree(tree):
print(tree, "type(tree):", type(tree))
if type(tree) != list or len(tree) < 1:
return False
for branch in branches(tree):
if not is_tree(branch):
return False
return True
def is_leaf(tree):
return not branches(tree)
### +++ === ABSTRACTION BARRIER === +++ ###
def fib_tree(n):
"""Construct a Fibonacci tree.
>>> fib_tree(1)
[1]
>>> fib_tree(3)
[2, [1], [1, [0], [1]]]
>>> fib_tree(5)
[5, [2, [1], [1, [0], [1]]], [3, [1, [0], [1]], [2, [1], [1, [0], [1]]]]]
"""
if n == 0 or n == 1:
return tree(n)
else:
left = fib_tree(n-2)
right = fib_tree(n-1)
fib_n = label(left) + label(right)
return tree(fib_n, [left, right])
def count_leaves(t):
"""The number of leaves in tree.
>>> count_leaves(fib_tree(5))
8
"""
if is_leaf(t):
return 1
else:
return sum([count_leaves(b) for b in branches(t)])
def leaves(tree):
"""return a list containing the leaf label of tree"""
if is_leaf(tree):
print(label(tree))
return [label(tree)] # 因为sum只能去掉一层[]
else:
return sum([leaves(b) for b in branches(tree)], []) # []很奇妙, 是做啥的??
def increment_leaves(t):
"""Return a tree like t but with leaf values tripled.
>>> print_tree(increment_leaves(fib_tree(4)))
3
1
1
2
2
2
1
1
2
"""
if is_leaf(t):
return tree(label(t) + 1)
else:
bs = [increment_leaves(b) for b in branches(t)]
return tree(label(t), bs)
def increment(t):
"""Return a tree like t but with all node values incremented.
>>> print_tree(increment(fib_tree(4)))
4
2
1
2
3
2
2
1
2
"""
# 无需区分base case!!! 因为当b为leaf时,就剩下[],所以压根没有call increment
return tree(label(t) + 1, [increment(b) for b in branches(t)])
def print_tree(t, indent=0):
"""Print a representation of this tree in which each node is
indented by two spaces times its depth from the entry.
>>> print_tree(tree(1))
1
>>> print_tree(tree(1, [tree(2)]))
1
2
>>> print_tree(fib_tree(4))
3
1
0
1
2
1
1
0
1
"""
print(' ' * indent + str(label(t)))
for b in branches(t):
# indnent 自己递增,correspond to its depth
print_tree(b, indent + 1) | false |
0d7d043efe19b403629fdca1a3e8b79f24ba9b74 | lpelczar/Algorithmic-Warm-Ups | /I-O/8_guess_the_number.py | 990 | 4.15625 | 4 | """
Write a program able to play the "Guess the number"-game, where the number to be guessed is randomly chosen between 1
and 20.
"""
import random
def guess_the_number():
number_to_guess = random.randint(1, 20)
guesses_left = 20
number_is_not_guessed = True
while number_is_not_guessed:
print(number_to_guess)
input_is_not_number = True
while input_is_not_number:
try:
user_input = int(input('Enter a number: '))
input_is_not_number = False
except ValueError:
continue
print('Guesses left: {}'.format(guesses_left))
if user_input < number_to_guess:
guesses_left -= 1
print('Your number is too low!')
elif user_input > number_to_guess:
guesses_left -= 1
print('Your number is too high!')
else:
print('Correct! You win!')
number_is_not_guessed = False
guess_the_number() | true |
a2fafbbffdde9ed22245673ec64f99028cf21504 | lpelczar/Algorithmic-Warm-Ups | /High order functions and list comprehensions/2_map.py | 509 | 4.28125 | 4 | """
Write a program that maps a list of words into a list of integers representing the lengths of the correponding words.
Write it in three different ways: 1) using a for-loop, 2) using the higher order function map(), and 3) using list
comprehensions.
"""
def words_to_length(words):
# lengths = []
# for i in words:
# lengths.append(len(i))
# return lengths
# return list(map(lambda x: len(x), words))
return [len(x) for x in words]
print(words_to_length(['hahaha', 'ha'])) | true |
0e3d8c3a231a71a9b6f9a54f34e4bc251405f43f | RoaaMustafa/data-structures-and-algorithms | /python/graph/graph/stack_and_queue.py | 2,916 | 4.25 | 4 | class Node():
def __init__(self,value=None) -> None:
"""This Function Creates Nodes """
self.value=value
self.next=None
class Stack():
def __init__(self,node=None) -> None:
self.top=node
def push(self,value=None):
""" Adding New value by assign it to head """
try:
node=Node(value)
node.next=self.top
self.top=node
except:
raise Exception('Something went wrong ')
def pop(self):
""" Remove Node From The stack and Return it """
try:
temp=self.top
self.top=self.top.next
temp.next=None
return temp.value
except:
raise Exception('The Stake Is empty ')
def is_empty(self):
"""Check if the Stack is Empty or Not """
return not self.top
def peek(self):
""" Return the Top value """
try:
return self.top.value
except:
raise Exception('The stack is Empty')
class Queue():
def __init__(self) -> None:
"""Create Queue with None Front and Rear """
self.front=None
self.rear=None
def enqueue(self,value):
"""Add Node to The Queue """
node=Node(value)
if not self.front and not self.rear:
self.front=node
self.rear=node
else:
self.rear.next=node
self.rear=node
def dequeue(self):
""" Return the Front Node From the Queue and Remove it """
try:
temp=self.front
self.front=self.front.next
temp.next=None
if self.front==None:
self.rear=None
return temp.value
except:
raise Exception("The Queue is empty")
def peek(self):
""" Return the Front Value Without Removing it """
try:
return self.front.value
except:
raise Exception("The Queue is empty")
def is_empty(self):
""" Checks if the Function it Empty of Not """
if self.front or self.rear:
return False
else:
return True
class PseudoQueue:
def __init__(self):
self.pushStack = Stack()
self.popStack = Stack()
def enqueue(self, item):
self.pushStack.push(item)
def dequeue(self):
if self.popStack.is_empty():
while self.pushStack.top != None:
print('ssss')
self.popStack.push(self.pushStack.top.value)
self.pushStack.top=self.pushStack.top.next
return self.popStack.pop()
def __str__(self):
strain=''
if __name__=="__main__":
test=PseudoQueue()
test.enqueue(7)
test.enqueue(1)
test.enqueue(2)
test.enqueue(5)
# test.dequeue()
print(test.dequeue())
print(test.dequeue())
print(test.dequeue())
print(test.dequeue())
| true |
bef13866e1a9638e0594ab519fb7e2f32b0586fa | RoaaMustafa/data-structures-and-algorithms | /python/insertion-sort/insertion_sort/insertion_sort.py | 518 | 4.125 | 4 | def insertionSort(arr):
for i in range(1,len(arr)):
j=i-1
temp=arr[i]
while j >=0 and temp < arr[j]:
arr[j+1]=arr[j]
j=j-1
arr[j + 1] =temp
return arr
arr=[8,4,23,42,16,15]
reversed_arr=[20,18,12,8,5,-2]
Few_uniques=[5,12,7,5,5,7]
Nearly_sorted=[2,3,5,7,13,11]
print(f'{arr}---->{insertionSort(arr)}')
print(f'{reversed_arr}---->{insertionSort(reversed_arr)}')
print(f'{Few_uniques}---->{insertionSort(Few_uniques)}')
print(f'{Nearly_sorted}---->{insertionSort(Nearly_sorted)}')
| false |
6efdc57d33a84eaadd35b0e4835dbca72801316a | anuraagdjain/cracking-the-coding-interview | /chapter 1 - arrays and strings/1.7.py | 460 | 4.125 | 4 | def rotate_matrix(matrix):
rows, cols = len(matrix), len(matrix[0])
if rows != cols:
print("not a square matrix")
return
result = [[0 for x in range(rows)] for y in range(cols)]
for r in range(rows):
for c in range(cols):
result[c][rows - r - 1] = matrix[r][c]
print(result)
if __name__ == "__main__":
matrix = [[1, 2, 3, 6], [4, 5, 6, 7], [7, 8, 9, 1], [11, 12, 13, 14]]
rotate_matrix(matrix)
| true |
ca3f089f534f9e3fa17369e6e8546a4e22c9b802 | karadisairam/pratice | /10.py | 345 | 4.125 | 4 | #Relational / Comparison Operators
a=3
b=3
print(a==b)
a=4
b=5
print(a!=b)
a=2
b=6
print(a>b)
a=5
b=6
print(a<b)
a=6
b=7
print(a>b)
a=8
b=7
print(a>b)
a=3
b=4
print(a<=b)
a=9
b=4
print(a<=b)
a=5
b=9
print(a>b)
a=5
b=9
print(a>=b)
a=8
b=4
print(a>b)
a=15
b=9
print(a>=b)
| false |
9e3d5d46e7ae58969d8c60e20fa243ae0607ada0 | Karthik23K/30-Days-Of-Python-2 | /Day 09 Conditionals/conditionals.py | 2,724 | 4.125 | 4 | age = int(input("Enter your age: "))
if age >= 18:
print("You are old enough to learn to drive.")
else:
print(f"You need {18-age} more years to learn to drive.")
my_age = int(input("Enter my age: "))
your_age = int(input("Enter your age: "))
if my_age > your_age:
print(f"I am {my_age-your_age} years older than you.")
elif my_age == your_age:
print("Our ages are same")
else:
print(f"You are {your_age-my_age} years older than me.")
a = int(input("Enter number one: "))
b = int(input("Enter number two: "))
if a > b:
print(f"{a} is greater then {b}")
elif a == b:
print("Both values are same")
else:
print(f"{b} is greater then {a}.")
s = int(input("Enter score: "))
if s >= 80 and s <= 100:
print("A")
elif s >= 70 and s <= 79:
print("B")
elif s >= 60 and s <= 69:
print("C")
elif s >= 50 and s <= 59:
print("C")
else:
print(F)
month = input("Enter month")
if month in ['September', 'October', 'November']:
print("Autumn")
elif month in ['December', 'January', 'February']:
print("Winter")
elif month in ['March', 'April', 'May']:
print("Spring")
elif month in ['June', 'July', 'August']:
print("Summer")
else:
print("Enter month correctly")
fruits = ['banana', 'orange', 'mango', 'lemon']
name = input("Enter a fruit")
if name not in fruits:
fruits.append(name)
print(fruits)
else:
print("That fruit already exist in the list")
person = {
'first_name': 'Asabeneh',
'last_name': 'Yetayeh',
'age': 250,
'country': 'Finland',
'is_marred': True,
'skills': ['JavaScript', 'React', 'Node', 'MongoDB', 'Python'],
'address': {
'street': 'Space street',
'zipcode': '02210'
}
}
if person.get('skills'):
if len(person['skills']) % 2 == 0:
print(person['skills'][(len(person['skills'])//2) - 1],
person['skills'][(len(person['skills'])//2)])
else:
print(person['skills'][len(person['skills'])//2])
else:
print("No Skills")
if person.get('skills'):
if 'Python' in person.get('skills'):
print("Python is one of the skills")
else:
print("No Python in skills")
else:
print("No Skills")
if person.get('skills'):
if 'Javascript' in person.get('skills') and 'React' in person.get('skills'):
print('He is a front end developer')
elif 'Node' in person.get('skills') and 'Python' in person.get('skills') and 'MongoDB' in person.get('skills'):
print('He is a backend developer')
elif 'Node' in person.get('skills') and 'React' in person.get('skills') and 'MongoDB' in person.get('skills'):
print('He is a fullstack developer')
else:
print('unknown title')
else:
print("No Skills")
| false |
2c9c828cbd94da15bda46f9ac0738c600ba81803 | dieb/algorithms.py | /algorithms/sorting/counting.py | 1,754 | 4.25 | 4 | # -*- coding: utf-8 -*-
from six.moves import range
__all__ = ('counting_sort',)
def counting_sort(array, k=None):
""" Integer sorting algorithm.
For each element in array, counts the number of elements that are less
than itself. E.g. if there are 18 elements less than element, then it
belongs on position=19 on the final array. This must be slightly modified
when there are equal values.
Analysis:
- Allocating `output`: O(n) - could be passed to the function
- Allocating `count`: O(k)
- Histogram: O(n)
- Indexes: O(k)
- Creating output: O(n)
Overall: O(k + n). When k = O(n), O(k + n) = O(n)
Complexity: O(n)
Space: O(n + k)
"""
k = max(array)
output = [None for i in range(len(array))]
count = [0 for i in range(k + 1)]
# Histogram of keys frequencies. `count[i]` contains the number of
# occurrences of i in array.
for elem in array:
count[elem] += 1
# Transform `count` into an array of indexes where each key goes.
#
# Starting from the left (index = 0), checks count[0], sets count[0] to
# index (=0), then adds to index the number of occurences of 0.
#
# When repeated, this procedure iteratively transforms `count` into an
# array where the position is the key and the position content is where to
# start adding this key.
index = 0
for i in range(k + 1):
old = count[i]
count[i] = index
index += old
# Now `count[i]` is the index where `i` must be inserted at. For every
# insertion, we update `count[i]` to be at the previous index + 1.
for elem in array:
output[count[elem]] = elem
count[elem] += 1
return output
| true |
fbfe4588119393d4be2971d525164582b4f5e80e | KevinBrack/Sorting | /project/re_merge.py | 2,435 | 4.34375 | 4 | # Reimplementing Merge Sort to help me understand the
# challenge behind in-place merge sort
# update - followed youtube vid, did not work
# def create_array(size = 10, max = 50):
# from random import randint
# return [randint(0, max) for _ in range(size)]
# def merge(a,b):
# c = [] # final output array
# a_index = b_index = 0
# # join the lists till one runs out
# while a_index < len(a) and b_index < len(b):
# if a[a_index]< b[b_index]:
# c.append(a[a_index])
# a_index += 1
# else:
# c.append(b[b_index])
# b_index += 1
# # add the list that still has items remaining to the end
# # of the result
# if a_index == len(a):
# c = c + (b[b_index:])
# else:
# c = c + (a[a_index:])
# return c
# a = [1,3,5]
# b = [2,4,6]
# print(merge(a, b)) # [1, 2, 3, 4, 5, 6]
# def merge_sort(arr):
# if len(arr) <= 1:
# return arr
# left = merge_sort(arr[:len(arr) // 2])
# right = merge_sort(arr[len(arr) // 2:])
# return merge(left, right)
# test = create_array()
# print(test)
# sort = merge_sort(a)
# print(sort)
# Rerwiting provided code
def merge(arrA, arrB):
elements = len(arrA) + len(arrB)
merged_arr = [0] * elements
a = 0
b = 0
# since arrA and arrB are already sorted, we only need
# to compare the first element of each
for i in range(0, elements):
# if all elements of arrA have been merged
if a >= len(arrA):
merged_arr[i] = arrB[b]
b += 1
# all elements in arrB have been merged
elif b >= len(arrB):
merged_arr[i] = arrA[a]
a += 1
# next element in arrA smaller, so add to final array
elif arrA[a] < arrB[b]:
merged_arr[i] = arrA[a]
a += 1
# else, next element in arrB must be smaller,
# add it to final array
else:
merged_arr[i] = arrB[b]
b += 1
return merged_arr
def merge_sort(arr):
if len(arr) > 1:
left = merge_sort(arr[0: len(arr) // 2])
right = merge_sort(arr[len(arr) // 2: ])
arr = merge(left, right) # merge defined later
return arr
def create_array(size = 10, max = 50):
from random import randint
return [randint(0, max) for _ in range(size)]
test = create_array()
print(test)
result = merge_sort(test)
print(result) | true |
d1a5950862f2bd38af9e15a24ef21717992a5629 | Yang-Hyeon-Seo/1stSemester | /python/coffeeMachine_v2.py | 2,128 | 4.25 | 4 |
cup={}
menu={'Americano':1800, 'Cafe latte':2200, 'Cafe Mocha': 2800}
money=0
sum=0
def print_menu():
print(' '+'='*5+'Sookmyung Cafe'+'='*5)
print("""1. Select coffee menu
2. Check your order
3. Pay total price
4. Get change""")
def print_coffeeMenu():
print('[Cafe Menu]')
for coffee,won in menu.items():
print(' '+coffee+' '+str(won)+'won')
def select_menu():
while True:
coffee=input('Select Menu : ')
if coffee not in menu.keys():
print('You selected wrong menu..')
continue
many=int(input('How many cups ? '))
if coffee in cup.keys():
cup[coffee] += many
else:
cup[coffee] = many
break
def check_order():
for coffee, many in cup.items():
print(coffee, '\t', many,'cups')
def calculate_price():
global sum
global money
sum=0
for coffee in cup.keys():
sum += cup[coffee]*menu[coffee]
print('TotalPrice :',sum)
while True:
money=int(input('Pay money : '))
if sum > money:
print('Too small..\n')
else:
break
def get_change():
change= money - sum
print('Your change is',change,'won')
print('='*30)
change_5000=change//5000
change=change%5000
change_1000=change//1000
change=change%1000
change_500=change//500
change=change%500
change_100=change//100
print('5000 won :',change_5000)
print('1000 won :',change_1000)
print('500 won :',change_500)
print('100 won :',change_100)
while True:
print_menu()
print()
choose=int(input('Choose : '))
if choose == 1:
print()
print_coffeeMenu()
print('\n')
select_menu()
elif choose == 2:
check_order()
elif choose == 3:
calculate_price()
elif choose == 4:
get_change()
print('\nThank you for using our machine')
break
| false |
2582d108a084c0dd2f2edd70970f2e14c49b15a1 | Sarsoo/py-labs | /exercise_2.py | 1,007 | 4.40625 | 4 | rows = eval(raw_input("Enter Row Number: ")) #user defines number of columns
columns = eval(raw_input("Enter Column Number: ")) #user defines number of columns
matrix = [] #define empty matrix
for i in range(0, rows): #populates matrix with user elements
newrow = []
for j in range(0, columns): #defines a row of elements added by user and appends it to matrix
num = int(raw_input("Enter Matrix Element: "))
newrow.append(num)
matrix.append(newrow)
for i in matrix: #print first matrix
print i
transposed_matrix = [] #defines new matrix which will become transpose of previous matrix
for i in range(0, columns): #same function as before to populate new matrix, defining number of rows as
newrow = [] #previous matrix had columns and vise versa
for j in range(0, rows):
num = matrix[j][i] #takes each element from previous matrix rather than user input as before
newrow.append(num)
transposed_matrix.append(newrow)
for i in transposed_matrix:
print i #print transpose matrix | true |
7d9f5906fa8cf493fa37343d70e23f42c8ec441f | aidamuhdina/basic-python-batch-4 | /string_formatting.py | 208 | 4.25 | 4 | name = "Aida"
age = "22"
text = "Nama saya {} dan umur saya {}".format(name,age)
print(text)
name = input("Nama : ")
age = input("Umur : ")
text = "Nama saya {} dan umur saya {}".format(name,age)
print(text) | false |
e85eb09748c2857ec40616eee4453b890e7b932c | BeardedGinger24/PythonTutorial | /python_work/Lists.py | 2,691 | 4.5625 | 5 |
# square brackets, [], indicate a list and individual elements in the list are seperated by commas
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles)
# access a specific element in a list
print(bicycles[0])
# we can even use the string functions
print(bicycles[0].title())
# python uses the index -1 to access the last item in the list (it's a special case)
# helpful if you want to access the last item without knowing the length of the list
# and this extends to the values -2 (second from last) and -3, etc
print(bicycles[-1])
# we can use an individual value from the list to create a message like before
message = "My first bicycle was a " + bicycles[0].title() + "."
print(message)
# Modifying elements in a lists
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
motorcycles[0] = 'ducati'
print(motorcycles)
# to add new data to a list use append
motorcycles.append('ducati')
print(motorcycles)
# Insert elements into a list given a specific position
motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles.insert(0, 'ducati')
print(motorcycles) # gives: ['ducati', 'honda', 'yamaha', 'suzuki']
# Removing/Deleting elements given position/index
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
del motorcycles[0]
print(motorcycles)
# remove an element and store the value, use pop()
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
popped_motorcycle = motorcycles.pop()
print(motorcycles)
print(popped_motorcycle)
# you can use position to pop as well
first_owned = motorcycles.pop(0)
print('The first motorcycle I owned was a ' + first_owned.title() + '.')
# if you dont know the position of the element, then remove by value (only removes first occurance)
motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
print(motorcycles)
motorcycles.remove('ducati')
print(motorcycles)
# you can also use the value that you are removing using the remove function
motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
print(motorcycles)
too_expensive = 'ducati'
motorcycles.remove(too_expensive)
print(motorcycles)
print("\nA " + too_expensive.title() + " is too expensive for me.")
# Permantitly organizing a list
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)
# Or sort it backwards
cars.sort(reverse=True)
print(cars)
# temporarly sort a list
print("\nHere is the sorted list:")
print(sorted(cars))
# Reverse order, without sorting
cars = ['bmw', 'audi', 'toyota', 'subaru']
print(cars)
cars.reverse()
print(cars)
#or, temporarly reverse
print(sorted(cars,reverse=True))
# Finding the length of the list
# >>> cars = ['bmw', 'audi', 'toyota', 'subaru']
# >>> len(cars)
# 4
| true |
2762e383854d137924e398426c45fc86690c2e81 | aakash2309/Guvi | /sides of a triangle.py | 287 | 4.1875 | 4 | s1=int(input("enter the 1st sidee of a triangle:"))
s2=int(input("enter the 2nd side of a triangle:"))
s3=int(input("enter the 3rd side of a triangle:"))
if s1**2==(s2**2+s3**2) or s2**2==(s1**2+s3**2) or s3**2==(s1**2+s2**2):
print("valid triangle")
else:
print("invalid triangle")
| true |
a4f3a65410ea6ac41485985d4d7ac4100e34fd13 | aakash2309/Guvi | /Upper or Lower case alphabet.py | 218 | 4.21875 | 4 | ch=input("enter any alphabet:")
if ch.islower():
print("the given character is in lowercase")
elif ch.isupper():
print("the given character is in uppercase")
else:
print("undetermined")
| true |
cc23713c2a15ab6ca67c3fa5a37aa412fea0da66 | minhnguyen2610/C4T-BO4 | /Session10/UpdateL.py | 209 | 4.15625 | 4 | info = {
"name":"God",
"creation":"Everything",
"age":"idk",
}
n = input("enter the key which you want to change: ")
m = input("Enter the value which you want to put in: ")
info[n] = m
print(info) | true |
3bf29afd83ce0ccb9c08d594133b235219754270 | BogdanLeo/CursuriGrupa5 | /Numere.py | 233 | 4.125 | 4 | nume = input("Enter your name: ")
val = input("Enter your value: ")
text = f"Sirul de numere a fost gasit de {nume}"
if type(val) == int:
print(text)
else:
text = f"Sirul de caractere a fost gasit de {nume}"
print(text)
| false |
99aa6b90ac8879ee206def722585dbb9e03a308e | subhashtiwari/algorithms | /9_Chapter 5/Problem.py | 2,752 | 4.15625 | 4 | # What is the average value of C(w,x) if we choose a random node v from graph.
# And then choose a pair of neighbour of that particular chosen node v randomly from graph.
# And then return either 1 or 0 depending whether those two nodes are connected or not.
# The average is over two sources of randomness that we're randomizing overall nodes and overall pairs.
# The expected value of some random variable x is the sum of all values that the variable can take on, the value of thet variable times the probability.
# Write the code for finding the expected value of C(w,x).
def expected_C(G,v):
return clustering_coefficient(G,v)
# The answer to this code is actually the clustering coefficient code as it returns the approximated value for any node.
# The value will be 1 at the starting but as the code repeats the value will flucuate around 0.3, i.e. it can be 0.27, 0.29, 0.31 etc.
# The value converges to actual clustering coefficient.
def clustering_coefficient(G,v):
neighbours = G[v].keys()
degree = len(neighbours)
if len(neighbours) == 1: return 0.0
links = 0.0
for w in neighbours:
for u in neighbours:
if u in G[w]: links += 0.5
return 2.0*links/(len(neighbours)*(len(neighbours)-1))
v = 2 # It can be the number of the node we want Clustering Coefficient of
print "CC:", clustering_coefficient(G,v)
# To choose different neighbours randomly move them into an array vindex.
# By this we choose indices from this array and thus they don't repeat.
vindex = {}
d = 0
for w in G[v].keys():
vindex[d] = w
d += 1
total = 0
for i in range(1,1000):
if d > 1: # d is the degree of node v. And as log as it is greater than 1 we can pick a random neighbour.
pick = random.randint(0,d-1) # Neighbour is chosen by its ordering from 0 to d-1.
v1 = vindex[pick] # v1 is the neighbour- the actual name associated with that pick.
v2 = vindex[(pick+random.randint(1,d-1))%d] # v2 is the second pick that will choose from 1 to d-1. Add this to the pick that we already got with modular d to make it wrap aroud. This make sure we pick a different node than the earlier one.
if v2 in G[v1]: total +=1 # if they are connected then we add 1 to the total.
print i, (total+0.0)/i # Repeat this loop thousand times and each time take the total number of things that are connected divided by the total number of times we tried.
# Thus the actual number converges to the actual clustering coefficient. | true |
2c5afb1673cbfa11c7be4a32922fc6f345f018ad | ioneaxelrod/calculator-2 | /calculator.py | 1,870 | 4.375 | 4 | """A prefix-notation calculator.
Using the arithmetic.py file from Calculator Part 1, create the
calculator program yourself in this file.
"""
import arithmetic
operations = {
"+": arithmetic.add,
"-": arithmetic.subtract,
"*": arithmetic.multiply,
"/": arithmetic.divide,
"square": arithmetic.square,
"cube": arithmetic.cube,
"pow": arithmetic.power,
"mod": arithmetic.mod,
"%": arithmetic.mod,
"x+": arithmetic.add_mult,
"cubes+": arithmetic.add_cubes
}
quit_list = ["q", "quit"]
def calculate(math_string):
""" Takes a single string and performs the math function specified at the
beginning on all following numbers. Returns a string with calculation or
user error info.
"""
tokens = math_string.split()
operator = tokens[0]
if operator not in operations:
return "INVALID INPUT!!!"
try:
for idx in range(1, len(tokens)):
tokens[idx] = float(tokens[idx])
except ValueError:
return "USE NUMBERS!!!"
else:
nums = tokens[1:]
return "{:.2f}".format(operations[operator](nums))
while True:
print("Please choose an option, or type q to quit.")
print()
print("1. User input prefix calculator")
print("2. Prefix calculate from text")
user_input = input("> ").lower()
if user_input in quit_list:
break
elif user_input == "1":
print("You have chosen the user calculator")
while True:
math_string = input("> ").lower()
if math_string in quit_list:
break
print(calculate(math_string))
elif user_input == "2":
file = open("math-to-do.txt")
for line in file:
line = line.rstrip()
print(calculate(line))
file.close()
else:
print("That was not a valid option")
| true |
aa0789be7e510042158de039b84e44e948fb8390 | yuvraj0042/python_files | /03.py | 210 | 4.15625 | 4 | a=input("enter the number")
f=1
if a<0:
print("factorial does not exist")
elif a==0:
print("the factorial of 0 is 1")
else:
for i in range(1,a+1):
f=f*i
print("the factorial of",a,"is",f)
| true |
7290198055c7b767701eb5d94adf319c93355484 | marceloehbemlegal/Projeto-ESOF---Python | /sprint 1/PasswordDetect.py | 770 | 4.125 | 4 | import re
def StrongPassword (password):
if len(password)<8:
return False
passwordRegexLower=re.compile(r'[a-z]')
passwordRegexUpper=re.compile(r'[A-Z]')
passwordRegexDigit=re.compile(r'[0-9]')
moForPassword=passwordRegexLower.search(password)
if moForPassword==None:
return False
moForPassword=passwordRegexDigit.search(password)
if moForPassword==None:
return False
moForPassword=passwordRegexUpper.search(password)
if moForPassword==None:
return False
return True
userPass=input("Type the password: ")
if StrongPassword(userPass):
print("Valid password.\n")
else:
print("Password not strong enough.\n") | true |
0b8cdc97ddddf58dd212c392e78a5697bcafe95d | zhumike/python_test | /练习/算法/字符串/实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。.py | 2,448 | 4.3125 | 4 |
"""
实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。
示例:
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple"); // 返回 true
trie.search("app"); // 返回 false
trie.startsWith("app"); // 返回 true
trie.insert("app");
trie.search("app"); // 返回 true
说明:
你可以假设所有的输入都是由小写字母 a-z 构成的。
保证所有输入均为非空字符串。
trie树,即字典树,又称单词查找树或键树,是一种树形结构,是一种哈希树的变种。典型应用是用于统计
和排序大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:最大
限度地减少无谓的字符串比较,查询效率比哈希表高。”
因为限定都是由a-z小写字母构成,所以这棵树是一棵26叉树。前缀树的构造过程,通过不断插入新的字符串来
丰富这棵26叉树。前缀树的功能很强大,可以做文本词频统计,例如我们在搜索框中的搜索提示,就可以利用前缀
树实现。因此,前缀树基本的操作是字符串的插入insert,搜索search,删除delete,查找前缀startsWith等。
https://blog.csdn.net/weixin_42077402/article/details/98174130
"""
class Trie(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = {}
def insert(self, word):
"""
Inserts a word into the trie.
:type word: str
:rtype: None
"""
node = self.root
for char in word:
node = node.setdefault(char, {})
print(node)
node["end"] = True
def search(self, word):
"""
Returns if the word is in the trie.
:type word: str
:rtype: bool
"""
node = self.root
for char in word:
if char not in node:
return False
node = node[char]
print(node)
return "end" in node
def startsWith(self, prefix):
"""
Returns if there is any word in the trie that starts with the given prefix.
:type prefix: str
:rtype: bool
"""
node = self.root
for char in prefix:
if char not in node:
return False
node = node[char]
return True
| false |
a8d431df62c93cc46ad591a9425cbd9749fdcfb2 | japugliese/learn_python_the_hardway | /solutions/ex4.py | 741 | 4.25 | 4 | #this is to create a the variable "cars"
cars=100
#use underscores to create spaces
space_in_cars=4.0
drivers=30
passengers=90
#this makes variables about calculations of previouse variables
cars_not_driven=cars-drivers
cars_driven=drivers
carpool_capacity=cars_driven*space_in_cars
average_passengers_per_car=passengers/cars_driven
#Now we are going to print out the various results
#when the program is executed
print "there are", cars, "cars available."
print "there are only", drivers, "drivers available."
print "there will be", cars_not_driven, "empty cars."
print "we can transport", carpool_capacity, "people today"
print "we have", passengers, "to carpool today"
print "we need to put", average_passengers_per_car, "in each car."
| true |
29b90a2a0197b216c020c81ec740f4af9f569aa0 | japugliese/learn_python_the_hardway | /solutions/ex3.py | 658 | 4.5 | 4 | print "I will now count my chickens:"
# counts the chickens by adding then dividing
print "Hens", 25+30/6
# this is a modulus which calculates the remainder of the forumula.
# 100-25=75*3=225%4=97
print "Roosters", 100-25*3%4
print "Now I will count the eggs:"
print 3+2+1-5+4%2-1/4+6
#by using < it creates a true false situation
print "Is it true that 3+2<5-7?"
print 3+2<5-7
#solves
print "What is 3+2?", 3+2
print "what is 5-7?", 5-7
print "Oh, that's why it is false."
print "How about some more?"
#agains creates true and false equations by using <>
print "Is it greater?", 5>-2
print "Is it greater or equal", 5>=-2
print "Is it less or equal", 5<=-2
| true |
7e32dc80548589bd717069d6c34ad717bae5bfe0 | swang2017/python-calculator | /calculatorApp.py | 575 | 4.21875 | 4 |
import calculator_helper as calculator
While True:
input1 = float(raw_input("please enter the first number\n"))
input2 = raw_input("please enter the operand\n")
input3 = float(raw_input("please enter the second number\n"))
if input2 == "+":
calculator.add(input1,input3)
elif input2 == "-":
calculator.subtract(input1,input3)
elif input2 == "*":
calculator.time(input1,input3)
elif input2 == "/":
calculator.divide(input1,input3)
choice = raw_input("Press q to quit")
if choice == "q":
break
| true |
b09b4ab59d5e0ea95f1c2bb952f41d69a7c0ec3d | Brian-RG/46-Python-Exercises | /Exercise25.py | 615 | 4.25 | 4 | vowels=["a","e","i","o","u"]
exceptions=["be","see","flee","knee"]
def make_ing_form(word):
if word.endswith("ie"):
word=word[:-2]+"ying"
elif word.endswith("e"):
if word not in exceptions:
word=word[:-1]+"ing"
else:
word=word+"ing"
elif word[0] not in vowels:
if word[1] in vowels:
if word[2] not in vowels:
word=word+word[2]+"ing"
else:
word+="ing"
return word
print(make_ing_form("lie"))
print(make_ing_form("see"))
print(make_ing_form("move"))
print(make_ing_form("hug"))
| false |
10f7bc9715ef73eed022140cfc2b081b2ef8b5b8 | Erniess/pythontutor | /Занятие 6 - Цикл while/Практика/Утренняя пробежка.py | 741 | 4.25 | 4 | # Задача «Утренняя пробежка»
# Условие
#
# В первый день спортсмен пробежал x километров, а затем он каждый день увеличивал
# пробег на 10% от предыдущего значения. По данному числу y определите номер дня,
# на который пробег спортсмена составит не менее y километров.
#
# Программа получает на вход действительные числа x и y и должна вывести одно
# натуральное число.
x, y = int(input()), int(input())
i = 1
while x < y:
x *= 1.1
i += 1
print(i) | false |
37c552f62b220cc96a624993119ef0dce7737438 | Erniess/pythontutor | /Занятие 8 - Функции и рекурсия/Практика/Возведение в степень.py | 649 | 4.15625 | 4 | # Задача «Возведение в степень»
# Условие
#
# Дано действительное положительное число a и целое неотрицательное число n.
# Вычислите an не используя циклы, возведение в степень через ** и функцию math.pow(),
# а используя рекуррентное соотношение an=a⋅an-1.
#
# Решение оформите в виде функции power(a, n).
def power(a, n):
if n == 0: return 1
return a * power(a, n - 1)
a = float(input())
n = int(input())
print(power(a, n)) | false |
010f6269a077f31825f915bd9e24ffbfffe270e6 | karlesleith/Python-Fundamentals | /GuessingGame.py | 608 | 4.21875 | 4 | #Guessing Game in Python
#Author Karle Sleith
import random
from random import randint
guesses = 3;
randomNumber = randint(1,10)
win = False;
while guesses > 0 :
print("\nNumber of Guesses Left: "+ str(guesses))
guess = int(input("Pick and number between 1 - 10 :\n"))
if guess > randomNumber:
print("Your number was too High")
guesses = guesses-1;
elif guess < randomNumber:
print("Your number was too Low")
guesses = guesses -1;
elif guess == randomNumber:
print("\nYou Win!")
break
print("\nGame Over The Number was "+ str(randomNumber))
| true |
acc83f7a5ead2144e804e10fe9e6127a7039ead2 | NathanCrotty/prime | /isprime.py | 830 | 4.28125 | 4 | from math import sqrt
def dec(num):
if round(num) == num:
return False
else:
return True
def isprime(num):
a = 2
if dec(num) == True:
return "Error"
# the above if statement says that if a the number put into "isprime()" function is a decimal, return "Error"
while 1 == 1:
if dec(num / a) == False:
print(str(num) + " / " + str(a) + " = " + str(num / a))
return False
break
elif a >= round(sqrt(num)):
return True
break
else:
print(str(num) + " / " + str(a) + " = " + str(num / a))
if a >= 3:
a += 2
else:
a += 1
continue
while 1 == 1:
print(str(isprime(float(input()))))
| true |
26cfd615f6c590e2639491f76fa149a5dd40c83a | okuchap/PyAlgo | /fractal.py | 720 | 4.3125 | 4 | #Draw a fractal tree
import turtle
import random
def tree(branchLen,t):
if branchLen < 10:
t.color("green")
if branchLen > 5:
t.forward(branchLen)
t.right(random.randint(15,45))
tree(branchLen-random.randint(10,20),t)
t.left(random.randint(15,45))
tree(branchLen-random.randint(10,20),t)
t.right(random.randint(15,45))
t.backward(branchLen)
if branchLen >= 10:
t.color("black")
def main():
t = turtle.Turtle()
myWin = turtle.Screen()
t.left(90)
#pull the pin up
t.up()
t.backward(100)
#put the pin down
t.down()
#change the color
t.color("black")
tree(75,t)
myWin.exitonclick()
main()
| false |
683e3a33925021ebb240671db1c5150720a29bb3 | Jioji1321/notebook | /code/python_helloworld/demo/base/condition.py | 780 | 4.15625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 条件判断 if, 注意 :
age = 14
print('ur age is ', age)
if age >= 18:
print('adult')
else:
print('youngster')
# 用elif 表示else if
age = 1
print('ur age is ', age)
if age >= 18:
print('adult')
elif age > 10:
print('youngster')
elif age > 8:
print('children')
else:
print('baby')
# if 判断条件可以简写,只要x是非零数值、非空字符串、非空list等,就判断为True,否则为False。
x = ()
if x:
print('True')
else:
print('False')
height = 1.83
weight = 70
bmi = weight / (height ** 2)
if bmi < 18.5:
print('过轻')
elif bmi < 25.0:
print('正常')
elif bmi < 28.0:
print('过重')
elif bmi < 32.0:
print('肥胖')
else:
print('过度肥胖') | false |
3867650888c03b2d67a0141f257b9ed05b311bb1 | devin-petersohn/ICE_SPRING_2016 | /guessing_game.py | 616 | 4.1875 | 4 | #guessingGame
import random
number = random.randint(1,20)
print('Hello! What is your name?')
myName = input()
print("Well " + myName + " I'm thinking of a number between 1 and 20")
guess = 0
num_guesses = 5
while num_guesses > 0:
print("Make a guess! " + str(num_guesses) + " guesses left!")
guess = int(input())
if guess < number:
print("Too low!")
if guess > number:
print("Too high!")
if guess == number:
break
num_guesses = num_guesses - 1
if guess == number:
print("You win!")
if num_guesses == 0:
print("You lost, I was thinking of " + str(number))
| true |
90f452bb308008bca324a96838cdf029f64e6522 | BrianBawden/local_hi-low | /hilo/game/card.py | 786 | 4.1875 | 4 |
# Create a dictionary of values: "two" '2', "11", "Jack"
# Create tuple of suits
# Create a tuple of ranks
values = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7,
'Eight':8, 'Nine':9, 'Ten':10, 'Jack':11, 'Queen':12,'King':13,'Ace':14}
suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs')
ranks = ('Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten','Jack','Queen','King','Ace')
class Card:
"""
A code template that facilitates the creation of cards.
Attributes:
suit = tuple
rank = tuple
value = values[rank]
"""
def __init__(self,suit,rank):
self.suit = suit
self.rank = rank
self.value = values[rank]
def __str__(self):
return self.rank + " of " + self.suit | true |
e4334e4456580c28b5194028807923b4d4a299a2 | Diego-LC/python-repo | /Python_stack/hello_world2test.py | 2,478 | 4.40625 | 4 | #concatenacion:
name = "Zen"
print("Mi nombre es", name)
name = "Zen"
print("Mi nombre es " + name)
#F-Strings (interpolación literal de cadenas)
first_name = "Zen"
last_name = "Coder"
age = 27
print(f"mi nombre es {first_name} {last_name} y tengo {age} años")
#antes era con string.format:
first_name = "Zen"
last_name = "Coder"
age = 27
print("Mi nombre es {} {} y tengo {} años.".format(first_name, last_name, age))
# output: My name is Zen Coder and I am 27 years old.
print("Mi nombre es {} {} y tengo {} años.".format(first_name, last_name, age))
# output: My name is 27 Zen and I am Coder years old.
#otra manera mas antigua aun:
hw = "Hola %s" % "mundo" # %s con valores string
py = "Me encanta Python %d" % 3 # %d con valores int
print(hw, py)
# salida: Hola mundo Me encanta Python 3
name = "Zen"
age = 27
print("Mi nombre es %s y tengo %d" % (name, age)) # o con variables
# Salida: Mi nombre es Zen y tengo 27
#otros
x = "hola mundo"
print(x.title())
# Salida:
"Hello World"
# string.upper(): devuelve una copia de la cadena con todos los caracteres en mayúscula.
# string.lower(): devuelve una copia de la cadena con todos los caracteres en minúsculas.
# string.count(substring): devuelve el número de ocurrencias de subcadena en la cadena.
# string.split(char): devuelve una lista de valores donde la cadena se divide en el carácter dado. Sin un parámetro, la división predeterminada está en cada espacio
# string.find(substring): devuelve el índice del inicio de la primera aparición de subcadena dentro de la cadena.
# string.isalnum(): devuelve booleano dependiendo de si la longitud de la cadena es> 0 y todos los caracteres son alfanuméricos (solo letras y números). Las cadenas que incluyen espacios y signos de puntuación devolverán False para este método. Métodos similares incluyen .isalpha(), .isdigit(), .islower(), .isupper(), y así sucesivamente. Todos regresan booleanos.
# string.join(list): devuelve una cadena que es todas las cadenas dentro de nuestro conjunto (en este caso, una lista) concatenadas.
# string.endswith(substring): devuelve un valor booleano en función de si los últimos caracteres de la cadena coinciden con la subcadena.
# La sentencia pass es una operación nula; No pasa nada cuando se ejecuta. El pase casi nunca se ve en la producción final, pero puede ser útil en lugares donde su código aún no se ha completado.
class EmptyClass:
pass
| false |
72ba3106aaa695e7382edcf9baa2a58b7b575e30 | MRamonSorell/100-Days-Of-Code-Python | /Day8_Project.py | 2,172 | 4.34375 | 4 | # Day 8 Project
# Ceaser Cipher
# Ceaser Cipher is an encoding and decoding game
# The goal is to encrypt (decrypt) a message using a positional shifts in the alphabet
# Rules for encoding:
# enter a string / phrase
# ask for a positional shift in the alphabet
# shift the alphabet
# generate a new string based on original string /phrase
# output phrase
# decoded word should be the reverse of the encoded word
def encode_word(phrase, shift):
alphabet ="abcdefghijklmnopqrstuvwxyz"
encoded_alpha = alphabet[shift-1:] + alphabet[0:shift-1]
#print(encoded_alpha)
text_position = []
for letter in phrase:
for index, item in enumerate(alphabet):
if letter == item:
text_position.append(index)
#print(text_position)
encoded_word =[]
for index in text_position:
encoded_word.append(encoded_alpha[index])
#print(encoded_word)
encoded = "".join(encoded_word)
#print(encoded)
return encoded
def decode_word(phrase, shift):
alphabet ="abcdefghijklmnopqrstuvwxyz"
encoded_alpha = alphabet[shift-1:] + alphabet[0:shift-1]
#print(encoded_alpha)
text_position = []
# this is wrong
for letter in phrase:
for index, item in enumerate(encoded_alpha):
if letter == item:
text_position.append(index)
#print(text_position)
decoded_word =[]
for index in text_position:
decoded_word.append(alphabet[index])
#print(decoded_word)
decoded = "".join(decoded_word)
#print(decoded)
return decoded
encode_decode = input("Do you want to encode a word or decode:").lower()
if encode_decode == "encode":
text_input = input("Please enter the text to be encoded: ").lower()
shift_text = int(input("Please enter the positional shift: "))
new_encode = encode_word(text_input, shift_text)
print(f"The encoded word is {new_encode}")
else:
text_input = input("Please enter the text to be decoded: ").lower()
shift_text = int(input("Please enter the positional shift: "))
new_decode = decode_word(text_input, shift_text)
print(f"The decoded word is {new_decode}")
| true |
c1f520d1874204d5799cb51d3c4470d914fc49e8 | alishirazakhter/JISAssasins | /Day4Challenge2.py | 1,122 | 4.125 | 4 | '''
Bonus Question:
Accept a 6 digit number from user!
Let the Computer Generate Random Numbers till the generated random number matches the user input
finally
display the total number of attempts made by computer to match the user input.
'''
'''
import random
a= int(input("Enter 6 digit Number : "))
count=0
while(1):
r=random.randint(100000,1000000)
print(r)
count+=1
if r==a:
break
else:
continue
print("Total number of attempts made by computer = ",count)
'''
import random
class Checking:
def __init__(self):
self.count=0
def calculation(self,a):
while(1):
r = random.randint(100000, 1000000)
# print(r)
self.count += 1
if r == a:
break
else:
continue
self.result()
def input(self):
self.a = int(input("Enter 6 digit Number : "))
self.calculation(self.a)
def result(self):
print("Total number of attempts made by computer = %s"%(self.count))
check=Checking()
check.input()
| true |
7c7f059092430334cb47a5899f5398b5d5ef4ad3 | mcolinj/training2017 | /Week1.py | 1,206 | 4.21875 | 4 | # French verb conjugator
import sys
def ends_in_er(word):
"""
Return True if the string word ends in 'er', otherwise return False.
This does not work if there is whitespace at the end of the string.
Maybe we could consider taking care of that in this function just to
be robust.
"""
return (word[-2:] == 'er')
def test_functions():
if not ends_in_er('beer'):
print("FAIL")
if ends_in_er('carrot'):
print("FAIL")
# Following test could catch something that we change
if ends_in_er('amanecer\n'):
print("FAIL. Currently not stripping whitespace")
# run the self-test for our functions
test_functions()
# prompt user
print ("Enter verb in infinitive form")
# Read the response
for verb in sys.stdin:
# be clever and work around the newline
ending=verb[-3:-1]
print (ending)
if ending=='er':
beg=verb[0:-3]
print ("j\' " + beg + "e")
print ("tu " + beg + "es")
print ("il/elle/on " + beg + "e")
print ("nous " + beg + "ons")
print ("vous " + beg + "ez")
print ("ils/elles " + beg + "ent")
# prompt user
print ("Enter verb in infinitive form")
| true |
430bccc3ddad20d241ba7905946c3b54c6804f5c | AkhilReddykasu/Functions | /12_Reverse a string.py | 353 | 4.34375 | 4 | """Reverse a string"""
from string import *
str1 = input("Enter a string:")
"""
def reverse_string(s):
return s[::-1]
print("Reverse of a string:", reverse_string(str1))
"""
def reverse_string(s):
str2 = ""
for i in s:
str2 = i + str2
return str2
print("Reverse of a string:", reverse_string(str1))
| true |
aa261210fa2b8b2837b46e0956b80f2f56970d76 | AkhilReddykasu/Functions | /07_Multiples of a given num.py | 223 | 4.21875 | 4 | """Multiples of a given number"""
num = int(input("enter a number to find the table:"))
def multiple(n):
print("Multiples of a number",n,"are:")
for i in range(1,11):
print(n * i)
multiple(num) | true |
b97a2c85ebe68df66cf911d4dd4cb74eea13b29b | cremzoo/python-number-guessing | /number_guessing.py | 636 | 4.25 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 5 18:38:15 2018
@author: cremz1
"""
import random
guesses = []
myComputer = random.randint(1, 70)
player = int(input("Enter a number between 1-70:"))
guesses.append(player)
while player != myComputer:
if player > myComputer:
print("Number is too high!")
else:
print("Number is too low!")
player = int(input("Enter a number between 1-70: "))
guesses.append(player)
else:
print("You have guessed right! Good job!")
print("It took you %i guesses. " % len(guesses))
print("This were your guesses:")
print(guesses)
| true |
c24129245d27661108e6fb4c2d91aff9882e649f | zac11/AutomateThingsWithPython | /WorkingWithStrings/FinalCombinationFunctions.py | 2,229 | 4.15625 | 4 | decnum=123.4322
string_normal=' Welcome to Python Combination Program '
string_sel='Intro to Selenium WebDriver'
"""
Stripping whitespaces can be done by the strip() method
"""
print('Before stripping whitespaces string is '+string_normal)
print('After stripping whitespaces, string becomes '+string_normal.strip())
"""
Check whether Selenium text is present in the string_sel
"""
if 'Selenium' in string_sel:
print('Selenium is present in '+string_sel)
else:
print('Selenium is not present in '+string_sel)
"""
First string starts with Welcome, which can be checked using startswith() method
"""
if string_normal.startswith('Welcome'):
print(string_normal+" starts with 'Welcome'")
else:
print('First trim the whitespace and then try it again')
print(string_normal.strip().startswith('Welcome'))
print('Now it will match the starting point')
"""
Second string ends with Driver, which can be checked using endswith() method
"""
if string_sel.endswith('Driver'):
print(string_sel+" string ended with 'Driver'")
else:
print(string_sel+ "doesn't end with the checking string")
"""
Checking if the string is empty, which is done by isspace() method
"""
if string_sel.isspace():
print('String is empty')
else:
print('String is not empty')
"""
To check if the two strings are equal, we can simply use the == operator
"""
if string_sel=="Selenium WebDriver":
print(string_sel+ " equals the text that we entered")
else:
print(string_sel+ " doesn't equal the text that we entered")
"""
Priting the length of the string can be done by len(str) method
"""
print(len(string_normal))
print(len(string_sel))
"""
Replacing a portion of string can be done by replace() method
"""
print(string_normal.replace('Python','Angular',1))
"""
Converting the string to lowercase can be done by lower() method
"""
if string_normal.islower():
print('String is already lower case')
else:
print(string_normal.lower())
"""
Converting the string to uppercase can be done by upper() method
"""
if string_sel.isupper():
print('String is already uppercase')
else:
print(string_sel.upper())
"""
Splitting the string can be done by split() method
"""
print(string_normal.split()) | true |
181bf2a5ad579903fbf01c4d61699740b66e0e98 | gauravtripathi001/EIP-code | /Tree/tree-insert.py | 794 | 4.125 | 4 | #User function Template for python3
'''
# Tree Node
class Node:
def __init__(self, val):
self.right = None
self.data = val
self.left = None
'''
# The function returns the root of the BST (currently rooted at 'root')
# after inserting a new Node with value 'Key' into it.
def insert(root, Key):
# code here
new_node=Node(Key)
if(root is None):
return new_node
prev=None
curr=root
while curr is not None:
if(Key==curr.data):
return root
elif(Key<curr.data):
prev=curr
curr=curr.left
else:
prev=curr
curr=curr.right
if(Key<prev.data):
prev.left=new_node
else:
prev.right=new_node
return root
| true |
1678b821d1ee85c4ae8a194a20ea2efc1b3dd112 | surajprajapati110/list | /sort.py | 240 | 4.125 | 4 | #sort():arrange list in ascending order/Descending order
a=[100,20,80,40,60,50,70,30,90,10]
print("Original List is\n",a)
a.sort(reverse=1)#descending
print("Sorted List is\n",a)
a.sort()#Ascending
print("Sorted List is\n",a)
input() | true |
6b35deaeaa61010a94ffed1ff9ab3ea5e5d3d973 | mohan2see/roadToSuccess | /Python/Introduction/Variables_and_simple_data_types.py | 1,246 | 4.4375 | 4 | # {CHAPTER 2 : VARIABLES AND SIMPLE DATA TYPES}
# ---------------------------------------------
print("WORKING WITH VARIABLES AND SIMPLE DATA TYPES:")
print("---------------------------------------------")
# Working with Strings
name = "MOHAN Ram"
# Camel case
print(name.title())
# Upper and Lower Case
print(name.upper())
print(name.lower())
# fstring introduced in v3.6
message = f"Welcome, {name.title()}!"
print(message)
# for older python versions
message = "Welcome, {0}!".format(name.title())
print(message)
# new line and tab
print("Hello\nWorld!")
print("Fruits:\n\t1.Apple\n\t2.Orange\n\t3.Grapes")
# whitespace strip
message = " Hitman "
print(message.rstrip())
print(message) # message variable still has the space.
print(message.lstrip())
print(message.strip())
# Working With Numbers
print(0.2 + 0.1)
print(3.0 * 2)
print(3.0 ** 2)
print(4 % 3) # returns the remainder
# long Numbers
# Note: Underscore is omitted when printing the numbers
long_num = 6_000_000_000
print(long_num)
# Multiple Assignments
# Note: Number of variables and values should match
a, b, c = 10, 20, 30
print(a, b, c)
# Constants
# Note: Define in Capital letters. There is no inbuilt Constant type in Python
MAX_CONNECTION = 10
print(f'\n\n\n')
| true |
2fd0ad8aea65df455bbda6e8b08c427c4f5b4486 | Lyoug/number-game | /number_game.py | 751 | 4.21875 | 4 | """A very simple number guessing game, mostly for me to try out GitHub."""
import random
lowest = 1
highest = 100
max_tries = 10
solution = random.randint(lowest, highest)
tries = 0
guess = lowest - 1 # anything different from solution
print("I chose a number between", lowest, "and", highest)
while guess != solution and tries < max_tries:
while True:
try:
guess = int(input("How much? "))
break
except ValueError:
print("Please type an integer")
if guess < solution:
print("Too small")
if guess > solution:
print("Too big")
tries += 1
if guess == solution:
print("Bravo! You found it in", tries, "tries")
else:
print("I was thinking of", solution)
| true |
e74648ffa14f0a64c27d7bb5a25f75ca450b5e3a | chrislockard21/ise589 | /python_files/homework/hw1/hw1_p10.py | 603 | 4.1875 | 4 | '''
@author: Chris Lockard
Problem 10:
Write a program that returns the name of the month (per user integer input)
without using conditional statements.
'''
print('Input:')
try:
month_int = input('Enter Integer: ')
# Defines dictionary to look up month names
month_dict = {
'1':'January', '2':'February', '3':'March', '4':'April', '5':'May',
'6':'June', '7':'July', '8':'August', '9':'September', '10':'October',
'11':'November', '12':'December',
}
print('Month is:', month_dict[month_int])
except:
print('Please enter a whole number between 1 and 12.')
| true |
c0e243c6510863e94390be2727b12460130bfd7d | pfe1223/python_crash_course | /basics/alien.py | 895 | 4.25 | 4 | #Dictionary is a key value pair. You can use any object in Python
#as a key value pair (number, string, list, dictionary, etc.)
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
#You can add new key value pairs to a dictionary
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)
#You can modify the values in a dictionary
alien_0 = {'x_position': 0, 'y_position': 25, 'speed': 'medium'}
print(alien_0)
#Move the alien to the right
#Determine how far to move the alien based on its current speed.
if alien_0['speed'] == 'slow':
x_increment = 1
elif alien_0['speed'] == 'medium':
x_increment = 2
else:
#This must be the fast alien
x_increment = 3
#The new position is the old position plus the increment
alien_0['x_position'] = alien_0['x_position'] + x_increment
print("New x-position: " + str(alien_0['x_position']))
#You can delete with - del alien_0['points'] | true |
0ff405c39805faddac7d5262dfee281eff4a9bc8 | ShaheerC/oop_inheritance1 | /people.py | 637 | 4.15625 | 4 | class Person:
def __init__(self, name):
self.name = name
def greeting(self):
return "Hi my name is {}.".format(self.name)
class Student(Person):
def learn(self):
return"I get it!"
class Instructor(Person):
def teach(self):
return"An object is an instance of a class"
nadia = Instructor('Nadia')
print(nadia.greeting())
chris = Student('Chris')
print(chris.greeting())
print(nadia.teach())
print(chris.learn())
print(chris.teach())
#does not work because teach is an instance method for Instructor and not Student. If student was a child of instructor then this would work. | true |
4ef8d60746b7d19eae3f70071f30ad499f84cc2b | syadav88/LeetCode | /Algorithm/ReverseString.py | 484 | 4.15625 | 4 | # ReverseString
def reverse(string):
return string[::-1]
def reverse(string):
newString = ''
for num in range(len(string)-1, -1,-1):
newString += string[num]
return newString
print reverse("sonali")
print reverse("raashid")
print reverse("raashid&sonali")
def reverse(string):
lastIndex = len(string)-1
newString = ''
for num in range(len(string)):
while lastIndex > -1:
newString += string[lastIndex]
lastIndex -= 1
return newString
print reverse("sexy")
| true |
8186b7582e5182dc8e336906c5b8bb400282d9a5 | SC-Mack/Programming102 | /resources/example_lessons/unit_4/examples/unit_3_review_template.py | 2,327 | 4.15625 | 4 | '''
Programming 102
Unit 3 Review
'''
# dictionaries are defined using curly brackets {}
# items (key:value pairs) are separated with commas
# -------------------------------------------------------------------------- #
# to do list item
todo = {}
# dict keys are generally strings
# dict values can be ANY datatype, including other dicts
# ------------------------------------------------------------------------- #
# when accessing values, keys are placed in square brackets [] after the dict name
# -------------------------------------------------------------------------- #
# change the value at a key
# cannot access keys that don't exist
# add a value at the key of 'id'
# ----------------------------------------------------------------------------- #
# delete items
# keyword: del
# ----------------------------------------------------------------------------- #
# .pop(key) - remove the item at the key and return the value
# --------------------------------------------------------------------------------- #
# To avoid key error, check if the key is in the dictionary's keys before using it
# .get(key, default) - return the value at the key if it exists, otherwise return the default
# ------------------------------------------------------------------------------ #
# .update(dict) - add the items from the dict to the original
# -------------------------------------------------------------------------------- #
# .keys(), .values(), .items() - allow access to different parts of the dictionary
# print(todo.keys())
# --------------------------------------------------------------------------------- #
# print(todo.values())
# ---------------------------------------------------------------------------------- #
# print(todo.items())
# ----------------------------------------------------------------------------------- #
# use .keys() to check if a key is in the dictionary
# -------------------------------------------------------------------------------------- #
# instead of multiple, individual todo item dictionaries, create a list of dictionaries
# loop through the todo list
# --------------------------------------------------------------------------------------- #
# Nested dictionaries
# two keys next to one another to access values within the inner dictionary
| true |
e276701130ff61b89400837da8d1a5dbd09d184a | Vladislav23R/algorithms | /less_2_task_2.py | 678 | 4.15625 | 4 | # https://drive.google.com/file/d/1vSSkmxbm9YG_uyA3_KVsR2geLVS68ixL/view?usp=sharing
# Задача 2.
# Посчитать четные и нечетные цифры введенного натурального числа.
# Например, если введено число 34560, в нем 3 четные цифры (4, 6 и 0) и 2 нечетные (3 и 5).
num = input('Введите натуральное число: ')
even = 0
uneven = 0
for i in num:
if int(i) % 2 == 0:
even += 1
else:
uneven += 1
print(f'В числе - {num}\n{even} - Четных чисел(числа) и {uneven} - нечетных чисел(числа).')
| false |
9b5fc9cf594bff7655d167116dde65460fdb97c7 | thainu00/bt3 | /b3.9.py | 304 | 4.15625 | 4 | """program make a simple calculator that can add, subtract, multiply and divide using function"""
#this function adds two numbers
def add(x,y):
return x+y
#this function subtracts two numbers
def subtract(x,y):
return x-y
#this function multiplics two numbers
def multiply(x,y):
| true |
f7e4487052644599b0aa8360721783324e2ea632 | correaswebert/miscellaneous | /Math/prime_factorise.py | 1,385 | 4.3125 | 4 | from math import floor, sqrt
# factors -> the list of prime factors
def prettyFactorsList(factors):
# the final list of factor ^ power
factor_list = []
# to obtain unique factors for finding their powers
factor_set = set(factors)
# add (factor, power) tuple to the factor_list
for num in factor_set:
factor_list.append( (num, factors.count(num)) )
print(factor_list)
def prettyPrintFactors(factors):
# to obtain unique factors for finding their powers
factor_set = set(factors)
for num in factor_set:
print( str(num) + "^" + str(factors.count(num)) + " *" , end=" ")
# as the sequance ends with ... * , so put a terminating 1
print(1)
def factorize(n):
"""Base condition is clubbed with return statement as while loop affects it"""
step = lambda x: 1 + (x<<2) - ((x>>1)<<1)
maxq = int(floor(sqrt(n)))
d = 1
q = 2 if n % 2 == 0 else 3
# another way to write it...
# q = n % 2 == 0 and 2 or 3
while q <= maxq and n % q != 0:
q = step(d)
d += 1
return [q] + factorize(n//q) if q <= maxq else [n]
if __name__ == "__main__":
user_num = int( input("Enter a number: ") )
prettyPrintFactors( factorize(user_num) )
prettyFactorsList( factorize(user_num) )
wait = input("Press ENTER to exit!")
| true |
35c2ab8b481bcda866a3eed3c49b0f3c2928bb17 | correaswebert/miscellaneous | /Math/is_prime.py | 623 | 4.28125 | 4 | from math import sqrt
def isPrime(num):
if num == 2:
return True
# step = 2, as even numbers non prime
# limit sqrt of num as no factors later
for i in range(3, int(sqrt(num)), 2):
if num % i == 0:
return False
return True
if __name__ == "__main__":
try:
user_num = int( input( "Enter a positive integer: ") )
if user_num < 0: raise ValueError
print('Prime' if isPrime(user_num) else 'Not prime')
except ValueError:
print("Not a positive integer!")
wait = input("\nPress ENTER to exit")
| true |
1174422e2fb110af7fad91ecc25f00f9f319d680 | WilyMayo/Lc101 | /lc101/crypto/vigenere.py | 727 | 4.28125 | 4 | from helpers import alphabet_position, rotate_character
def encrypt(text,key):
cipher = ''
l = len(key)
idx = 0 #to access key characters
for i in text:
if i.isalpha(): #If the character is a alphabet then only rotate it otherwise leave it as it is
cipher += rotate_character(i,alphabet_position(key[idx])) #get the position of the key's character and rotate the text's character by that amount
idx = (idx+1)%l #get the next character of the key
else:
cipher += i
return cipher
def main():
text = input("Type a message: \n")
key = input("Encryption key: \n")
print(encrypt(text,key))
if __name__ == '__main__':
main()
| true |
d0ca248661d2abf3960eaa7b984fc42568a0a05a | whoisstan/tristan_python | /variables/types.py | 832 | 4.21875 | 4 | #NUMBERS (int) and OPERATIONS
#we are declaring a number variable
tristanBirthYear=2008
#here we are printing it
print(tristanBirthYear)
#we are printing the result of a opperation
print("minus",2020-tristanBirthYear)
print("multiply",tristanBirthYear*5)
print("divive",tristanBirthYear/5)
print("pow",tristanBirthYear ** 99)
print("remainder", 10 % 6)
#STRINGS (str)
#ordered list of characters (abc...)
tristan = "Tristan Wiechers "
print(tristan)
theFirst = tristan + "the first"
print(theFirst)
print(tristan * 2)
print("")
#ARRAY list
soccerTeam = ["brandon","tristan","nash","soren","issac","max","nico","lucas","jacob"]
print(soccerTeam)
print("length", len(soccerTeam) )
print(soccerTeam + ["zack"])
for name in soccerTeam:
print name
#comparing is if
if name == "tristan":
print(u"\u26BD") #soccer symbol
| false |
3284c3559249ea51066bbade9c20168a60dab00a | bekkam/code-challenges-python-easy | /split.py | 1,833 | 4.25 | 4 | """Split astring by splitter and return list of splits.
This should work like that built-in Python .split() method [*].
YOU MAY NOT USE the .split() method in your solution!
YOU MAY NOT USE regular expressions in your solution!
For example:
>>> split("i love balloonicorn", " ")
['i', 'love', 'balloonicorn']
>>> split("that is which is that which is that", " that ")
['that is which is', 'which is that']
>>> split("that is which is that which is that", "that")
['', ' is which is ', ' which is ', '']
>>> split("hello world", "nope")
['hello world']
* Note: the actual Python split method has special behavior
when it is not passed anything for the splitter -- you do
not need to implemented that.
"""
def split(astring, splitter):
"""Split astring by splitter and return list of splits."""
result_list = []
splitter_length = len(splitter)
# iterate over each character in the string
# current segement = astring[end:i+j]
# if current segment = splitter, slice from beginning up to but not including
# i, and add it to result_list
# increment i
# when finish looping, add remaining segment to result_list
i = 0
j = len(splitter)
end = 0
while (i + j <= len(astring)):
current_segment = astring[i: i + j]
if current_segment == splitter:
# slice from beginning up to but not including i
result_list.append(astring[end:i])
end = i + j
i += 1
# append last segment after splitter (or entire segment if no splitter)
result_list.append(astring[end:])
return result_list
# print split("i love balloonicorn", " ")
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print "\n*** ALL TESTS PASSED. FINE SPLITTING!\n"
| true |
9708d0bff0ad906167e51d6b3f9a42c984f54419 | momentum-morehouse/palindrome-SteveOris | /main.py | 253 | 4.125 | 4 | import re
def is_Palindrome():
x = input('enter phrase ')
clean = re.sub(r'[^A-Za-z]','', x.lower())
return clean == clean[::-1], x
ans = is_Palindrome()
if ans:
print( ans[1], 'is a palindrome')
else:
print("is not a palindrome") | false |
bbcb0ab0fa85ab9784e521453de9c24e43d6a1be | tutejadhruv/Datascience | /Next.tech/Analyzing-Text-Data/solution/lemmatizer.py | 1,340 | 4.46875 | 4 | '''
The goal of lemmatization is also to reduce words to their base forms, but this is a more structured approach. In the previous recipe, we saw that the base words that we obtained using stemmers don't really make sense. For example, the word "wolves" was reduced to "wolv", which is not a real word.
Lemmatization solves this problem by doing things using a vocabulary and morphological analysis of words. It removes inflectional word endings, such as "ing" or "ed", and returns the base form of a word. This base form is known as the lemma. If you lemmatize the word "wolves", you will get "wolf" as the output. The output depends on whether the token is a verb or a noun. Let's take a look at how to do this in this recipe.
'''
from nltk.stem import WordNetLemmatizer
words = ['table', 'probably', 'wolves', 'playing', 'is',
'dog', 'the', 'beaches', 'grounded', 'dreamt', 'envision']
# Compare different lemmatizers
lemmatizers = ['NOUN LEMMATIZER', 'VERB LEMMATIZER']
lemmatizer_wordnet = WordNetLemmatizer()
formatted_row = '{:>24}' * (len(lemmatizers) + 1)
print('\n', formatted_row.format('WORD', *lemmatizers), '\n')
for word in words:
lemmatized_words = [lemmatizer_wordnet.lemmatize(word, pos='n'),
lemmatizer_wordnet.lemmatize(word, pos='v')]
print(formatted_row.format(word, *lemmatized_words)) | true |
18121bf404f15031a7824c8993cb57084fd10f22 | tutejadhruv/Datascience | /Next.tech/Analyzing-Text-Data/solution/chunking.py | 1,357 | 4.125 | 4 | '''
Chunking refers to dividing the input text into pieces, which are based on any random condition. This is different from tokenization in the sense that there are no constraints and the chunks do not need to be meaningful at all. This is used very frequently during text analysis. When you deal with really large text documents, you need to divide it into chunks for further analysis. In this recipe, we will divide the input text into a number of pieces, where each piece has a fixed number of words.
'''
import nltk
nltk.download('brown')
import numpy as np
from nltk.corpus import brown
# Split a text into chunks
def splitter(data, num_words):
words = data.split(' ')
output = []
cur_count = 0
cur_words = []
for word in words:
cur_words.append(word)
cur_count += 1
if cur_count == num_words:
output.append(' '.join(cur_words))
cur_words = []
cur_count = 0
output.append(' '.join(cur_words) )
return output
if __name__=='__main__':
# Read the data from the Brown corpus
data = ' '.join(brown.words()[:10000])
# Number of words in each chunk
num_words = 1700
chunks = []
counter = 0
text_chunks = splitter(data, num_words)
# print(data)
print(text_chunks[0])
print("Number of text chunks =", len(text_chunks))
| true |
914a5a0b47f1d14ae62068469b670525e0eaa262 | oliverJuhasz/Code-Challenges | /CodeWars/6-Take_a_ten_minute_walk.py | 1,497 | 4.25 | 4 | """
https://www.codewars.com/kata/take-a-ten-minute-walk/train/python
You live in the city of Cartesia where all roads are laid out in a perfect grid. You arrived ten minutes too early
to an appointment, so you decided to take the opportunity to go for a short walk. The city provides its citizens with
a Walk Generating App on their phones -- everytime you press the button it sends you an array of one-letter strings
representing directions to walk (eg. ['n', 's', 'w', 'e']). You always walk only a single block in a direction and
you know it takes you one minute to traverse one city block, so create a function that will return true if the walk
the app gives you will take you exactly ten minutes (you don't want to be early or late!) and will, of course, return
you to your starting point. Return false otherwise.
Note: you will always receive a valid array containing a random assortment of direction letters
('n', 's', 'e', or 'w' only). It will never give you an empty array (that's not a walk, that's standing still!).
Note: Codewars doesn't accept solution as its random test-generation crashes
"""
def isValidWalk(walk):
if len(walk) == 10:
while "e" in walk and "w" in walk:
walk.remove("e")
walk.remove("w")
while "s" in walk and "n" in walk:
walk.remove("s")
walk.remove("n")
if not walk:
return True
return False
print(isValidWalk(["n", "s", "e", "w", "n", "s", "n", "s", "e", "e"]))
| true |
a34cd3026816ffde04ae5e7f3e1c08173557b246 | Sonnenlicht/ProjectEuler | /1-50/Q1.py | 330 | 4.21875 | 4 | #Multiples of 3 and 5
#Problem 1
#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.
#! python3
total = 0
for i in range(1000):
if i%3 == 0 or i%5 == 0:
total += i;
print(total)
| true |
33171c517234a3d5989d38727e2a0f297e9b2896 | nasirhemed/python-course | /09-review/ex9/birthday_lookup.py | 988 | 4.625 | 5 | # For this exercise, we will keep track of when our friend’s birthdays are,
# and be able to find that information based on their name.
# Create a dictionary (in your file) of names and birthdays.
# When you run your program it should ask the user to enter a name, and return the birthday of that person back to them.
# The interaction should look something like this:
# >>> Welcome to the birthday dictionary. We know the birthdays of:
# Albert Einstein
# Benjamin Franklin
# Ada Lovelace
# >>> Who's birthday do you want to look up?
# Benjamin Franklin
# >>> Benjamin Franklin's birthday is 01/17/1706.
birthdays = {
"Nasir": "02/02/1920",
"Benjamin" : "17/01/1706",
"Albert" : "13/04/1930"
}
while True:
name = input("Who's birthday do you want to look up? ")
if name in birthdays:
dob = birthdays[name]
print("{}'s birthday is {}".format(name, dob))
else:
dob = input("This name is not in my list. Do you know the person's birthday ? " )
birthdays[name] = dob
| true |
a58caa091a6c9a2842af7fedadf919d857cfef68 | nasirhemed/python-course | /04-strings/ex4/validate_postal_code.py | 972 | 4.25 | 4 |
"""
Define a function postalValidate(S) which first checks if S represents
a postal code (Canadian) which is valid:
first, delete all spaces;
the remainder must be of the form L#L#L# where L are letters
(in either lower or upper case) and # are numbers.
If S is not a valid postal code, return the boolean False.
If S is valid, return a version of the same postal code in the nice format
L#L#L# where each L is capital.
Use the following methods to do this exercise:
str.replace(), str.isalpha(), str.isdigit(), and str.upper()
"""
def postalValidate(S):
""" Return False if S is not a valid postal code.
If S is valid, return it in the format L#L#L# where each L is capital.
>>> postalValidate(' d3 L3 T3')
>>> 'D3L3T3'
"""
# your code here
# Use these arguments to test your function.
"""
‘H0H0H0’, ‘postal’, ‘ d3 L3 T3’, ‘ 3d3 L3 T’, ‘’, ‘n21 3g1z’, ‘V4L1D’,
‘K1A 0A3’, ‘H0H0H’
""" | true |
a404b044a9931f7de2b34fc7d17ad37abff9d9e7 | TaninDean/refactoring-practice | /time/timestamp.py | 1,392 | 4.25 | 4 | """
This code creates a datetime.time object from a string.
- Is it easy to verify that it works correctly?
- Do you see any obvious errors?
- How would you modify it to be easier to read?
"""
import datetime
def create_time_from_time_stamp(timestamp: str) -> datetime.time:
"""Create a datetime.time object from a string in the form 'hh:mm:ss'.
Args:
timestamp - string containing a timestamp in the format 'hh:mm:ss'
Returns:
a datetime.time object with value equal to the timestamp
Raises:
ValueError if timestamp is not a string in form "hh:mm:ss"
Example:
>>> t = create_time_from_time_stamp("9:23:15")
>>> type(t)
<class 'datetime.time'>
>>> print(t)
09:23:15
"""
args = timestamp.split(":")
if len(args) != 3:
raise ValueError('Timestamp must be "hh:mm:ss"')
(hour, minute, second) = args
# if the timestamp is not valid, this may raise TypeError or ValueError
if is_valid_time(int(hour), int(minute), int(second)):
return datetime.time(int(hour), int(minute), int(second))
def is_valid_time(hour, minute, second):
"""Verify hour, minute and second is valid.
Return:
bollean
Raise:
ValueError if hour, minute and second is can't cast to integer
"""
return 0 <= int(hour) <= 23 and 0 <= int(minute) < 60 and 0 <= int(second) < 60
| true |
b165e4716acc1f284a4cf61a705bcbaf890ed0fd | Easwar737/Python | /Leetcode(Easy) - Python/Merge Sorted Array.py | 511 | 4.25 | 4 | """Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
The number of elements initialized in nums1 and nums2 are m and n respectively.
You may assume that nums1 has enough space (size that is equal to m + n) to hold additional elements from nums2."""
# I have manually given the input. This one works perfectly for other testcases too.
nums1=[1,2,3,0,0,0]
nums2=[2,5,6]
n=3
m=3
i=m
j=0
while i<m+n:
nums1[i]=nums2[j]
j+=1
i+=1
nums1.sort() | true |
b5727fe7e40761851ee3bf15dd4f823e095bbffe | Easwar737/Python | /Leetcode(Easy) - Python/Reverse String.py | 440 | 4.375 | 4 | """Write a function that reverses a string. The input string is given as an array of characters char[].
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
You may assume all the characters consist of printable ascii characters."""
# I have manually given the input. This one works perfectly for other testcases too.
s=["h","e","l","l","o"]
s[::1]=s[-1::-1] | true |
0b177c83a545094356916ac6b2303bb0d62b1a98 | Easwar737/Python | /Python/Check if string begins with IS.py | 206 | 4.28125 | 4 | string=input("Enter a string:")
def check_is(string):
if(string[:2]=="Is"):
return string
else:
return "Is"+string
result=check_is(string)
print("The String is:"+result) | true |
cb3b1827185a613db3fdbbc25b12d5c9581583ea | Easwar737/Python | /Leetcode(Easy) - Python/Smallest Number Greater than Target.py | 549 | 4.15625 | 4 | """Given a list of sorted characters letters containing only lowercase letters, and given a target letter target,
find the smallest element in the list that is larger than the given target.
Letters also wrap around. For example, if the target is target = 'z' and letters = ['a', 'b'], the answer is 'a'."""
# I have manually given the input. This one works perfectly for other testcases too.
target="a"
letters=["c", "f", "j"]
if target>=letters[-1]:
return letters[0]
for i in letters:
if ord(i)>ord(target):
return i | true |
814cf4c7cd684e2324695b058e58d3e03356a3b2 | pradeep-sukhwani/Learn-Python-The-Hard-Way-by-Zed-Shaw | /Learn Python The Hard Way/ex30-2.py | 1,060 | 4.40625 | 4 | # assigning the varibles.
people = 30
cars = 40
trucks = 15
# here if/elif/else statement starts.
# here if statement will execute when cars is greater than people.
# or elif statement will execute when cars is less than people.
# or lastly else statement will execute when both of above is not possible.
if cars > people:
print "We should take the cars."
elif cars < people:
print "We should not take the cars."
else:
print "We can't decide."
# here if statement will execute when trucks is greater than cars.
# or elif statement will execute when trucks is less than cars.
# or lastly if both of above statement is not possible then else statement will execute.
if trucks > cars:
print "That's too many trucks."
elif trucks < cars:
print "Maybe we could take the trucks."
else:
print "We still can't decide."
# here if statement will execute when trucks is greater than cars.
# or else statement will execute.
if people > trucks:
print "Alright, let's just take the trucks."
else:
print "Fine, let's stay home then." | true |
b5b2343924052746b7c30a49eb6f0e1e3e55873e | pradeep-sukhwani/Learn-Python-The-Hard-Way-by-Zed-Shaw | /Learn Python The Hard Way/ex24-2.py | 1,786 | 4.5625 | 5 | # Print statement is used to print the following string.
# Here in 2ns statement first we have a single escapes character, then we have
# we have a escape character than new line escape character and horizontal tab.
print "Let's pratice everything."
print 'You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.'
# Here triple quotation is used for extended string.
# in 1st line we have a horizontal tab, 3rd line new line,
# 6th line a new line and 2 times horizontal tab.
poem = """
\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires an explanation
\n\t\twhere there is none.
"""
# Print statement is used to print the following string.
print "--------------"
print poem
print "--------------"
# Assigned a new variable 'five' which has a
# string conversion character which will print the total of number of a variable 'five'
five = 10 - 2 + 3 - 6
print "This should be five: %s" % five
# Declared a function.
# assigned new variables
# then we use return statement to return the values to its caller.
def secret_formula(started):
jelly_beans = started * 500
jars = jelly_beans / 1000
crates = jars / 100
return jelly_beans, jars, crates
# Assigned a new variable 'start_point'.
# Assigned a new variable i.e. equal to a function.
start_point = 10000
beans, jars, crates = secret_formula(start_point)
print "With a starting point of: %d" % start_point
print "We'd have %d beans, %d jars, and %d crates." % (beans, jars, crates)
# Changed the value of the variable.
start_point = start_point / 10
print "We can also do that this way:"
print "We'd have %d beans, %d jars, and %d crates." % secret_formula(start_point) | true |
7209b7b5fea5a3b74c49a80ab2b8e6ad064797d6 | pradeep-sukhwani/Learn-Python-The-Hard-Way-by-Zed-Shaw | /Learn Python The Hard Way/ex6.py | 1,472 | 4.65625 | 5 | # Here I'm assigning a variable x equal to the string with character (%) inside the string to put
# formatted variable inside the strings.
x = "There are %d types of people." % 10
# Here I'm assigning a variable binary equal to the string.
binary = "binary"
# Here I'm assigning a variable do_not equal to a string.
do_not = "don't"
# Here I'm assigning a variable y equal to the string with character (%) inside the string to use
# shortkey which we have assigned earlier.
y = "Those who know %s and those who %s." % (binary, do_not)
# Here I'm printing x and y.
print x
print y
# Here I'm printing a string with a character (%) inside the string and r carries a raw data of a
# variable x
print "I said: %r." % x
# Here I'm printing a string with a character (%) and has another string inside the string and r
# carries a raw data of a variable y
print "I also said: '%s'." %y
# Here I'm assigning a variable equal to boolean character False.
hilarious = False
# Here I'm assigning a variable equal to the string with a character (%), here r carries the raw data
# of a variable 'halarious'.
joke_evaluation = "Isn't that joke so funny?! %r"
# Here I'm printing two variables.
print joke_evaluation % hilarious
# Here I'm assigning two variables equal to the string.
w = "This is the left side of..."
e = "a string with a right side."
# Here I'm printing two variables and joining them with a '+' sign
print w + e | true |
9ddfd8e504fc9d61b529ba38deabadad016bf615 | LuanaDeMoraes/code | /list.py | 2,962 | 4.3125 | 4 | listHeros=["Ryu","Ken","Guile","E. Honda"];
listBadGuys=["Bison","Vega", "Sagat"];
print("--- Loop a list ---");
for element in listHeros:
print(element);
print("--- len() ---")
print ("listHeros size:"+ str(len(listHeros)))
print("--- append() ---")
#append(): append the object to the end of the list.
listHeros.append("Blanka")
for element in listHeros:
print(element)
print ("listHeros size:"+ str(len(listHeros)))
print("--- insert() ---")
#insert(): inserts the object before the given index.
listHeros.insert(2,"Dalcin");
for element in listHeros:
print(element)
print ("List size:"+ str(len(listHeros)))
print("--- extend() or + ---")
#List Concatenation: We can use + operator to concatenate multiple lists and create a new list.
listAll=listHeros+listBadGuys;
print ("ListAll size:"+ str(len(listAll)))
for element in listAll:
print(element);
print("--- clonning [:] ---")
#cloning a list
clonedList= listAll[:];
print("Cloned list:");
clonedList[1]="Rafael";
for element in clonedList:
print(element);
print("Original list:");
for element in listAll:
print(element);
print("--- in: searching within a list ---")
#Verify if an element is within a list
if "Balrog" in listBadGuys:
print ("Balrog is in the list")
else:
print("Balrog is not in the list")
#Verify if an element is within a list
if "Ryu" in listHeros:
print ("Ryu is in the list")
print("--- index() ---")
#list.index(elem) -- searches for the given element from the start of the list and returns its index. Throws a ValueError if the element does not appear (use "in" to check without a ValueError).
guileIndex=listHeros.index("Guile")
print ("guileIndex:"+str(guileIndex))
#cammyIndex=listHeros.index("Cammy")
#print ("cammyIndex:"+str(cammyIndex))
print("--- remove() ---")
#list.remove(elem) -- searches for the first instance of the given element and removes it (throws ValueError if not present)
print ("listHeros size:"+ str(len(listHeros)))
listHeros.remove("Ryu");
print ("listHeros size:"+ str(len(listHeros)))
print("--- pop() ---")
#list.pop(index) -- removes and returns the element at the given index. Returns the rightmost element if index is omitted (roughly the opposite of append()).
for element in listHeros:
print(element)
print ("listHeros size:"+ str(len(listHeros)))
el=listHeros.pop()
print("Removed with pop(): "+str(el))
print ("listHeros size:"+ str(len(listHeros)))
print("--- pop(index) ---")
for element in listHeros:
print(element)
el=listHeros.pop(1)
print("Removed with pop(index): "+str(el))
print ("listHeros size:"+ str(len(listHeros)))
print("--- sort() ---")
#list.sort() -- sorts the list in place (does not return it). (The sorted() function shown later is preferred.)
listHeros.sort()
for element in listHeros:
print(element)
print("--- reverse() ---")
#list.reverse() -- reverses the list in place (does not return it)
listHeros.reverse()
for element in listHeros:
print(element)
| true |
64bf9d9238803c2fc4eeb6204f044b5b9e918480 | PeithonKing/Python_Help | /Shubhankar sir Homework/7th April/simple.py | 272 | 4.125 | 4 | def add():
print("sum = " + str(sum(numbers)))
def avg():
print("average = " + str(sum(numbers)/len(numbers)) + "\n")
while True:
startnum = int(input("Enter startnum: "))
endnum = int(input("Enter endnum: "))
numbers = list(range(startnum, endnum+1))
add()
avg()
| false |
da288fc3c1398f48aa81773b67133ee7ecb15bb5 | Daniel780106/Daniel780106.github.io | /practice.py | 342 | 4.125 | 4 | a1=int(input("Please insert number1 here: "))
a2=int(input("Please insert number2 here: "))
result=input("Please pick one calculation: +,-,*,/: ")
if result=="+":
print(a1+a2)
elif result=="-":
print(a1-a2)
elif result=="*":
print(a1*a2)
elif result=="/":
print(a1/a2)
else:
print("Wrong picking Calcuation")
| false |
c66608b1f28e162934291a44b8afedc7818e9d33 | hao5959/Big_Data | /Algorithm/linkedList.py | 1,228 | 4.1875 | 4 | # implement a linked list
class Node:
def __init__(self, data):
self.data = data
self.next = None
def __repr__(self):
return self.data
class LinkedList:
def __init__(self, nodes = None):
self.head = None
if nodes is not None:
node = Node(data = nodes.pop(0))
self.head = node
for elm in nodes:
node.next = Node(data = elm)
node = node.next
def __iter__(self):
node = self.head
while node is not None:
yield node
node = node.next
# def __repr__(self):
# node = self.head
# nodes = []
# while node is not None:
# nodes.append(node.data)
# node = node.next
# nodes.append('None')
# return '->'.join(nodes)
def add_first(self, node):
node.next = self.head
self.head = node
llist = LinkedList(['a', 'b', 'c', 'd'])
# # print(llist)
# first_node = Node('a')
# llist.head = first_node
# # print(llist)
# second_node = Node('b')
# third_node = Node('c')
# first_node.next = second_node
# second_node.next = third_node
# llist.add_first(Node('z'))
print(llist)
| true |
dd4ee0356fcb8239f7e741d43a082cc298d0998e | whisper1225/algorithm | /src/com/whisper/selftest/binaryNum.py | 333 | 4.25 | 4 | #coding:utf-8
'''
the num of binary
求一个int整数的二进制含有1的个数
'''
def binnaryNum(int):
if(int == 0):
return 0
count = 1
while(int & (int -1)): #核心代码 int = int & (int -1) 但是Python语法支持
int = int & (int - 1)
count +=1
return count
print binnaryNum(7)
| false |
5b24efe39263e41cb28c84cfa49546b52327bc65 | akb46mayu/Data-Structures-and-Algorithms | /BinaryTree and Divide and Conquer/le114_flattenBinaryTreeToLinkedList.py | 1,196 | 4.34375 | 4 | """
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def flatten(self, root):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify root in-place instead.
"""
if not root:
return
self.lastNode = None
self.dfsHelper(root)
def dfsHelper(self, root): # i am not familiar with this case when reference is a node not a list/dict
if not root:
return
if self.lastNode:
self.lastNode.left = None
self.lastNode.right = root
self.lastNode = root
right = root.right
self.dfsHelper(root.left) # after this step root's location (direction) has been changed
self.dfsHelper(right)
| true |
76e9d55ceb01b7de7e1fdaad8b89090d32a9d5b8 | Erksters/code | /python/monkey.py | 1,446 | 4.3125 | 4 | ## Monkey.py by Jordan Scales (scalesjordan@gmail.com, http://ilictronix.com)
## Date: 4/2/2010
##
## Description: Takes a string and randomly types keys until the desired
## string has been typed (in order)
##
## Tips: Python is pretty damn slow, so don't try anything
## too out of the ordinary. Only a few letters is practical.
from random import randint
goal = str(raw_input('Enter a string for the monkey to type: ')).lower()
current = ''
count = 0
def format(number): # just adds commas to the number
final = ''
string = str(number)
length = len(string)
instances = (length - 1) / 3
if length % 3 == 0: # choose a good starting point
start = 3 # place of first comma
else:
start = length % 3
final += string[:start] # gradually piece together the string
for i in range(instances): # with commas
pos = start + i * 3
final += ',' + string[pos:pos+3]
return final
print 'The monkey is typing...'
while current <> goal: # strings should be same length
count += 1
current += chr(randint(0,25) + 97) # add a random letter
if len(current) > len(goal):
current = current[-(len(goal)):] # trim off what wastes memory
print 'It took the monkey %s keystrokes to type "%s"' % (format(count), goal)
| true |
1d710690104c00ac66ec5905254cdfb783a9cbaf | saurabhgupta2104/Coding_solutions | /GFG/Minimum_Swaps_to_Sort.py | 1,844 | 4.21875 | 4 | # https://practice.geeksforgeeks.org/problems/minimum-swaps/1
"""
Given an array of integers. Find the minimum number of swaps required to sort the array in non-decreasing order.
Input:
The first line of input contains an integer T denoting the no of test cases. Then T test cases follow. Each test case contains an integer N denoting the no of element of the array A[ ]. In the next line are N space separated values of the array A[ ] .
Output:
For each test case in a new line output will be an integer denoting minimum umber of swaps that are required to sort the array.
Constraints:
1 <= T <= 100
1 <= N <= 105
1 <= A[] <= 106
User Task:
You don't need to read input or print anything. Your task is to complete the function minSwaps() which takes the array arr[] and its size N as inputs and returns an integer denoting the minimum number of swaps required to sort the array. If the array is already sorted, return 0.
Expected Time Complexity: O(NlogN).
Expected Auxiliary Space: O(N).
Example(To be used only for expected output):
Input:
2
4
4 3 2 1
5
1 5 4 3 2
Output:
2
2
Explanation:
Test Case 1: We need two swaps, swap 1 with 4 and 3 with 2 to make it sorted.
Test Case 2: We need two swaps, swap 2 with 5 and 3 with 4 to make it sorted.
"""
def minSwaps(arr, n):
import copy
# Code here
if n == 1:
return 0
slis = copy.copy(arr)
slis.sort()
count = 0
v = set()
d = {}
for i in range(n):
d[slis[i]] = i
if arr[i] == slis[i]:
v.add(i)
for ind in range(n):
if ind in v:
continue
c = -1
while(1):
if ind not in v:
v.add(ind)
ind = d[arr[ind]]
count += 1
else:
break
count += c
return count
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.