blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
41b44b20257c4a5e99ca9af99d7ca7fc7066ed1c
|
Lesikv/python_tasks
|
/python_practice/matrix_tranpose.py
| 654
| 4.1875
| 4
|
#!usr/bin/env python
#coding: utf-8
def matrix_transpose(src):
"""
Given a matrix A, return the transpose of A
The transpose of a matrix is the matrix flipped over it's main diagonal, switching the row and column indices of the matrix.
"""
r, c = len(src), len(src[0])
res = [[None] * r for i in range(c)]
for i in range(len(src)):
for j in range(len(src[i])):
res[j][i] = src[i][j]
return res
def test_1():
assert matrix_transpose([[1], [2]]) == [[1, 2]]
def test_2():
assert matrix_transpose([[1, 2], [3, 4]]) == [[1, 3], [2,4]]
if __name__ == '__main__':
test_1()
test_2()
| true
|
485fd356a2b3da8cd0db30d1d83714ef64d174f2
|
anubhavcu/python-sandbox-
|
/conditionals.py
| 1,765
| 4.15625
| 4
|
x = 50
y = 50
# if-else: <, >, ==
# if x > y:
# print(f'{x} is greater than {y}')
# else:
# print(f'{x} is smaller than {y}')
if x > y:
print(f'{x} is greater than {y}')
elif x < y:
print(f'{x} is smaller than {y}')
else:
print("Both numbers are equal")
# logical operators - and, or, not
x = 5
if x > 2 and x < 10:
print(f'{x} is greater than 2 and less than 10')
if x > 2 or x <= 10:
print(f'{x} is greater than 2 or less than 10')
if not(x == y):
print(f'{x} is not equal to {y}')
# membership operators -not , not in
numbers = [1, 2, 3, 4, 5]
if x in numbers:
print(x in numbers)
if y not in numbers:
print(y not in numbers)
# identity operators - is, is not
if x is y:
print(x is y)
if x is not y:
print('x is not y', x is not y)
if type(x) is int:
print('x is int type')
l1 = []
l2 = []
l3 = l1
l4 = l3 + l1
print('l1 == l2', l1 == l2) # true
print('l1 is l2', l1 is l2) # false
print('l1 == l3', l1 == l3) # true
print('l1 is l3', l1 is l3) # true
print('l4 is l3', l4 is l3) # false
# == and is are slightly different -
# == checks if values of both variables are same
# is checks whether variable point to the same object
# l1 is l2 returns false as two empty lists are at different memory locations , hence l1 and l2 refer to different objects - we can check that by id(l1) and id(l2)
# l4 is l3 return false as concatenation of two lists always produce a new list
a = 1
f = a
print('a', a, id(a))
print('f', f, id(f))
print(f is a)
a = 2
print('a', a, id(a))
print('f', f, id(f))
print(f is a)
# note when doing f = a, f now refers to the value a is referring to (not a), so when we change value of a,say to 2, then a will refer to 2 but f is referring to 1.
| false
|
c70cbbe6dd0107e74cd408a899dc6bbe77432829
|
reenadhawan1/coding-dojo-algorithms
|
/week1/python-fundamentals/selection_sort.py
| 1,044
| 4.15625
| 4
|
# Selection Sort
x = [23,4,12,1,31,14]
def selection_sort(my_list):
# find the length of the list
len_list = len(my_list)
# loop through the values
for i in range(len_list):
# for each pass of the loop set the index of the minimum value
min_index = i
# compare the current value with all the remaining values in the array
for j in range(i+1,len_list):
# to update the min_index if we found a smaller int
if my_list[j] < my_list[min_index]:
min_index = j
# if the index of the minimum value has changed
# we will make a swap
if min_index != i:
# we could do the swap like this
# temp = my_list[i]
# my_list[i] = my_list[min_index]
# my_list[min_index] = temp
# but using tuple unpacking to swap values here makes it shorter
(my_list[i], my_list[min_index]) = (my_list[min_index], my_list[i])
# return our array
return my_list
print selection_sort(x)
| true
|
249cbda74673f28d7cc61e8be86cdfef2b855e2a
|
Bharadwaja92/DataInterviewQuestions
|
/Questions/Q_090_SpiralMatrix.py
| 414
| 4.4375
| 4
|
"""""""""
Given a matrix with m x n dimensions, print its elements in spiral form.
For example:
#Given:
a = [ [10, 2, 11],
[1, 3, 4],
[8, 7, 9] ]
#Your function should return:
10, 2, 11, 4, 9, 7, 8, 1, 3
"""
def print_spiral(nums):
# 10, 2, 11, 4, 9, 7, 8, 1, 3
# 4 Indicators -- row start and end, column start and end
return
a = [[10, 2, 11],
[1, 3, 4],
[8, 7, 9]]
print_spiral(a)
| true
|
8b2af30e0e3e4fc2cfefbd7c7e9a60edc42538c0
|
Bharadwaja92/DataInterviewQuestions
|
/Questions/Q_029_AmericanFootballScoring.py
| 2,046
| 4.125
| 4
|
"""""""""
There are a few ways we can score in American Football:
1 point - After scoring a touchdown, the team can choose to score a field goal
2 points - (1) after scoring touchdown, a team can choose to score a conversion,
when the team attempts to score a secondary touchdown or
(2) an uncommon way to score, a safety is score when the opposing team causes the ball to
become dead
3 points - If no touchdown is scored on the possession, a team can attempt to make a field goal
6 points - Awarded for a touchdown
Given the above, let's assume the potential point values for American Football are:
2 points - safety
3 points - only field goal
6 points - only touchdown
7 points - touchdown + field goal
8 points - touchdown + conversion
Given a score value, can you write a function that lists the possible ways the score could have been achieved?
For example, if you're given the score value 10, the potential values are:
8 points (touchdown + conversion) + 2 points (safety)
6 points (only touchdown) + 2x2 points (safety)
7 points (touchdown + field goal) + 3 points (only field goal)
5x2 points (safety)
2x2 points (safety) + 2x3 points (only field goal)
"""
from collections import Counter
# A different version of Coin Change
possible_scores = []
def get_possible_ways(score, points, partial=[]):
s = sum(partial)
if s == score:
possible_scores.append(partial)
if s >= score:
return
for i in range(len(points)):
p = points[i]
remaining = points[i: ]
get_possible_ways(score=score, points=remaining, partial=partial+[p])
return 0
points_dict = {2: 'safety', 3: 'only field goal', 6: 'only touchdown', 7: 'touchdown + field goal',
8: 'touchdown + conversion'}
points = list(points_dict.keys())
print(points)
print(get_possible_ways(10, points))
print(possible_scores)
for ps in possible_scores:
d = dict(Counter(ps))
sent = ['{} * {} = {} Points'.format(d[v], points_dict[v], v) for v in d]
print(sent)
| true
|
604a4bb01ff02dc0da1ca2ae0ac71e414c5a6afe
|
Bharadwaja92/DataInterviewQuestions
|
/Questions/Q_055_CategorizingFoods.py
| 615
| 4.25
| 4
|
"""""""""
You are given the following dataframe and are asked to categorize each food into 1 of 3 categories:
meat, fruit, or other.
food pounds
0 bacon 4.0
1 STRAWBERRIES 3.5
2 Bacon 7.0
3 STRAWBERRIES 3.0
4 BACON 6.0
5 strawberries 9.0
6 Strawberries 1.0
7 pecans 3.0
Can you add a new column containing the foods' categories to this dataframe using python?
"""
import pandas as pd
df = pd.DataFrame(columns=['food', 'pounds'])
df['category'] = df['food'].apply(lambda f: 'fruit' if f.lower() in ['strawberries'] else 'meat' if f.lower() == 'bacon' else 'other')
| true
|
015f6e785a2d2b8f5ebe76197c15b8dd335526cc
|
code4nisha/python8am
|
/day4.py
| 1,594
| 4.375
| 4
|
x = 1/2+3//3+4**2
print(x)
# name = 'sophia'
# print(name)
# print(dir(name))
# print(name.capitalize)
# course = "we are learning python"
# print(course.title())
# print(course.capitalize())
# learn = "Data type"
# print(learn)
# learn = "python data types"
# print(learn.title())
# data =['ram',123,1.5]
# print(data[1])
# negative index
# b = "Hello, World!"
# print(b[-5:-2])
# Strings
# strings in python are single or double quotation marks
# print('Hello')
# print("Hello")
# Multiline Strings
# We can use three double quotes
# a ="""Lorem ipsum dolor sit amet
# consectetur adipiscing alit,
# sed do eiusmod tempor incididunt
# ut labore et dolore magna aliqua."""
# print(a)
# Length string
# a = "Hello, World!"
# print(len(a))
# slicing
# b = "Hello, World!"
# print(b[2:5])
# replace string
# a = "Hello, World!"
# print(a.replace("H", "J"))
# format string
# age = 36
# txt ="My name is John, and I am {}"
# print(txt.format(age))
# we can use %s also in formatting
# print("I love %s in %s" % ("programming", "Python"))
# 'I love programming in python'
# if we have more num then
# quantity = 3
# itemno = 567
# price = 49.95
# myorder = "I want {} pieces of item {} for dollars."
# print(myorder.format(quantity, itemno,price))
# escape character
# the escape charater allows you to use double quotes when you normally would not be allowed
# txt = "We are the so-called \"Vikings\" from the north."
# print(txt)
# text = "I'm fine"
# print(text"I'm fine")
# tuple
# x = ("apple", "banana", "cherry")
# y = list(x)
# y[1] = "kiwi"
# x = tuple(y)
# print(x)
| false
|
58401ce6e6a3876062d2a629d39314432e08b64f
|
mattling9/Algorithms2
|
/stack.py
| 1,685
| 4.125
| 4
|
class Stack():
"""a representation of a stack"""
def __init__(self, MaxSize):
self.MaxSize = MaxSize
self.StackPointer = 0
self.List = []
def size(self):
StackSize = len(self.List)
return StackSize
def pop(self):
StackSize = self.StackSize()
if StackSize > 0:
self.items.pop()
self.StackPointer = StackSize
else:
print("There are no items in the stack")
def push(self, item ):
size()
StackSize = self.StackSize()
if self.StackSize < MaxSize:
self.List.append(item)
self.StackPoitner = StackSize
else:
print("The stack is full")
def peek(self):
size()
StackSize = self.StackSize
if StackSize == 0:
print(" the stack is empty")
else:
print("The top item is {0}".format(self.List[StackSize-1]))
def main():
CustomStack = Stack(5)
Done = False
while Done == False:
print("Please select an option")
print()
print("1. Peek")
print("2. Push")
print("3. Pop")
print("4. Exit")
choice = int(input())
if choice == 1:
CustomStack.peek()
elif choice == 2:
CustomStack.push()
elif choice == 3:
CustomStack.pop()
elif choice == 4:
Done = True
while choice < 2 or choice > 4:
print("Please enter a valid number")
choice=int(input())
if __name__ == "__main__":
main()
| true
|
31b272d2675be1ecfd20e9b4bae4759f5b533106
|
iemeka/python
|
/exercise-lpthw/snake6.py
| 1,792
| 4.21875
| 4
|
#declared a variable, assigning the string value to it.
#embedded in the string is a format character whose value is a number 10 assigned to it
x = "There are %d types of people." % 10
#declared a variable assigning to it the string value
binary = "binary"
#same as above
do_not = "don't"
# also same as above but with who format characters whose values variables
# hence the value of the two format characters equals the value of the two variables assigned to the format character
y = "Those who know %s and those who %s." % (binary, do_not)
# told python to print the values of the variable x
print x
# told python to print the values of the variable y
print y
# here python has the print a string in which a format character is embedded and whose value is he
# the values of he variable x
print "I said: %r." % x
# same here ...which value is the values of the variable y
print " I also said: '%s'. " % y
#assigned a boolean to a variable
hilarious = False
# declared a variable assigning assigning to it a string with an embedded format character
joke_evaluation = "Isn't that joke so funny?! %r"
# told python to print the value of the variable which is a string which a format character
# is embedded in it then assigning the value of the embedde character in the string the value
# of another variable.
# so python has to print a variable value assigning a variable to the format character in the first variable value
print joke_evaluation % hilarious
w = "This is the left side of..."
e = "a string with a right side."
# here python simply joined two stings together using the operator + thats why is makes
# a longer string. In javaScript is called concatenation of strings (learnt javaScript initially) tongue out* <(-,-)>
print w + e
# yes! they are four places fuck you shaw!
| true
|
ed10b4f7cebef6848b14803ecf76a16b8bc84ca4
|
iemeka/python
|
/exercise-lpthw/snake32.py
| 713
| 4.40625
| 4
|
the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
# this first kind of for-loop goes through a list
for number in the_count:
print "This is count %d" % number
# same as above
for fruit in fruits:
print "A fruit of type: %s" % fruit
for i in change:
print "I got %r" % i
elements = []
# range function to do 0 to 5 counts
for i in range(0, 6):
print "Adding %d to the list." % i
# append is a function that lists understands
elements.append(i)
print "Element was: %d" % i
print elements.pop(0)
print elements[1:3]
elements[3] = "apple"
print elements
del elements[2]
print elements
print len(elements)
print elements[2]
| true
|
bb1a2972bc806e06fe6302c703c158130318bf07
|
iemeka/python
|
/exercise-lpthw/snake20.py
| 1,128
| 4.21875
| 4
|
from sys import argv
script, input_file = argv
# a function to read the file held and open in the variable 'current_file' and then passed..
# the variable is passed to this functions's arguement
def print_all(f):
print f.read()
# seek takes us to the begining of the file
def rewind(f):
f.seek(0)
# we print the numer of the line we want to read and the we print the content of the line
# the comma makes sure the 'print' doesnt end with newline
def print_a_line(line_count, f):
print line_count, f.readline(),
current_file = open(input_file)
print "First let's print the whole file:\n"
# calling the function print_all'
print_all(current_file)
print "Now lets rewind, kind of like a tape"
# calling the function 'rewind'
rewind(current_file)
print "Let's print three lines:"
#calling functions
current_line = 1
print_a_line(current_line, current_file)
# current_line = 1 (initially) plus another 1. current lines = 2
current_line +=1
print_a_line(current_line, current_file)
# current_line = 2 (from the last global variable) plus another 1. current lines = 3
current_line +=1
print_a_line(current_line, current_file)
| true
|
3d3bb07c0afda8d2c9943a39883cbbee67bfe4b1
|
icgowtham/Miscellany
|
/python/sample_programs/tree.py
| 2,130
| 4.25
| 4
|
"""Tree implementation."""
class Node(object):
"""Node class."""
def __init__(self, data=None):
"""Init method."""
self.left = None
self.right = None
self.data = data
# for setting left node
def set_left(self, node):
"""Set left node."""
self.left = node
# for setting right node
def set_right(self, node):
"""Set right node."""
self.right = node
# for getting the left node
def get_left(self):
"""Get left node."""
return self.left
# for getting right node
def get_right(self):
"""Get right node."""
return self.right
# for setting data of a node
def set_data(self, data):
"""Set data."""
self.data = data
# for getting data of a node
def get_data(self):
"""Get data."""
return self.data
# Left -> Root -> Right: ./\.
def in_order(node):
"""In-order traversal (Left->Root->Right)."""
if node:
in_order(node.get_left())
print(node.get_data(), end=' ')
in_order(node.get_right())
return
# Root -> Left ->Right: \._.
def pre_order(node):
"""Pre-order traversal (Root->Left->Right)."""
if node:
print(node.get_data(), end=' ')
pre_order(node.get_left())
pre_order(node.get_right())
return
# Left -> Right -> Root: ._.\
def post_order(node):
"""Post-order traversal (Left->Right->Root)."""
if node:
post_order(node.get_left())
post_order(node.get_right())
print(node.get_data(), end=' ')
return
if __name__ == '__main__':
root = Node(1)
root.set_left(Node(2))
root.set_right(Node(3))
root.left.set_left(Node(4))
print('In-order Traversal:')
in_order(root)
print('\nPre-order Traversal:')
pre_order(root)
print('\nPost-order Traversal:')
post_order(root)
# OUTPUT:
# Inorder Traversal:
# 4 2 1 3
# Preorder Traversal:
# 1 2 4 3
# Postorder Traversal:
# 4 2 3 1
| true
|
1eb9a54a4c86c72594064717eb0cd65c6376421d
|
icgowtham/Miscellany
|
/python/sample_programs/algorithms/quick_sort_v1.py
| 1,352
| 4.125
| 4
|
# -*- coding: utf-8 -*-
"""Quick sort implementation in Python."""
def partition(array, begin, end):
"""Partition function."""
pivot_idx = begin
"""
arr = [9, 3, 4, 8, 1]
pivot = 0
i = 1, begin = 0
3 <= 9 -> swap -> [3, 9, 4, 8, 1]
pivot = 1
i = 2, pivot = 1
4 <= 9 -> swap -> [3, 4, 9, 8, 1]
pivot = 2
i = 3, pivot = 2
8 <= 9 -> swap -> [3, 4, 8, 9, 1]
pivot = 3
i = 4, pivot = 3
1 <= 9 -> swap -> [3, 4, 8, 1, 9]
pivot = 4
i = 5, pivot = 4
"""
for i in range(begin + 1, end + 1):
if array[i] <= array[begin]:
pivot_idx += 1
array[i], array[pivot_idx] = array[pivot_idx], array[i]
array[pivot_idx], array[begin] = array[begin], array[pivot_idx]
print(array)
return pivot_idx
def quick_sort_recursion(array, begin, end):
"""Recursive function."""
if begin >= end:
return
pivot_idx = partition(array, begin, end)
print(pivot_idx)
quick_sort_recursion(array, begin, pivot_idx - 1)
quick_sort_recursion(array, pivot_idx + 1, end)
def quick_sort(array, begin=0, end=None):
"""Quick sort function."""
if end is None:
end = len(array) - 1
return quick_sort_recursion(array, begin, end)
if __name__ == '__main__':
arr = [9, 3, 4, 8, 1]
quick_sort(arr)
print(arr)
| false
|
55b9c9b05bcaa82321000ef230e049cab763a7f9
|
sovello/palindrome
|
/palindrome_recursive.py
| 632
| 4.28125
| 4
|
from re import *
def reverseChar(word = '' ):
reversed_word = ''
for letter in word:
if len(word) == 1:
reversed_word = reversed_word + word
else:
reversed_word = reversed_word+word[-1]
word = word[:len(word)-1]
reverseChar(word)
return reversed_word
word = input("Write some text: ")
# determine if the text is palindrome or not
reversed_word = sub(r'[^A-Za-z]', "",reverseChar(word))
original_word = sub(r'[^A-Za-z]', "", word)
if original_word.lower() == reversed_word.lower():
print("is a palindrome")
else:
print("is not a palindrome")
| false
|
87661803c954900ef11a81ac450ffaaf76b83167
|
truas/kccs
|
/python_overview/python_database/database_03.py
| 1,482
| 4.375
| 4
|
import sqlite3
'''
The database returns the results of the query in response to the cursor.fetchall call
This result is a list with one entry for each record in the result set
'''
def make_connection(database_file, query):
'''
Common connection function that will fetch data with a given query in a specific DB
The cursor will be closed at the end of it
'''
connection = sqlite3.connect(database_file)
cursor = connection.cursor()
cursor.execute(query) # if id is available here we can also use cursor.execute(query, [person_id])
results = cursor.fetchall()
cursor.close()
connection.close()
return results
def get_name(database_file, person_id):
'''
Here we get one specific record according to an ID
Different from database_01 we are using variable names to compose our query,
just make sure to compose one string at the end
'''
query = "SELECT personal || ' ' || family FROM Person WHERE id='" + person_id + "';"
results = make_connection(database_file, query)
return results[0][0]
def get_allnames(database_file):
'''
Here we fetch all data in our table, regardless of id
'''
query = "SELECT personal || ' ' || family FROM Person;"
results = make_connection(database_file, query)
return results
print("Full name for dyer:", get_name('survey.db', 'dyer')) # specific id
partial = get_allnames("survey.db") # all results
for item in partial:
print(item[0])
| true
|
5217a281d3ba76965d0cb53a38ae90d16e7d7640
|
truas/kccs
|
/python_overview/python_oop/abstract_animal_generic.py
| 2,001
| 4.25
| 4
|
from abc import ABC, abstractmethod #yes this is the name of the actual abstract class
'''
From the documentation:
"This module provides the infrastructure for defining abstract base classes (ABCs) in Python"
'''
class AbstractBaseAnimal(ABC):
'''
Here we have two methods that need to be implemented by any class that extends AbstractBaseAnimal
'''
@abstractmethod
def feed(self, other_food=None):
print("All animals have to feed!")
@abstractmethod
def sleep(self, state=1):
if state == 1:
print("This animal needs to sleep")
else:
print("This animal does not need to sleep")
# no abstract, we can implement if we want, but it is not required
def exist(self):
print("I am alive!")
class Dolphins(AbstractBaseAnimal):
'''
All the abstract methods need to be implemented otherwise we cannot instantiate any object
from this class
'''
def __init__(self, food="Fish"):
self.food_type = food
'''
Note that the abstract functions need to be implemented, even if with 'pass' (try that)
We don't need to follow the same signature of the function but it has to be implemented
Notice we do not implement the method 'exist()'. Why ? Try to spot the difference between
this exist() and the other methods. That's right, exist() is not an abstract method,
thus we do not need to implement in our class.
'''
# this is an abstract method from our base class
def feed(self, alternative=None):
print("I like to eat ", self.food_type)
print("I can also eat other things, such as ", alternative)
# this is an abstract method from our base class
def sleep(self, state=-1):
if state == 1:
print("This animal needs to sleep.")
elif state == 0:
print("This animal does not need to sleep.")
elif state == -1:
print("This animal only sleeps with half of the brain.")
| true
|
f0c289169c7eea7a8d4675450cda1f36b10c3baf
|
alexeydevederkin/Hackerrank
|
/src/main/python/min_avg_waiting_time.py
| 2,648
| 4.4375
| 4
|
#!/bin/python3
'''
Tieu owns a pizza restaurant and he manages it in his own way. While in a normal restaurant,
a customer is served by following the first-come, first-served rule, Tieu simply minimizes
the average waiting time of his customers. So he gets to decide who is served first,
regardless of how sooner or later a person comes.
Different kinds of pizzas take different amounts of time to cook. Also, once he starts cooking a pizza,
he cannot cook another pizza until the first pizza is completely cooked. Let's say we have three customers
who come at time t=0, t=1, & t=2 respectively, and the time needed to cook their pizzas is 3, 9, & 6 respectively.
If Tieu applies first-come, first-served rule, then the waiting time of three customers is 3, 11, & 16 respectively.
The average waiting time in this case is (3 + 11 + 16) / 3 = 10. This is not an optimized solution.
After serving the first customer at time t=3, Tieu can choose to serve the third customer.
In that case, the waiting time will be 3, 7, & 17 respectively.
Hence the average waiting time is (3 + 7 + 17) / 3 = 9.
Help Tieu achieve the minimum average waiting time. For the sake of simplicity,
just find the integer part of the minimum average waiting time.
input:
3
0 3
1 9
2 6
output:
9
'''
from queue import PriorityQueue
def solve():
queue_arrival = PriorityQueue()
queue_cook_time = PriorityQueue()
end_time = 0
sum_time = 0
num = int(input())
# parse all data and push it in queue_arrival
for i in range(num):
arrival, cook_time = [int(x) for x in input().split()]
queue_arrival.put((arrival, cook_time))
while True:
next_arrival = 0
# pop all arrived by end_time from queue_arrival
# push them into queue_cook_time
if not queue_arrival.empty():
next_arrival = queue_arrival.queue[0][0]
while not queue_arrival.empty() and end_time >= queue_arrival.queue[0][0]:
arrival, cook_time = queue_arrival.get()
queue_cook_time.put((cook_time, arrival))
# pop 1 item from queue_cook_time or move to next_arrival or break
if queue_cook_time.empty():
if queue_arrival.empty():
break
end_time = next_arrival
continue
else:
cook_time, arrival = queue_cook_time.get()
# add waiting time for it to sum_time
# update end_time
end_time += cook_time
sum_time += end_time - arrival
average_time = sum_time // num
print(average_time)
if __name__ == '__main__':
solve()
| true
|
6033592ae372bada65743cdb8cad06e78b5546a4
|
EkataShrestha/Python-Assignment
|
/Assignment 1.py
| 2,195
| 4.125
| 4
|
print(" ASSIGNMENT-1 ")
"-------------------------------------------------------------------------------"
print("Exercise 1:---------------------------------------------------")
width = 17
height = 12.0
delimiter = '.'
##1. width/2:
print("answer number 1 (width/2) is:", width/2)
print( type(width/2) )
##2. width/2.0
print("answer number 2 (width/2.0) is:",width/2.0)
print( type(width/2.0) )
##3. height/3
print("answer number 3 (height/3) is:",height/3)
print( type(height/3) )
##4. 1 + 2 * 5
print("answer number 4 (1 + 2 * 5) is:",1 + 2 * 5)
print( type(1 + 2 * 5) )
##5. delimiter * 5
print("answer number 5 (delimiter * 5) is:",delimiter * 5)
print( type(delimiter * 5) )
"-------------------------------------------------------------------------------"
print("Exercise 2:-----------------------------------------------------------")
Temperature = float(input("Enter temperature in Fahrenheit:"))
Celsius = (Temperature - 32)* 5/9
print("Temperature in Celsius: ",Celsius)
"-------------------------------------------------------------------------------"
print("Exercise 3:-----------------------------------------------------------")
SECONDS_PER_MINUTE= 60
seconds= int(input("Enter number of seconds:"))
minutes= seconds / SECONDS_PER_MINUTE
seconds= seconds % SECONDS_PER_MINUTE
print("the duration is:", "%02d minutes and %02d seconds "% (minutes,seconds))
"-------------------------------------------------------------------------------"
print("Exercise 4:-----------------------------------------------------------")
list= [10,20,30,40,50,60,70,80]
print("List of elements are:", list)
print("length of list:", len(list))
print("first element of the list:", list[0])
print("fourth element of the list:", list[3])
"-------------------------------------------------------------------------------"
print("Exercise 5:-----------------------------------------------------------")
list= [10,20,30,40,50,60,70,80]
print("List of elements are:", list)
print("poping last element:", list.pop())
print(list)
print("inserting '90' in 5th position:", list.insert(5,90))
print(list)
print("removing '20' element from the list:", list.remove(20))
print(list)
| false
|
2b82cd1ea8697747b28486a7987f99dceea7775a
|
mousexjc/basicGrammer
|
/org/teamsun/mookee/senior/c012_1funcType.py
| 452
| 4.53125
| 5
|
"""
Chapter 12 函数式编程
匿名函数
格式:lambda param_list: expression
lambda:关键字
expression * :只能是【表达式】
"""
# 正常函数
def add(x, y):
return x + y
f = lambda x, y: x + y
print(f(2, 3))
print("=====================")
# 三元表达式
# 其他语言:表达式 ?true结果 : false结果
# Python : true结果 if 表达式 else false结果
x = 1
y = 2
a = x if x > y else y
print(a)
| false
|
2e86e6d499de5d51f19051728db135aac6b36044
|
avisek-3524/Python-
|
/oddeven.py
| 260
| 4.1875
| 4
|
'''write a program to print all the numbers from
m-n thereby classifying them as even or odd'''
m=int(input('upper case'))
n=int(input('lower case'))
for i in range(m,n+1):
if(i%2==0):
print(str(i)+'--even')
else:
print(str(i)+'--odd')
| true
|
3d3513f1520a98a06f7047699c4bee78d6e4a00f
|
carolinesekel/caesar-cipher
|
/caesar.py
| 361
| 4.34375
| 4
|
alphabet = "abcdefghijklmnopqrstuvwxyz"
#shift by 5
cipher = "fghijklmnopqrstuvwxyzabcde"
input_string = input("What would you like to encrypt? ")
print("Now encrypting ", input_string, "...")
encrypted = ""
for letter in input_string:
position = alphabet.index(letter)
new_char = cipher[position]
encrypted += new_char
print("Encrypted string: ", encrypted)
| false
|
4a4f0e71027d92fa172f78811993aa1d62e2a6c7
|
JuveVR/Homework_5
|
/Exercise_2.py
| 2,650
| 4.21875
| 4
|
#2.1
class RectangularArea:
"""Class for work with square geometric instances """
def __init__(self, side_a, side_b):
"""
Defines to parameters of RectangularArea class. Checks parameters type.
:param side_a: length of side a
:param side_b:length of side a
"""
self.side_a = side_a
self.side_b = side_b
if type(self.side_a) and type(self.side_b) == int or float:
pass
else:
raise Exception("Wrong type, sides should be int or float")
def square(self):
"""
:return: value of square for class instance
"""
return self.side_a * self.side_b
def perimeter(self):
"""
:return: alue of square for class instance
"""
return (self.side_b + self.side_a)*2
#2.2
class Dot:
"""Defines coordinates of the dot on the map"""
def __init__(self, x, y):
"""
:param x: distance from point x to y-axis
:param y: distance from point y to x-axis
"""
self.x = x
self.y = y
def dist_from_zero_version1(self):
"""
:return: the distance on the plain from the dot to the origin
"""
x1 = 0
y1 = 0
d = ((self.x-x1)**2 + (self.y - y1)**2)**0.5
return d
def dist_from_zero_version2(self, x2=0, y2=0):
"""
:param x2: origin of x-axis (by default)
:param y2: origin of y-axis (by default)
:return: :return: the distance on the plain from the dot to the origin
"""
dv2 = ((self.x-x2)**2 + (self.y - y2)**2)**0.5
return dv2
def between_two_dots(self, x3, y3): # I am not sure that this is correct way to solve your exercise
"""
:param x3: distance from point x to y-axis
:param y3: distance from point y to x-axis
:return: the distance on the plain between two dots
"""
d = ((self.x - x3) ** 2 + (self.y - y3) ** 2) ** 0.5
return d
def three_dimensional(self, z): # Maybe I misunderstood the task. My method looks weird
"""
Converts coordinates to three_dimensional system
:param z: distance from point x to xy plane
:return: coordinates of the dot in three_dimensional system
"""
return (self.x, self.y, z)
if __name__ == "__main__":
rect = RectangularArea(10, 12)
print(rect.square())
print(rect.perimeter())
dot1 = Dot(20,20)
print(dot1.dist_from_zero_version1())
print(dot1.dist_from_zero_version2())
print(dot1.between_two_dots(34.4, 45))
print(dot1.three_dimensional(12))
| true
|
0b0e1f3f55ae4faa409b1fefb704b577aebb6c87
|
saicataram/MyWork
|
/DL-NLP/Assignments/Assignment4/vowel_count.py
| 801
| 4.3125
| 4
|
"""
*************************************************************************************
Author: SK
Date: 30-Apr-2020
Description: Python Assignments for practice;
a. Count no of vowels in the provided string.
*************************************************************************************
"""
def vowel_count(str):
# Initializing count variable to 0
count = 0
# Creating a set of vowels
vowel = set("aeiouAEIOU")
# Loop to traverse the alphabet
# in the given string
for alphabet in str:
# If alphabet is present
# in set vowel
if alphabet in vowel:
count = count + 1
print("No. of vowels :", count)
str = input("Enter a character: ")
# Function Call
vowel_count(str)
| true
|
bd557b8cb881b1a6a0832b347c6855289a7c7cef
|
saicataram/MyWork
|
/DL-NLP/Assignments/Assignment4/lengthofStringinList.py
| 528
| 4.375
| 4
|
"""
*************************************************************************************
Author: SK
Date: 30-Apr-2020
Description: Python Assignments for practice;
a. Count length of the string in list provided.
*************************************************************************************
"""
string = ["mahesh","hello","nepal","Hyderabad","mahesh","Delhi", "Amsterdam", "Tokyo"]
index = len(string)
for i in range (0, index):
count_each_word = len(string[i])
print(count_each_word)
| true
|
d4aa13f6bd5d92ad0445200c91042b1b72f8f4cc
|
lilianaperezdiaz/cspp10
|
/unit4/Lperez_rps.py
| 2,982
| 4.3125
| 4
|
import random
#function name: get_p1_move
# arguments: none
# purpose: present player with options, use input() to get player move
# returns: the player's move as either 'r', 'p', or 's'
def get_p1_move():
move=input("rock, paper, scissors: ")
return move
#function name: get_comp_move():
# arguments: none
# purpose: randomly generates the computer's move,
# either 'r' 'p' or 's'
# returns: the computer's randomly generated move
def get_comp_move():
randy=random.randint(1,3)
if randy==1:
return("rock")
elif randy==2:
return("paper")
elif randy==3:
return("scissors")
return randy
#function name: get_rounds
# arguments: none
# purpose: allows the user to choose a number of rounds from 1 to 9.
# returns: the user-chosen number of rounds
def get_rounds():
rounds=int(input("How many rounds do you want to play 1-9: "))
return rounds
#function name: get_round_winner
# arguments: player move, computer move
# purpose: based on the player and computer's move, determine
# the winner or if it's a tie
# returns: returns a string based on the following:
# "player" if player won
# "comp" if computer won
# "tie" if it's a tie
def get_round_winner(p1move, cmove):
if p1move == cmove:
return("Tie!")
if p1move == "rock" and cmove == "paper":
return("You lose!")
elif p1move == "paper" and cmove == "rock":
return("You win!")
elif p1move == "scissors" and cmove == "rock":
return("You lose!")
elif p1move == "rock" and cmove == "scissors":
return("You win!")
elif p1move == "paper" and cmove == "scissors":
return ("You lose!")
elif p1move == "scissors" and cmove == "paper":
return ("You win!")
#function name: print_score
# arguments: player score, computer score, number of ties
# purpose: prints the scoreboard
# returns: none
def print_score(pscore, cscore, ties):
print("Player score: {}".format(pscore))
print("Computer score: {}".format(cscore))
print("Tie score: {}".format(ties))
#function name: rps
# arguments: none
# purpose: the main game loop. This should be the longest, using
# all the other functions to create RPS
# returns: none
def rps():
pscore=0
cscore=0
ties=0
rounds = get_rounds()
for rounds in range(1, rounds + 1):
p1move = get_p1_move()
randy = get_comp_move()
winner = get_round_winner(p1move, randy)
print ("Computer chose {}".format(randy))
if winner == "You win!":
print("Player won!")
pscore= pscore+1
elif winner =="You lose!":
print("Computer won!")
cscore = cscore +1
else:
print("It's a tie!")
ties = ties+1
print_score(pscore,cscore,ties)
print("_________________________________")
rps()
| true
|
d717960b2780b50a21f2ce7e1a586d08c2937f38
|
huhudaya/leetcode-
|
/LeetCode/212. 单词搜索 II.py
| 2,593
| 4.21875
| 4
|
'''
给定一个二维网格 board 和一个字典中的单词列表 words,找出所有同时在二维网格和字典中出现的单词。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。
同一个单元格内的字母在一个单词中不允许被重复使用。
示例:
输入:
words = ["oath","pea","eat","rain"] and board =
[
['o','a','a','n'],
['e','t','a','e'],
['i','h','k','r'],
['i','f','l','v']
]
输出: ["eat","oath"]
说明:
你可以假设所有输入都由小写字母 a-z 组成。
提示:
你需要优化回溯算法以通过更大数据量的测试。你能否早点停止回溯?
如果当前单词不存在于所有单词的前缀中,则可以立即停止回溯。
什么样的数据结构可以有效地执行这样的操作?
散列表是否可行?为什么? 前缀树如何?
如果你想学习如何实现一个基本的前缀树,请先查看这个问题: 实现Trie(前缀树)。
'''
from typing import List
class Solution:
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
# trie树
root = {}
for word in words:
trie = root
for i in word:
trie = trie.setdefault(i, {})
trie["end"] = "1"
m = len(board)
n = len(board[0])
directions = [[-1, 0], [1, 0], [0, 1], [0, -1]]
marked = [[False] * n for i in range(m)]
res = []
def dfs(i, j, trie, path):
# 剪枝
if board[i][j] not in trie:
return
trie = trie[board[i][j]]
if "end" in trie and trie["end"] == "1":
res.append(path)
# 防止重复加入
trie["end"] = "0"
# 注意,这个marked不能在最上面使用,否则直接return了,就不能回溯了
marked[i][j] = True
for di in directions:
row = i + di[0]
col = j + di[1]
if not (row >= 0 and row < m and col >= 0 and col < n):
continue
if marked[row][col] is True:
continue
dfs(row, col, trie, path + board[row][col])
marked[i][j] = False
for i in range(m):
for j in range(n):
dfs(i, j, root, board[i][j])
return res
Solution().findWords([["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]],["oath","pea","eat","rain"])
| false
|
287660ee7a1580903b9815b83106e8a5bd6e0c20
|
5folddesign/100daysofpython
|
/day_002/day_004/climbing_record_v4.py
| 2,228
| 4.15625
| 4
|
#python3
#climbing_record.py is a script to record the grades, and perceived rate of exertion during an indoor rock climbing session.
# I want this script to record: the number of the climb, wall type, grade of climb, perceived rate of exertion on my body, perceived rate of exertion on my heart, and the date and time of the climbing session. I then want all of this information to be added to a .csv file
import csv
#import the datetime library.
csvFile = open('/Users/laptop/github/100daysofpython/day_004/climbinglog.csv','a',newline='')
csvWriter = csv.writer(csvFile,delimiter=',',lineterminator='\n\n')
#add functions for each question.
climb_number =''
wall_type = ''
grade = ''
pre_heart = ''
pre_body = ''
def climbNumber():
global climb_number
climb_number = input("What number route is this? \n > ")
answer_string = str(climb_number)
if str.isnumeric(answer_string):
pass
else:
print("You must enter a number. Try again. ")
climbNumber()
def wallType():
global wall_type
wall_type = input("What type of wall was the route on? \n >")
if str.isalpha(wall_type):
pass
else:
print("You entered a number, you must enter a word. Try again. ")
wallType()
def grade():
global grade
grade = input("What was the grade of the route? \n >")
answer_string = str(grade)
if answer_string:
pass
else:
print("You must enter a number. Try again. ")
grade()
def preBody():
global pre_body
pre_body = input("On a scale of 1-10, how difficult did this route feel on your body? \n >")
answer_string = str(pre_body)
if str.isnumeric(answer_string):
pass
else:
print("You must enter a number. Try again. ")
preBody()
def preHeart():
global pre_heart
pre_heart = input("On a scale of 1-10, how difficult did this route feel on your heart? \n >")
answer_string = str(pre_heart)
if str.isnumeric(answer_string):
pass
else:
print("You must enter a number. Try again. ")
preHeart()
climbNumber()
wallType()
grade()
preBody()
preHeart()
csvWriter.writerow([climb_number,wall_type,grade,pre_body,pre_heart])
| true
|
6367b485bbbeb065dc379fa1164072db6bac22e4
|
risbudveru/machine-learning-deep-learning
|
/Machine Learning A-Z/Part 2 - Regression/Section 4 - Simple Linear Regression/Simple linear reg Created.py
| 1,590
| 4.3125
| 4
|
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
#X is matrix of independent variables
#Y is matrix of Dependent variables
#We predict Y on basis of X
dataset = pd.read_csv('Salary_data.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 1].values
# Splitting the dataset into the Training set and Test set
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 1/3, random_state = 0)
#Random_state = 0 indicates no randomized factors in algorithm
#Fitting Simple linear regression to Training set
from sklearn.linear_model import LinearRegression
#This class will help us to build models
regresor = LinearRegression() #Here we created a machine
regresor.fit(X_train, y_train) #Machine has learnt
#Now, We'll predict future values based on test set
#y_pred is predicted salary vector
y_pred = regresor.predict(X_test)
#Visualization of Trainning set data
plt.scatter(X_train, y_train, color='red') #Make scatter plot of real value
plt.plot(X_train, regresor.predict(X_train), color='blue') #Plot Predictions
plt.title('Salary vs Exprience(Training Set)')
plt.xlabel('Exprience(Years)')
plt.ylabel('Salary')
plt.show
#Visualization of Test set data
plt.scatter(X_test, y_test, color='red') #Make scatter plot of real value
plt.plot(X_train, regresor.predict(X_train), color='blue') #Plot Predictions
plt.title('Salary vs Exprience(Training Set)')
plt.xlabel('Exprience(Years)')
plt.ylabel('Salary')
plt.show
| true
|
84c9145c5802f5f1b2c2e70b8e2038b573220bd5
|
renan09/Assignments
|
/Python/PythonAssignments/Assign8/fibonacci2.py
| 489
| 4.15625
| 4
|
# A simple generator for Fibonacci Numbers
def fib(limit):
# Initialize first two Fibonacci Numbers
a, b = 0, 1
# One by one yield next Fibonacci Number
while a < limit:
yield a
#print("a : ",a)
a, b = b, a + b
#print("a,b :",a," : ",b)
# Create a generator object
x = fib(5)
# Iterating over the generator object using for
# in loop.
print("\nUsing for in loop")
for i in fib(55):
print("\t\t Series :",i)
| true
|
8fa278a0adcf19426d8b40a82aa53992b685341a
|
itssekhar/Pythonpractice
|
/oddandeven.py
| 515
| 4.125
| 4
|
num=int(input("enter a numer:"))
res=num%2
if(res>0):
print("odd number")
else:
print("even number")
""" Using function"""
def Number(n):
res=n%2
if res>0:
return "odd"
else:
return "even"
Number(2)
"""Using main function for to find an even and odd number """
def tofindoddoreven(n):
if n%2 == 0 :
print("even number")
elif n%2!=0:
print("odd number")
if __name__ == "__main__":
n = int(input("Enter n number:"))
tofindoddoreven(n)
| false
|
be1a6beb03d6f54c3f3d42882c84031cd415dc83
|
shaversj/100-days-of-code-r2
|
/days/27/longest-lines-py/longest_lines.py
| 675
| 4.25
| 4
|
def find_longest_lines(file):
# Write a program which reads a file and prints to stdout the specified number of the longest lines
# that are sorted based on their length in descending order.
results = []
num_of_results = 0
with open(file) as f:
num_of_results = int(f.readline())
for line in f.readlines():
line = line.strip()
results.append([line, len(line)])
sorted_results = sorted(results, reverse=True, key=lambda x: x[1])
for num in range(0, num_of_results):
print(sorted_results[num][0])
find_longest_lines("input_file.txt")
# 2
# Hello World
# CodeEval
# Quick Fox
# A
# San Francisco
| true
|
f99e68cfa634143883bfce882bc3b399bf1f1fcf
|
shaversj/100-days-of-code-r2
|
/days/08/llist-py/llist.py
| 862
| 4.21875
| 4
|
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def add(self, data):
new_node = Node(data)
node = self.head
# Get to the last node
previous = None
while node is not None:
node = node.next
if node is None:
previous.next = new_node
previous = node
def print_list(self):
node = self.head
while node:
print(f"{node.data} ->", end=" ")
node = node.next
print("None")
ll = LinkedList()
first_node = Node("A")
second_node = Node("B")
third_node = Node("C")
first_node.next = second_node
second_node.next = third_node
ll.head = first_node
ll.print_list()
ll.add("D")
ll.add("E")
ll.print_list()
| true
|
1b68f58a36594c14385ff3e3faf8569659ba0532
|
derekcollins84/myProjectEulerSolutions
|
/problem0001/problem1.py
| 521
| 4.34375
| 4
|
'''
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
'''
returnedValues = []
sumOfReturnedValues = 0
for testNum in range(1, 1000):
if testNum % 3 == 0 or \
testNum % 5 == 0:
returnedValues.append(testNum)
for i in range(len(returnedValues)):
sumOfReturnedValues = \
sumOfReturnedValues \
+ returnedValues[i]
print(sumOfReturnedValues)
| true
|
59609427d2e62f29bb7388f7bd320cb2cf927da3
|
Sohom-chatterjee2002/Python-for-Begineers
|
/Assignment-1-Python Basics/Problem 3.py
| 423
| 4.15625
| 4
|
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 2 14:23:03 2020
@author: Sohom Chatterjee_CSE1_T25
"""
def append_middle(s1,s2):
middleIndex=int(len(s1)/2)
print("Original strings are: ",s1,s2)
middleThree=s1[:middleIndex]+s2+s1[middleIndex:]
print("After appending new string in middle: ",middleThree)
s1=input("Enter your first string: ")
s2=input("Enter your seccond string: ")
append_middle(s1,s2)
| false
|
8b29ca12d190975f7b957645e9a18b4291e662a1
|
Sohom-chatterjee2002/Python-for-Begineers
|
/Assignment 2 -Control statements in Python/Problem 6.py
| 556
| 4.15625
| 4
|
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 23 14:25:28 2020
@author: Sohom Chatterjee_CSE1_T25
"""
#The set of input is given as ages. then print the status according to rules.
def age_status(age):
if(age<=1):
print("in_born")
elif(age>=2 and age<=10):
print("child")
elif(age>=11 and age<=17):
print("young")
elif(age>=18 and age<=49):
print("adult")
elif(age>=50 and age<=79):
print("old")
else:
print("very_old")
age=int(input("Enter your age: "))
age_status(age)
| true
|
fccacd3a4799ab9b23a34b5c60f007afd54f7f73
|
tejaswisunitha/python
|
/power.py
| 348
| 4.28125
| 4
|
def power(a,b):
if a==0: return 0
elif b==0: return 1
elif b==1: return a
elif b%2 == 0:
res_even = power(a,b/2)
return res_even*res_even
else :
b=(b-1)/2
res_odd= power(a,b)
return a*res_odd*res_odd
pow = power(2,3)
print(pow)
| false
|
413524181632130eb94ef936ff18caecd4d47b06
|
nikhilroxtomar/Fully-Connected-Neural-Network-in-NumPy
|
/dnn/activation/sigmoid.py
| 341
| 4.1875
| 4
|
## Sigmoid activation function
import numpy as np
class Sigmoid:
def __init__(self):
"""
## This function is used to calculate the sigmoid and the derivative
of a sigmoid
"""
def forward(self, x):
return 1.0 / (1.0 + np.exp(-x))
def backward(self, x):
return x * (1.0 - x)
| true
|
8e96a6fcac5695f7f0d47e1cf3f6ecef9382cbbf
|
janvanboesschoten/Python3
|
/h3_hours_try.py
| 275
| 4.125
| 4
|
hours = input('Enter the hour\n')
try:
hours = float(hours)
except:
hours = input('Error please enter numeric input\n')
rate = input('Enter your rate per hour?\n')
try:
rate = float(rate)
except:
rate = input('Error please enter numeric input\n')
| true
|
ed98b46454cb7865aadfe06077dff076dfd71a73
|
mujtaba4631/Python
|
/FibonacciSeries.py
| 308
| 4.5625
| 5
|
#Fibonacci Sequence -
#Enter a number and have the program generate the Fibonacci sequence to that number or to the Nth number.
n = int(input("enter the number till which you wanna generate Fibonacci series "))
a = 0
b = 1
c = a+1
print(a)
print(b)
for i in range(0,n):
c = a+ b
print(c)
a,b=b,c
| true
|
4c99cd87da23da776fff6f9f56348488be10e8d5
|
zzb15997937197/django-study
|
/mysite/polls/python_study/dict_demo.py
| 1,917
| 4.28125
| 4
|
dict_data = {"age": 23, "name": "张正兵"}
# 1. items()方法,返回字典的所有键值对,以列表的形式返回可遍历的元组数组
items = dict_data.items()
for i in items:
print(i)
# 2. key in dict 判断键是否在字典里
if "age" in dict_data:
print("age is in dict")
else:
print("age is not in dict")
# 3. 可以直接根据键来拿到对应的值
print(dict_data["age"])
# 4. keys()方法,返回该字典的键列表,包含该字典内的所有键
print("获取所有的key", dict_data.keys(), "类型:", type(dict_data.keys()))
# 5. get(key,default=None)返回指定的key,如果key不存在,那么返回default值。
print(dict_data.get("address", "不存在!"))
# 6. setdefault(key,default=None)设置key的默认值,如果key不存在,那么设置的值为default的值
print(dict_data.setdefault("address", "上海浦东新区"))
print(dict_data)
# 7.values()方法, values方法,返回一个迭代器,可以用list转换为值列表
print(dict_data.values())
# --> 列表
print(list(dict_data.values()))
# 8. pop(key[,default])方法, 返回被删除的key值,如果指定的key值不存在,那么返回设定的default的值。
pop_result = dict_data.pop("add", "666")
print("pop_result", pop_result, ",dict_data", dict_data)
# 9. popitem()方法,随机返回字典的最后一个键值对。
pop_item = dict_data.popitem()
print("pop_item", pop_item, ",dict_data", dict_data)
# 10. .fromkeys()方法,根据元组序列来生成一个字典
tuple_data = ("name", "age", "address")
print("根据元组生成字典:", dict.fromkeys(tuple_data))
print("当前局部变量", locals())
print("当前全局变量", globals())
dict_data = {"1": 1, "2": 2}
print(dict_data)
print(dict_data.get("1"))
# 取出字典的第二个元素
print("2" in dict_data)
print(tuple(dict_data))
# 元组和字典可以相互转换,转换的是字典的keys
| false
|
2ddc4abc64069852fdd535b49a26f5712463f14a
|
nathanandersen/SortingAlgorithms
|
/MergeSort.py
| 1,122
| 4.25
| 4
|
# A Merge-Sort implementation in Python
# (c) 2016 Nathan Andersen
import Testing
def mergeSort(xs,key=None):
"""Sorts a list, xs, in O(n*log n) time."""
if key is None:
key = lambda x:x
if len(xs) < 2:
return xs
else:
# sort the l and r halves
mid = len(xs) // 2
l = mergeSort(xs[:mid],key)
r = mergeSort(xs[mid:],key)
# merge them r together
return merge(l,r,key)
def merge(l,r,key):
"""A merge routine to complete the mergesort."""
result = []
l_ptr = 0
r_ptr = 0
while (l_ptr < len(l) or r_ptr < len(r)):
if l_ptr == len(l):
# if we have added everything from the l
result.extend(r[r_ptr:])
return result
elif r_ptr == len(r):
# we have added everything from the r
result.extend(l[l_ptr:])
return result
elif key(l[l_ptr]) < key(r[r_ptr]):
result.append(l[l_ptr])
l_ptr += 1
else:
result.append(r[r_ptr])
r_ptr += 1
if __name__ == "__main__":
Testing.test(mergeSort)
| true
|
614d2f3dfc383cf24fd979bb2918bef80fda3450
|
fancycheung/LeetCodeTrying
|
/easy_code/Linked_List/876.middleofthelinkedlist.py
| 1,180
| 4.15625
| 4
|
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
@author:nali
@file: 876.middleofthelinkedlist.py
@time: 2018/9/3/上午9:41
@software: PyCharm
"""
"""
Given a non-empty, singly linked list with head node head, return a middle node of linked list.
If there are two middle nodes, return the second middle node.
Example 1:
Input: [1,2,3,4,5]
Output: Node 3 from this list (Serialization: [3,4,5])
The returned node has value 3. (The judge's serialization of this node is [3,4,5]).
Note that we returned a ListNode object ans, such that:
ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, and ans.next.next.next = NULL.
Example 2:
Input: [1,2,3,4,5,6]
Output: Node 4 from this list (Serialization: [4,5,6])
Since the list has two middle nodes with values 3 and 4, we return the second one.
Note:
The number of nodes in the given list will be between 1 and 100.
"""
import sys
reload(sys)
sys.setdefaultencoding("utf8")
def middleNode(head):
"""
:type head: ListNode
:rtype: ListNode
"""
one, two = head, head
while two and two.next:
one = one.next
two = two.next.next
return one
if __name__ == "__main__":
pass
| true
|
4e2ef817bd967563c72eadc6728f80a74cd661b7
|
sakuma17/PythonTraining
|
/0201/dictLesson.py
| 584
| 4.1875
| 4
|
dict1=dict() #空のdict
dict1['apple']='りんご'
dict1['orange']='みかん'
print(dict1)
print(len(dict1))
dict1['banana']='ばなな'
del dict1['orange']
print(dict1)
print(dict1['apple']) # 指定したキーのバリューを取得
#print(dict1['pine']) #無いのでerror
print(dict1.get('pine')) #Noneを返す
print(dict1.get('banana')) #ばなな
if 'apple' in dict1:
print('key:appleは含まれている')
if 'pine' not in dict1:
print('key:pineは含まれていない')
if 'りんご' in dict1.values():
print('value:りんごは含まれている')
| false
|
4afad10bff966b08e4f0aab782049901a3fb66dc
|
BalintNagy/GitForPython
|
/Checkio/01_Elementary/checkio_elementary_11_Even_the_last.py
| 1,261
| 4.21875
| 4
|
"""\
Even the last
You are given an array of integers. You should find the sum of the elements
with even indexes (0th, 2nd, 4th...) then multiply this summed number and
the final element of the array together. Don't forget that the first element
has an index of 0.
For an empty array, the result will always be 0 (zero).
Input: A list of integers.
Output: The number as an integer.
Example:
checkio([0, 1, 2, 3, 4, 5]) == 30
checkio([1, 3, 5]) == 30
checkio([6]) == 36
checkio([]) == 0
How it is used: Indexes and slices are important elements of coding. This
will come in handy down the road!
Precondition:
0 ≤ len(array) ≤ 20
all(isinstance(x, int) for x in array)
all(-100 < x < 100 for x in array)
"""
def checkio(array):
"""
sums even-indexes elements and multiply at the last
"""
index = 0
sumofevens = 0
try:
for i in array:
if index%2 == 0:
sumofevens += i
index += 1
return sumofevens * array[len(array)-1]
except IndexError:
return 0
print(checkio([0, 1, 2, 3, 4, 5]))
print(checkio([1, 3, 5]))
print(checkio([6]))
print(checkio([]))
| true
|
92067b660f1df00f7d622b49388994c892145033
|
BalintNagy/GitForPython
|
/OOP_basics_1/01_Circle.py
| 572
| 4.125
| 4
|
# Green Fox OOP Basics 1 - 1. feladat
# Create a `Circle` class that takes it's radius as cinstructor parameter
# It should have a `get_circumference` method that returns it's circumference
# It should have a `get_area` method that returns it's area
import math
class Circle:
def __init__(self, radius):
self.radius = radius
def get_circumference(self):
return 2 * self.radius * math.pi
def get_area(self):
return pow(self.radius, 2) * math.pi
karika = Circle(5)
print(karika.get_circumference())
print(karika.get_area())
| true
|
7852ff2dfef25e356a65c527e94ee88d10c74a0b
|
BalintNagy/GitForPython
|
/Checkio/01_Elementary/checkio_elementary_16_Digits_multiplication.py
| 929
| 4.40625
| 4
|
"""\
Digits Multiplication
You are given a positive integer. Your function should calculate the product
of the digits excluding any zeroes.
For example: The number given is 123405. The result will be 1*2*3*4*5=120
(don't forget to exclude zeroes).
Input: A positive integer.
Output: The product of the digits as an integer.
Example:
checkio(123405) == 120
checkio(999) == 729
checkio(1000) == 1
checkio(1111) == 1
How it is used: This task can teach you how to solve a problem with simple
data type conversion.
Precondition:
0 < number < 10^6
"""
def checkio(number: int) -> int:
numberlist = list(str(number))
product = 1
for i in numberlist:
if int(i) != 0:
product = product * int(i)
return product
print(checkio(123405))
print(checkio(999))
print(checkio(1000))
print(checkio(1111))
# szép, könnyen olvasható
| true
|
d5353aa98262d9de8b540c9ae863bde41ab0cda9
|
mura-wx/mura-wx
|
/python/Practice Program/basic program/chekPositifAndNegatif.py
| 306
| 4.15625
| 4
|
try :
number=int(input("Enter Number : "))
if number < 0:
print("The entered number is negatif")
elif number > 0:
print("The entered number is positif")
if number == 0:
print("number is Zero")
except ValueError :
print('The input is not a number !')
| true
|
b45e6f6b1e8bb428e0e3fd5b6985687e64812a1c
|
Alihussain-khan/HangMan-Game-Python
|
/hangman game.py
| 2,638
| 4.1875
| 4
|
import random
def get_word():
words= [ 'Woodstock',
'Gray',
'Hello',
'Gopher',
'Spikepike',
'green',
'blue',
'Willy',
'Rex',
'yes',
'Roo',
'Littlefoot',
'Baagheera',
'Remy',
'good',
'Kaa',
'Rudolph',
'Banzai',
'Courage',
'Nemo',
'Nala',
'other',
'Sebastin',
'lago',
'head',
'car',
'Dory',
'Pumbaa',
'Garfield',
'Manny',
'bubble',
'ball',
'Flik',
'Marty',
'Gloria',
'Donkey',
'Timon',
'Baloo',
'Thumper',
'Bambi',
'Goofy',
'Tom',
'Sylvester',
'Jerry',
'Tiger']
return random.choice(words).upper()
def Check(word,guesses,guess):
guess=guess.upper()
status=''
i=0
matches = 0
for letter in word:
if letter in guesses:
status += letter
else:
status += '*'
if letter == guess:
matches += 1
if matches > 1:
print ('yes! The word contains', matches, '"'+guess + '"' + 's')
elif matches == 1:
print ('Yes! The word containes the letter"'+ guess + '"')
else:
print('Sorry. the word does not cpontain the letter " '+ guess + '"')
return status
def main():
word = get_word()
guesses=[]
guessed = False
print ('The word contains',len(word) ,'letters.')
while not guessed:
text= 'please enter one letter or whole word '
guess = input(text)
guess = guess.upper()
if(len(guesses)>=8):
print("GAME OVER")
break;
if guess in guesses:
print ('you already guessed"' + guess + '"')
elif len(guess) == len(word):
guesses.append(guess)
if guess == word:
guessed = True
else:
print('Sorry, thst is incorrect')
elif len(guess) == 1:
guesses.append(guess)
result = Check(word,guesses,guess)
if result == word:
guessed = True
else:
print (result)
else:
print('invalid entry')
print ('The word is', word + '! you took ',len(guesses),'tries.')
main()
| false
|
76b5171706f347c58c33eed212798f84c6ebcfd1
|
zuxinlin/leetcode
|
/leetcode/350.IntersectionOfTwoArraysII.py
| 1,434
| 4.1875
| 4
|
#! /usr/bin/env python
# coding: utf-8
'''
'''
class Solution(object):
'''
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].
Note:
Each element in the result should appear as many times as it shows in both arrays.
The result can be in any order.
Follow up:
What if the given array is already sorted? How would you optimize your algorithm?
What if nums1's size is small compared to nums2's size? Which algorithm is better?
What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
'''
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
result = []
cache = {}
# 先用哈希表存储一个数组统计情况,另外一个数组查表即可
for i in nums1:
if i in cache:
cache[i] += 1
else:
cache[i] = 1
for i in nums2:
if i in cache and cache[i] > 0:
result.append(i)
cache[i] -= 1
return result
if __name__ == '__main__':
solution = Solution()
assert solution.intersect([1, 2, 2, 1], [2]) == [2, ]
assert solution.intersect([3, 1, 2], [1, 1]) == [1, ]
| true
|
37e1234e8f39adc280dc20a3c39ea86f93143b0e
|
zuxinlin/leetcode
|
/leetcode/110.BalancedBinaryTree.py
| 1,342
| 4.28125
| 4
|
#! /usr/bin/env python
# coding: utf-8
'''
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example 1:
Given the following tree [3,9,20,null,null,15,7]:
3
/ \
9 20
/ \
15 7
Return true.
Example 2:
Given the following tree [1,2,2,3,3,null,null,4,4]:
1
/ \
2 2
/ \
3 3
/ \
4 4
Return false.
判断一颗二叉树是否是平衡二叉树,主要是左右子树高度差有没有大于1
'''
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def dfs(self, root):
if root is None:
return 0
left = self.dfs(root.left)
right = self.dfs(root.right)
if left == -1 or right == -1 or abs(left - right) > 1:
return -1
else:
return max(left, right) + 1
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if self.dfs(root) == -1:
return False
else:
return True
if __name__ == '__main__':
pass
| true
|
7a750725399d333e2cd1b46add1b8cc0c02b1522
|
MadyDixit/ProblemSolver
|
/Google/Coding/UnivalTree.py
| 1,039
| 4.125
| 4
|
'''
Task 1: Check weather the Given Tree is Unival or Not.
Task 2: Count the Number of Unival Tree in the Tree.
'''
'''
Task 1:
'''
class Tree:
def __init__(self,x):
self.val = x
self.left = None
self.right = None
def insert(self, data):
if self.val:
if self.val > data:
if self.left is None:
self.left = Tree(data)
else:
self.left.insert(data)
else:
if self.right is None:
self.right = Tree(data)
else:
self.right.insert(data)
else:
return False
class Tasker:
def is_unival(self,root):
return unival_helper(root, root.val)
def unival_helper(self, root, value):
if root is None:
return True
elif root.val == value:
return self.unival_helper(root.left, value) and self.unival_helper(root.right, value)
return False
if __name__ == '__main__':
| true
|
02d2c723586f0b98c48dde041b20e5ec86809fae
|
pkray91/laravel
|
/string/string.py
| 1,254
| 4.4375
| 4
|
print("Hello python");
print('Hello python');
x = '''hdbvfvhbfvhbf'''
y = """mdnfbvnfbvdfnbvfvbfm"""
print(y)
print(x)
a='whO ARE you Man';
print(a);
print(a.upper());
print(a.lower());
print(len(a));
print(a[1]);
#sub string not including the given position.
print(a[4:8]);
#The strip() method removes any whitespace from the beginning or the end:
b=" hello ";
print(b);
print(b.strip());
print(b.replace('h','l'));
#The split() method splits the string into substrings if it finds instances of the separator:
print(a.split(' '));
print(a.split('a'));
#As we learned in the Python Variables chapter, we cannot combine strings and numbers like this:
#The format() method takes unlimited number of arguments, and are placed into the respective placeholders:
age=36;
c='I am going home {}';
print(c.format(age));
quant=20;
age=28;
mobile=898767898;
txt='total men was {} and their age was {} and have only one mobile no is {}';
print(txt.format(quant,age,mobile));
age=36;
c='I am going home {}';
print(c.format(age));
quant=20;
age=28;
mobile=898767898;
txt='total men was {2} and their age was {0} and have only one mobile no is {1}';
print(txt.format(quant,age,mobile));
#reverse the string.
rev= 'hello python'[::-1];
print(rev);
| true
|
0ee9e3d684e4a810701066ada2cc0daf04347abf
|
WebClub-NITK/Hacktoberfest-2k20
|
/Algorithms/14_disjoint_set/disjoint-set.py
| 989
| 4.1875
| 4
|
# Python3 program to implement Disjoint Set Data Structure for union and find.
class DisjSet:
def __init__(self, n):
self.rank = [1] * n
self.parent = [i for i in range(n)]
# Finds set of given item x
def find(self, x):
if self.parent[x] != x:
self.parent[x] = self.find(self.parent[x])
return self.parent[x]
def Union(self, x, y):
xset = self.find(x)
yset = self.find(y)
if xset == yset:
return
if self.rank[xset] < self.rank[yset]:
self.parent[xset] = yset
elif self.rank[xset] > self.rank[yset]:
self.parent[yset] = xset
else:
self.parent[yset] = xset
self.rank[xset] = self.rank[xset] + 1
# Driver code
obj = DisjSet(5)
obj.Union(0, 2)
obj.Union(4, 2)
obj.Union(3, 1)
if obj.find(4) == obj.find(0):
print('Yes')
else:
print('No')
if obj.find(1) == obj.find(0):
print('Yes')
else:
print('No')
| false
|
996520dcd43c24c0391fc8767ee4eb9f8f3d309e
|
AdityaChavan02/Python-Data-Structures-Coursera
|
/8.6(User_input_no)/8.6.py
| 481
| 4.3125
| 4
|
#Rewrite the program that prompts the user for a list of numbers and prints the max and min of the numbers at the end when the user presses done.
#Write the program to store the numbers in a list and use Max Min functions to compute the value.
List=list()
while True:
no=input("Enter the no that you so desire:\n")
if no=='done':
break
List.append(no)
print(List)
print("The MAX value is %d",max(List))
print("The MIN value is %d",min(List))
| true
|
0ac525f075a96f8a749ddea35f8e1a59775217c8
|
ZoranPandovski/al-go-rithms
|
/sort/selection_sort/python/selection_sort.py
| 873
| 4.125
| 4
|
#defines functions to swap two list elements
def swap(A,i,j):
temp = A[i]
A[i] = A[j]
A[j] = temp
#defines functions to print list
def printList(A,n):
for i in range(0,n):
print(A[i],"\t")
def selectionSort(A,n):
for start in range(0,n-1):
min=start #min is the index of the smallest element in the list during the iteration
#Scan from A[min+1] to A[n-1] to find a list element that is smaller than A[min]
for cur in range(min+1,n):
#if A[cur] is smaller than A[min] min is updated
if A[cur]<A[min]:
min = cur
#the two elements are swapped
swap(A,start,min)
def test():
A = [38,58,13, 15,21,27,10,19,12,86,49,67,84,60,25]
n = len(A)
print("Selection Sort: ")
selectionSort(A,n)
print("Sorted List: ")
printList(A,n)
test()
| true
|
6b2ae13e2f7dfa26c15cef55978cf7e70f4bf711
|
ZoranPandovski/al-go-rithms
|
/dp/min_cost_path/python/min_cost_path_.py
| 809
| 4.21875
| 4
|
# A Naive recursive implementation of MCP(Minimum Cost Path) problem
R = 3
C = 3
import sys
# Returns cost of minimum cost path from (0,0) to (m, n) in mat[R][C]
def minCost(cost, m, n):
if (n < 0 or m < 0):
return sys.maxsize
elif (m == 0 and n == 0):
return cost[m][n]
else:
return cost[m][n] + min( minCost(cost, m-1, n-1),
minCost(cost, m-1, n),
minCost(cost, m, n-1) )
#A utility function that returns minimum of 3 integers */
def min(x, y, z):
if (x < y):
return x if (x < z) else z
else:
return y if (y < z) else z
# Driver program to test above functions
cost= [ [1, 2, 3],
[4, 8, 2],
[1, 5, 3] ]
print(minCost(cost, 2, 2))
| true
|
1f2547aa08428209cf4d106ad8361033dd411efc
|
ZoranPandovski/al-go-rithms
|
/strings/palindrome/python/palindrome2.py
| 369
| 4.53125
| 5
|
#We check if a string is palindrome or not using slicing
#Accept a string input
inputString = input("Enter any string:")
#Caseless Comparison
inputString = inputString.casefold()
#check if the string is equal to its reverse
if inputString == inputString[::-1]:
print("Congrats! You typed in a PALINDROME!!")
else:
print("This is not a palindrome. Try Again.")
| true
|
fc9287fca6c7b390cbd47ae7f70806b10d6114c3
|
ZoranPandovski/al-go-rithms
|
/data_structures/b_tree/Python/check_bst.py
| 1,131
| 4.28125
| 4
|
"""
Check whether the given binary tree is BST(Binary Search Tree) or not
"""
import binary_search_tree
def check_bst(root):
if(root.left != None):
temp = root.left
if temp.val <= root.val:
left = check_bst(root.left)
else:
return False
else:
left = True
if(root.right != None):
temp = root.right
if temp.val > root.val:
right = check_bst(root.right)
else:
return False
else:
right = True
if (left and right):
return True
else:
return False
# ### Testcases ###
#
# root = None
# tree = binary_search_tree.Tree()
#
# # This tree should return Tree
# root = tree.insert(root, 6)
# root = tree.insert(root,3)
# root = tree.insert(root,1)
# root = tree.insert(root,4)
# root = tree.insert(root,8)
# root = tree.insert(root,7)
# root = tree.insert(root,9)
# tree.preorder(root)
# print check_bst(root)
#
# # This tree should return False
# root = tree.not_bst()
# print check_bst(root)
| true
|
bf23783e9c07a11cdf0a186ab28da4edc1675b54
|
ZoranPandovski/al-go-rithms
|
/sort/Radix Sort/Radix_Sort.py
| 1,369
| 4.1875
| 4
|
# Python program for implementation of Radix Sort
# A function to do counting sort of arr[] according to
# the digit represented by exp.
def countingSort(arr, exp1):
n = len(arr)
# The output array elements that will have sorted arr
output = [0] * (n)
# initialize count array as 0
count = [0] * (10)
# Store count of occurrences in count[]
for i in range(0, n):
index = arr[i] // exp1
count[index % 10] += 1
# Change count[i] so that count[i] now contains actual
# position of this digit in output array
for i in range(1, 10):
count[i] += count[i - 1]
# Build the output array
i = n - 1
while i >= 0:
index = arr[i] // exp1
output[count[index % 10] - 1] = arr[i]
count[index % 10] -= 1
i -= 1
# Copying the output array to arr[],
# so that arr now contains sorted numbers
i = 0
for i in range(0, len(arr)):
arr[i] = output[i]
# Method to do Radix Sort
def radixSort(arr):
# Find the maximum number to know number of digits
max1 = max(arr)
# Do counting sort for every digit. Note that instead
# of passing digit number, exp is passed. exp is 10^i
# where i is current digit number
exp = 1
while max1 / exp > 0:
countingSort(arr, exp)
exp *= 10
# Driver code
arr = [170, 45, 75, 90, 802, 24, 2, 66]
# Function Call
radixSort(arr)
for i in range(len(arr)):
print(arr[i])
# This code is contributed by Manas Misra
| true
|
45d1f94946fb66eb792a8dbc8cbdb84c216d381c
|
ZoranPandovski/al-go-rithms
|
/math/leapyear_python.py
| 491
| 4.25
| 4
|
'''Leap year or not'''
def leapyear(year):
if (year % 4 == 0) and (year % 100 != 0) or (year % 400==0) : #checking for leap year
print(year," is a leap year") #input is a leap year
else:
print(year," is not a leap year") #input is not a leap year
year=int(input("Enter the year: "))
while year<=999 or year>=10000: #check whether the year is four digit number or not
print("Enter a year having four digits.")
year=int(input("Enter the year: "))
leapyear(year)
| true
|
533b8c91219f7c4a2e51f952f88581edb8446fd5
|
ZoranPandovski/al-go-rithms
|
/sort/python/merge_sort.py
| 1,809
| 4.25
| 4
|
"""
This is a pure python implementation of the merge sort algorithm
For doctests run following command:
python -m doctest -v merge_sort.py
or
python3 -m doctest -v merge_sort.py
For manual testing run:
python merge_sort.py
"""
from __future__ import print_function
def merge_sort(collection):
"""Pure implementation of the merge sort algorithm in Python
:param collection: some mutable ordered collection with heterogeneous
comparable items inside
:return: the same collection ordered by ascending
Examples:
>>> merge_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3, 5]
>>> merge_sort([])
[]
>>> merge_sort([-2, -5, -45])
[-45, -5, -2]
"""
length = len(collection)
if length > 1:
midpoint = length // 2
left_half = merge_sort(collection[:midpoint])
right_half = merge_sort(collection[midpoint:])
i = 0
j = 0
k = 0
left_length = len(left_half)
right_length = len(right_half)
while i < left_length and j < right_length:
if left_half[i] < right_half[j]:
collection[k] = left_half[i]
i += 1
else:
collection[k] = right_half[j]
j += 1
k += 1
while i < left_length:
collection[k] = left_half[i]
i += 1
k += 1
while j < right_length:
collection[k] = right_half[j]
j += 1
k += 1
return collection
if __name__ == '__main__':
try:
raw_input # Python 2
except NameError:
raw_input = input # Python 3
user_input = input('Enter numbers separated by a comma:\n').strip()
unsorted = [int(item) for item in user_input.split(',')]
print(merge_sort(unsorted))
| true
|
0fbd0364c4afb58c921db8d3a036916e69b5a2b1
|
ZoranPandovski/al-go-rithms
|
/sort/bubble_sort/python/capt-doki_bubble_sort.py
| 652
| 4.3125
| 4
|
# Python program for implementation of Bubble Sort
# TIME COMPLEXITY -- O(N^2)
# SPACE COMPLEXITY -- O(1)
def bubbleSort(arr):
n = len(arr)
# Traverse through all array elements
for i in range(n):
# Last i elements are already in place
for j in range(0, n-i-1):
# traverse the array from 0 to n-i-1
# Swap if the element found is greater
# than the next element
if arr[j] > arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]
arr = [64, 34, 25, 12, 22, 11, 90]
bubbleSort(arr)
print ("Sorted array is:")
for i in range(len(arr)):
print (arr[i])
| true
|
0b275806d4228c967856b0ff6995201b7af57e5e
|
ZoranPandovski/al-go-rithms
|
/data_structures/Graphs/graph/Python/closeness_centrality.py
| 1,585
| 4.28125
| 4
|
"""
Problem :
Calculate the closeness centrality of the nodes of the given network
In general, centrality identifies the most important vertices of the graph.
There are various measures for centrality of a node in the network
For more details : https://en.wikipedia.org/wiki/Closeness_centrality
Formula :
let C(x) be the closeness centrality of the node x.
C(x) = (N-1) / (sum of shortest paths between x & all nodes in the graph)
"""
def bfs(x: int) -> int:
"""
Does BFS traversal from node x
Returns the sum of all shortest distances
"""
sum_d = 0
# store the shortest distance from x
d = [-1 for _ in range(len(adj))]
# queue
queue = []
queue.append(x)
d[x] = 0
while len(queue) != 0:
front = queue[0]
queue.pop(0)
for v in adj[front]:
if d[v] == -1:
queue.append(v)
d[v] = d[front] + 1
sum_d += d[v]
return sum_d
def closeness_centrality():
"""
calculates the closeness centrality
Returns:
A list containing the closeness centrality of all nodes
"""
n = len(adj)
closeness_centrality = []
for i in range(len(adj)):
closeness_centrality.append((n - 1) / bfs(i))
return closeness_centrality
if __name__ == "__main__":
global adj
adj = [[] for _ in range(5)]
adj[0] = [1, 3]
adj[1] = [0, 2, 4]
adj[2] = [1]
adj[3] = [0, 4]
adj[4] = [1, 3]
closeness_centrality = closeness_centrality()
print("Closeness centrality : {}".format(closeness_centrality))
| true
|
9b8696686283cf9e7afea3bf7b1ac976c3233a54
|
ZoranPandovski/al-go-rithms
|
/dp/EditDistance/Python/EditDistance.py
| 1,017
| 4.15625
| 4
|
from __future__ import print_function
def editDistance(str1, str2, m , n):
# If first string is empty, the only option is to
# insert all characters of second string into first
if m==0:
return n
# If second string is empty, the only option is to
# remove all characters of first string
if n==0:
return m
# If last characters of two strings are same, nothing
# much to do. Ignore last characters and get count for
# remaining strings.
if str1[m-1]==str2[n-1]:
return editDistance(str1,str2,m-1,n-1)
# If last characters are not same, consider all three
# operations on last character of first string, recursively
# compute minimum cost for all three operations and take
# minimum of three values.
return 1 + min(editDistance(str1, str2, m, n-1), # Insert
editDistance(str1, str2, m-1, n), # Remove
editDistance(str1, str2, m-1, n-1) # Replace
)
# Driver program to test the above function
str1 = "sunday"
str2 = "saturday"
print(editDistance(str1, str2, len(str1), len(str2)))
| true
|
81807e5f75856d4c7d6e44065c9d13e6d750a75d
|
marciogomesfilho/Codes
|
/ex72.py
| 1,079
| 4.28125
| 4
|
#Exercício Python 072: Crie um programa que tenha uma tupla totalmente preenchida com uma contagem por extenso, de zero até vinte.
# Seu programa deverá ler um número pelo teclado (entre 0 e 5) e mostrá-lo por extenso.
contagem = ('Zero', 'Um', 'Dois', 'Três', 'Quarto', 'Cinco')
numero = int(input('Digite um número entre 0 e 5: '))
while numero not in range (0,6):
numero = int(input('Tente novamente: '))
else:
print(contagem[numero])
#lanche = ('Hamb', 'suco', 'pizza', 'pudim')
#for comida in lanche:
# print (f'eu vou comer {comida}')
#for cont in range (0,len(lanche)):
#print (f'Comi {lanche[cont]}')
#for pos, comida in enumerate (lanche):
#print (f'eu vou comer {comida} na posicao {pos}')
#print (sorted(lanche))
"""a = (2,5,4)
b = (5,8,1,2)
c = a + b
print (len(c))
print (c.count(5))
print(c.index(5,1))# o 1 depois, fala pra ele começar a procurar a partir do indx 1 desconsiderando o 0
pessoa = ('gustavo', 39, 'M', 99.88)
print (pessoa)
del (pessoa)
print (pessoa)"""
| false
|
bec4691cc3960e641bfaae05bcd7afdce043ffa7
|
marciogomesfilho/Codes
|
/ex31.py
| 420
| 4.25
| 4
|
#Exercício Python 031: Desenvolva um programa que pergunte a distância de uma viagem em Km.
# Calcule o preço da passagem, cobrando R$0,50 por Km para viagens de até 200Km e R$0,45 parta viagens mais longas.
dist = float(input('digite quantos kms foi a viagem: '))
if dist <= 200:
print ('o valor da viagem foi: R${}'.format(dist*0.50))
else:
print ('o valor da viagem foi: R${}'.format(dist*0.45))
| false
|
fb4fc200462f10023d7f470ebd64aadb799c6519
|
marciogomesfilho/Codes
|
/ex79.py
| 627
| 4.25
| 4
|
#Exercício Python 079: Crie um programa onde o usuário possa digitar vários valores numéricos e
# cadastre-os em uma lista. Caso o número já exista lá dentro, ele não será adicionado.
# No final, serão exibidos todos os valores únicos digitados, em ordem crescente.
numeros = list()
while True:
n = int(input('Digite um numero: '))
if n not in numeros:
numeros.append(n)
print ('Número adicionado')
else:
opcao = str(input('Numero repetido! Deseja continuar? [S/N]'))
if opcao in 'Nn':
break
numeros.sort()
print (f'Lista de numeros: {numeros}')
| false
|
399c60589ea352d922f22c5392bb3a41594b6167
|
marciogomesfilho/Codes
|
/ex89.py
| 1,679
| 4.1875
| 4
|
"""
"""Exercício Python 089: Crie um programa que leia nome e duas notas de vários alunos e
guarde tudo em uma lista composta. No final, mostre um boletim contendo a média de cada um e
permita que o usuário possa mostrar as notas de cada aluno individualmente.
"""
"""
completa = list()
temp = list()
resposta = list()
media = 0
while True:
nome = str(input('Digite o nome do aluno: '))
nota1 = float(input('Digite a 1 nota: '))
nota2 = float(input('Digite a 2 nota: '))
media = (nota1+nota2)/2
temp.append([nome], [nota1, nota2], [media])
completa.append(temp[:])
temp.clear()
resposta.append(f'Nome:{nome}||Média:{media}')
continuar = str(input('Deseja continuar? (S/N): '))
if continuar in 'Nn':
break
print (resposta)
print(completa)
"""opcao = str(input('Deseja ver as notas de um aluno em especifico? [S/N]: '))
if opcao in 'Ss':
while True:
opcao2 = str(input('Digite o nome do aluno ou [N/n] para finalizar: ')).upper()
if opcao2 not in 'nN':
print (f' O aluno {nome} teve as notas {completa[0][1]} e {completa[0][2]}.')
opcao2 = str(input('Digite o nome do aluno ou [N/n] para finalizar: ')).upper()
else:
break
print ('FIM DO PROGRAMA')
input()
else:
print('FIM DO PROGRAMA')
input()"""""
# ""while True:
# opcao3 = str(input('Deseja ver de outro aluno? [S/N]: '))
# opcao3 = str(input('Digite o nome do aluno: ')).upper()
# print(f' O aluno {opcao3} teve as notas {completa[0][1]} e {completa[0][2]}.')
# if opcao3 in 'Nn':
# break"""""
""""""
| false
|
044b06fda913253faaa6ac13b30308aa18c7aa47
|
th3n0y0u/C2-Random-Number
|
/main.py
| 577
| 4.4375
| 4
|
import random
print("Coin Flip")
# 1 = heads, 2 = tails
coin = random.randint(1,2)
if(coin == 1):
print("Heads")
else:
print("Tails")
# Excecise: Create a code that mimics a dice roll using random numbers. The code of the print what number is "rolled", letting the user what it is.
dice = random.randint(1,6)
if(dice == 1):
print("You rolled a 1")
elif(dice == 2):
print("You rolled a 2")
elif(dice == 3):
print("You rolled a 3")
elif(dice == 4):
print("You rolled a 4")
elif(dice == 5):
print("You rolled a 5")
elif(dice == 6):
print("You rolled a 6")
| true
|
9ee168ff9d35d0968e709211340358f2b3a1b5ac
|
IleanaChamorro/CursoPython
|
/Modulo2/Operadores/operadores.py
| 456
| 4.15625
| 4
|
#Operadores
a = 3
b = 2
resultado = a + b
print(f'Resultado suma: {resultado}')
resta = a - b
print(f'Resultado es: {resta}')
multiplicacion = a * b
print(f'resultado multiplicacion: {multiplicacion}')
division = a / b
print(f'resultado division: {division}')
division = a // b
print(f'resultado division(int): {division}')
modulo = a % b
print(f'resultado division(modulo): {modulo}')
exponente = a ** b
print(f'resultado exponente: {exponente}')
| false
|
a54440ee6d73d158644143c3b43659a5fca377da
|
IleanaChamorro/CursoPython
|
/Modulo4/cicloFor.py
| 389
| 4.28125
| 4
|
#El bucle for se utiliza para recorrer los elementos de un objeto iterable (lista, tupla, conjunto, diccionario, …) y ejecutar un bloque de código. En cada paso de la iteración se tiene en cuenta a un único elemento del objeto iterable, sobre el cuál se pueden aplicar una serie de operaciones.
cadena = 'Hola'
for letra in cadena:
print(letra)
else:
print('Fin ciclo For')
| false
|
869a95eb86410b60b95c95c08ab58a93193b55e1
|
thevarungrovers/Area-of-circle
|
/Area Of Circle.py
| 209
| 4.25
| 4
|
r = input("Input the radius of the circle:") # input from user
r = float(r) # typecasting
a = 3.14159265 * (r**2) # calculating area
print(f'The area of circle with radius {r} is {a}') # return area
| true
|
efffd3b52497bf990f8a02ea00af6f8f360f0270
|
musatoktas/Numerical_Analysis
|
/Python/Non-Linear Equations Roots/step_decreasing.py
| 387
| 4.125
| 4
|
x = float(input("Enter X value:"))
h = float(input("Enter H value:"))
a = float(input("Enter a value:"))
eps = float(input("Enter Epsilon value:"))
def my_func(k):
import math
j = math.sin(k)
l = 2*pow(k,3)
m = l-j-5
return m
while (h>eps):
y = my_func(x)
z = my_func(x+h)
if (y*z>0):
x = x + h
else:
h = h / a
print('root is: %f'%x)
| false
|
2c969e27e178cb286b98b7e320b5bbdcaee3b8f7
|
ProximaDas/HW06
|
/HW06_ex09_04.py
| 1,579
| 4.53125
| 5
|
#!/usr/bin/env python
# HW06_ex09_04.py
# (1)
# Write a function named uses_only that takes a word and a string of letters,
# and that returns True if the word contains only letters in the list.
# - write uses_only
# (2)
# Can you make a sentence using only the letters acefhlo? Other than "Hoe
# alfalfa?"
# - write function to assist you
# - type favorite sentence(s) here:
# 1: reproachful coalfishes
# 2: coalfishes reproachfully
# 3: coalfishes reproachfulnesses
##############################################################################
# Imports
import itertools
# Body
def uses_only(word,letters):
flag = False
for letter in word.lower():
if letter in letters.lower():
flag = True
else:
flag = False
break
return flag
def make_sentence():
letters = "acefhlo"
flag = False
word_list = []
with open("words.txt","r") as handler:
words = handler.read().split()
for word in words:
for letter in letters:
if letter in word:
flag = True
else:
flag = False
break
if flag == True:
word_list.append(word)
print ' '.join(word_list)
# def combination():
# list_ = list('acefhlo')
# new = itertools.chain.from_iterable(itertools.combinations(list_,i) for i in range(len(list_)+1))
# # print list(new)
# while True:
# try:
# print ''.join(new.next())
# except:
# break
##############################################################################
def main():
print uses_only("banana","aBn")
make_sentence()
combination()
if __name__ == '__main__':
main()
| true
|
aa1403aeaa7c51aa6031bd5361a55cb8a796bc78
|
Marcoakira/Desafios_Python_do_Curso_Guanabara
|
/Mundo3/Desafio086b.py
| 423
| 4.125
| 4
|
# Desafio086b criar uma matriz 3*3 e preencher ela com dados.
alista = [[0,0,0],[0,0,0],[0,0,0]]
for l in range(0,3):
for c in range(0,3):
alista[l][c] = int(input(f'Insira o numero da posição {l},{c}'))
for c in range (0,3):
for d in range(0,3):
print(f'{alista[c][d]:^5}',end='')
print()
# print(f'{alista[0]:^5}\n{alista[1]}\n{alista[2]}') # essa é outra posssiblidade de fazer o print
| false
|
308a96b56534d587575e0be55f037bdcbeb5c06e
|
subbul/python_book
|
/lists.py
| 2,387
| 4.53125
| 5
|
simple_list = [1,2,3]
print "Simple List",simple_list
hetero_list = [1,"Helo",[100,200,300]]# can containheterogenous values
print "Original List",hetero_list
print "Type of object hetero_list",type(hetero_list) # type of object, shows its fundamental data type, for e.g., here it is LIST
print "Item at index 0 ",hetero_list[0] #first index
print "Item at index -1",hetero_list[-1] #negative index start from end so here the last elemtn in LIST
print "Length -->", len(hetero_list)
print "#############################################"
big_list = [1,2,3,4,5,6,7,8,9]
print " big List", big_list
print "lets slice from index [2:]",big_list[2:] # start, end index, includes start, ends before end-index
print " slice till [:4]", big_list[:4] # stops before index 4 , 0-1-2-3
new_list = big_list[:] #from beginning to end
print "New list is a copy of big list", new_list
print "##############################################"
big_list = [1,2,3,4,5,6,7,8,9]
big_list[2]="x"
print " Index 2 is modified to x-->"
print big_list
big_list[len(big_list):] = [11,12,13] # adding at the end appending
print "Appended list", big_list
print " Append vs Extend list"
list_a = [1,2,3]
list_b = ['a','b','c']
print "list a", list_a
print "list b", list_b
list_a.append(list_b)
print "Append b to a", list_a
list_a = [1,2,3]
list_a.extend(list_b)
print "Extend b to a", list_a
list_a = [1,2,3]
print "Original list", list_a
list_a.insert(1,"x")
print " x insert before index 1",list_a
list_a = [1,2,3]
list_a.reverse()
print "reverse list", list_a
print "1 in list_a", (1 in list_a)
print "10 in list_a", (10 in list_a)
print "###################################################"
def custom_sort(string1):
return len(string1)
list_a = ["I am","good","World","Very big statement"]
list_a.sort()
print "Sorted naturally alphabetical", list_a
list_a = ["I am","good","World","Very big statement"]
list_a.sort(key=custom_sort)
print "Sorted using custom key", list_a
list_a = [10] * 4
print "list with initialization using *", list_a
list_a = [1,11] * 4
print "list with initialization using *", list_a
list_a = [10,20,30,40,50,60]
print "List -->", list_a
print "Index of 40-->", list_a.index(40)
list_a = [20,2,442,3,2,67,3]
print "List -->", list_a
print "Count occurance of 3 in list ==",list_a.count(3)
| true
|
1bb058c929eb776f52deab7486bcb65c71148d58
|
yangxi5501630/pythonProject
|
/study/study/15_元组.py
| 1,470
| 4.1875
| 4
|
'''
tuple下元组本质就是一个有序集合
格式:元组名 = (元组元素1, 元组元素2, ……, 元组元素n)
特点:
1.与列表类似
2.用()
3.一旦初始化就不能修改,这个和字符串一样
'''
#创建空元组
tuple1 = ()
print(tuple1)
#创建带元素的元组
tuple2 = (1,2,"tarena", True)
print(tuple2)
#定义只有一个元素的元组,记得后面带分割符,
tuple3 = (1,)
print(tuple3)
print(type(tuple3))
#访问元组成员
tuple4 = (1,2,3,4)
index = 0
for member in tuple4:
print("tuple[%d] = %d" %(index, tuple4[index]))
index += 1
tuple4 = (1,2,3,4)
index = -4
for member in tuple4:
print("tuple[%d] = %d" %(index, tuple4[index]))
index += 1
#修改元组的成员
tuple5 = (1,2,3,4,[5,6,7])
#tuple5[2] = 250 #不可修改
tuple5[4][1] = 250 #修改成员列表,没毛病
print(tuple5)
#删除元组
del tuple5
#print(tuple5)
#元组合体
tuple6 = (1,2,3)
tuple7 = (4,5,6)
print(tuple6 + tuple7)
#元组的重复
print(tuple6 * 3)
#判断
print(2 in tuple6)
print(2 in tuple7)
#元组截取
tuple8 = (1,2,3,4,5,6,7,8)
print(tuple8[:3])
print(tuple8[3:])
print(tuple8[3:6])
#二维元组
tuple9 = ((1,2,3),(4,5,6))
print(tuple9[1][1])
#元组的方法
#len() 返回元组中元素的个数
tuple10 = (1,2,3,4,5)
print(len(tuple10))
#max() 返回元组中的最大值
#min()
print(max((5,6,7,8,9)))
print(min((5,6,7,8,9)))
#列表转元组
list = [1,2,3,4]
tuple11 = tuple(list)
print(tuple11)
| false
|
6a8aa8ce16427dab54ddc650747a5fcb306b86ba
|
twilliams9397/eng89_python_oop
|
/python_functions.py
| 897
| 4.375
| 4
|
# creating a function
# syntax def name_of_function(inputs) is used to declare a function
# def greeting():
# print("Welcome on board, enjoy your trip!")
# # pass can be used to skip without any errors
#
# greeting() # function must be called to give output
#
# def greeting():
# return "Welcome on board, enjoy your trip!"
#
# print(greeting())
# def greeting(name):
# return "Welcome on board " + name
#
# print(greeting("Tom"))
# def greeting(name):
# return "Welcome on board " + name + "!"
#
# print(greeting(input("What is your name? ").capitalize()))
# functions can have multiple arguments and data types
# def add(num1, num2):
# return num1 + num2
#
# print(add(2, 3))
def multiply(num1, num2):
return num1 * num2
print("this is the required outcome of two numbers") # this line will not execute as it is after return statement
print(multiply(3, 5))
| true
|
013b2ac2244f256970950dc1cc7cdcae25f5371d
|
stockholm44/python_study_2018
|
/wikidocs/06-2.py
| 737
| 4.15625
| 4
|
# 06-2 3의 배수와 5의 배수를 1-1000사이에 더해주는거. 아니다. 그냥 class로 n을 받자.
class Times:
def __init__(self, n):
self.n = n
def three_five_times(self):
sum = 0
# return sum = sum + i for i in range(1, self.n) if i % 3 ==0 or i % 5 == 0]
# how can i make functional sum of for loop.
for i in range(1, self.n):
if i % 3 == 0 or i % 5 == 0:
sum += i
return sum
a = Times(1000)
print(a.three_five_times())
#새로운답
"""
class Sum:
def __init__(self, n):
self.n = n
def Sum_Times(self):
return sum([x for x in range(1, self.n) if x % 3 ==0 or x % 5 == 0])
a = Sum(1000)
print(a.Sum_Times())
"""
| false
|
c5910f1116ccfb97578f5c4d0f3f65023e3be1ad
|
leocjj/0123
|
/Machine Learning/0_Copilot/test02.py
| 342
| 4.21875
| 4
|
def calculate_fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return calculate_fibonacci(n-1) + calculate_fibonacci(n-2)
def main():
n = int(input("Enter the number of terms: "))
for i in range(n):
print(calculate_fibonacci(i), end=" ")
if __name__ == "__main__":
main()
| false
|
2b32d798a175be4fbc682ca9b737c5d1231ff989
|
leocjj/0123
|
/Python/python_dsa-master/stack/postfix_eval.py
| 730
| 4.1875
| 4
|
#!/usr/bin/python3
"""
Evaluate a postfix string
"""
from stack import Stack
def postfix_eval(string):
# Evaluate a postfix string
operands = Stack()
tokens = string.split()
for token in tokens:
if token.isdigit():
operands.push(int(token))
else:
op2 = operands.pop()
op1 = operands.pop()
operands.push(do_math(token, op1, op2))
return operands.pop()
def do_math(op, op1, op2):
# Perform an operation
if op == '*':
return op1 * op2
elif op == '/':
return op1 / op2
elif op == '+':
return op1 + op2
else:
return op1 - op2
if __name__ == '__main__':
print(postfix_eval('7 8 + 3 2 + /'))
| false
|
27c6ec9e71d1d1cdd87ae03180937f2d798db4b2
|
leocjj/0123
|
/Python/python_dsa-master/recursion/int_to_string.py
| 393
| 4.125
| 4
|
#!/usr/bin/python3
"""
Convert an integer to a string
"""
def int_to_string(n, base):
# Convert an integer to a string
convert_string = '0123456789ABCDEF'
if n < base:
return convert_string[n]
else:
return int_to_string(n // base, base) + convert_string[n % base]
if __name__ == '__main__':
print(int_to_string(1453, 16))
print(int_to_string(10, 2))
| true
|
35eb4eddbc01e1c926e84c1a7d5f5467f4365746
|
leocjj/0123
|
/Python/python_dsa-master/recursion/palindrome.py
| 737
| 4.21875
| 4
|
#!/usr/bin/python3
"""
Check if a string is a palindrome
"""
def remove_white(s):
# Remove characters that are not letters
new = ''
for ch in s:
if ord(ch) >= ord('a') and ord(ch) <= ord('z'):
new += ch
return new
def palindrome(s):
# Check if a string is a palindrome
if len(s) <= 1:
return True
elif s[0] != s[len(s) - 1]:
return False
else:
return palindrome(s[1:-1])
if __name__ == '__main__':
print(palindrome(remove_white('lsdkjfskf')))
print(palindrome(remove_white('radar')))
print(palindrome(remove_white('a man, a plan, a canal, panama')))
print(palindrome(remove_white('')))
print(palindrome(remove_white("madam i'm adam")))
| false
|
e81c76e31dd827790d6b98e739763201cfc618ab
|
tlepage/Academic
|
/Python/longest_repetition.py
| 1,121
| 4.21875
| 4
|
__author__ = 'tomlepage'
# Define a procedure, longest_repetition, that takes as input a
# list, and returns the element in the list that has the most
# consecutive repetitions. If there are multiple elements that
# have the same number of longest repetitions, the result should
# be the one that appears first. If the input list is empty,
# it should return None.
def longest_repetition(i):
count = 0
largest_count = 0
curr = None
largest = None
for e in i:
if curr == None:
curr = e
largest = e
count = 1
else:
if e == curr:
count += 1
if count > largest_count:
largest_count = count
largest = curr
else:
curr = e
count = 1
return largest
#For example,
print longest_repetition([1, 2, 2, 3, 3, 3, 2, 2, 1])
# 3
print longest_repetition(['a', 'b', 'b', 'b', 'c', 'd', 'd', 'd'])
# b
print longest_repetition([1,2,3,4,5])
# 1
print longest_repetition([])
# None
print longest_repetition([2, 2, 3, 3, 3])
| true
|
9682bdce76206453617d5b26c2c219becb5d4001
|
yougov/tortilla
|
/tortilla/formatters.py
| 444
| 4.125
| 4
|
# -*- coding: utf-8 -*-
def hyphenate(path):
"""Replaces underscores with hyphens"""
return path.replace('_', '-')
def mixedcase(path):
"""Removes underscores and capitalizes the neighbouring character"""
words = path.split('_')
return words[0] + ''.join(word.title() for word in words[1:])
def camelcase(path):
"""Applies mixedcase and capitalizes the first character"""
return mixedcase('_{0}'.format(path))
| true
|
d817d8f491e23137fd24c3184d6e594f1d8381b0
|
GaneshManal/TestCodes
|
/python/practice/syncronous_1.py
| 945
| 4.15625
| 4
|
"""
example_1.py
Just a short example showing synchronous running of 'tasks'
"""
from multiprocessing import Queue
def task(name, work_queue):
if work_queue.empty():
print('Task %s nothing to do', name)
else:
while not work_queue.empty():
count = work_queue.get()
total = 0
for x in range(count):
print('Task %s running' % name)
total += 1
print('Task %s total: %s' %(name, str(total)))
def main():
"""
This is the main entry point for the program
"""
# create the queue of 'work'
work_queue = Queue()
# put some 'work' in the queue
for work in [15, 10, 5, 2]:
work_queue.put(work)
# create some tasks
tasks = [
(task, 'One', work_queue),
(task, 'Two', work_queue)
]
# run the tasks
for t, n, q in tasks:
t(n, q)
if __name__ == '__main__':
main()
| true
|
68a9fa74fcc26279e1e184eb9281e458c86b3937
|
GaneshManal/TestCodes
|
/python/practice/sqaure_generator.py
| 510
| 4.15625
| 4
|
# Generator Function for generating square of numbers
def square_numbers(nums):
for num in nums:
yield num*num
numbers = range(1, 6)
gen_x = square_numbers(numbers)
print "Generator Object : ", gen_x
print "Generator Mem : ", dir(gen_x)
""""
'print '--->', gen_x.next()
print '--->', gen_x.next()
print '--->', gen_x.next()
print '--->', gen_x.next()
print '--->', gen_x.next()
# print '--->', gen_x.next() # StopIteration Exception.
"""
# print list(gen_x)
for num in gen_x:
print num,
| false
|
5a9161c4f8f15e0056fd425a5eee58de16ec45bf
|
beb777/Python-3
|
/003.py
| 417
| 4.28125
| 4
|
#factorial n! = n*(n-1)(n-2)..........*1
number = int(input("Enter a number to find factorial: "))
factorial = 1;
if number < 0:
print("Factorial does not defined for negative integer");
elif (number == 0):
print("The factorial of 0 is 1");
else:
while (number > 0):
factorial = factorial * number
number = number - 1
print("factorial of the given number is: ")
print(factorial)
| true
|
1c922b07b6b1f011b91bc75d68ece9b8e2958576
|
Leah36/Homework
|
/python-challenge/PyPoll/Resources/PyPoll.py
| 2,168
| 4.15625
| 4
|
import os
import csv
#Create CSV file
election_data = os.path.join("election_data.csv")
#The list to capture the names of candidates
candidates = []
#A list to capture the number of votes each candidates receives
num_votes = []
#The list to capture the number of votes each candidates gather
percent_votes = []
#The counter for the total number of votes
total_votes = 0
with open(election_data, newline = "") as csvfile:
csvreader = csv.reader(csvfile, delimiter = ",")
csv_header = next(csvreader)
for row in csvreader:
#Add to our vote-countr
total_votes += 1
#If the candidate is not on our list, add his/her name to our list, along with
#a vote in his/her name.
#If he/she is already on our list, we will simply add a vote in his/her name.
if row[2] not in candidates:
candidates.append(row[2])
index = candidates.index(row[2])
num_votes.append(1)
else:
index = candidates.index(row[2])
num_votes[index] += 1
#Add to percent_votes list
for votes in num_votes:
percentage = (votes/total_votes) * 100
percentage = round(percentage)
percentage = "%.3f%%" % percentage
percent_votes.append(percentage)
#Find the winning candidate
winner = max(num_votes)
index = num_votes.index(winner)
winning_candidate = candidates[index]
#Display the results
print("Election Results")
print("------------")
print(f"Total Votes:{str(total_votes)}")
print("------------")
for i in range(len(candidates)):
print(f"{candidates[1]}: {str[percent_votes[i])} ({str(num_votes[i])})")
print("-----------")
print(f"Winner: {winning_candidate}")
print("----------")
#Print to a text file
output = open("output.txt", "w")
line1 = "Election Results"
line2 = "----------"
line3 = str(f"Total Votes: {str(total_votes)}")
line4 = str("----------")
output.write('{}\n{}\n{}\n{}\n'.formate(line1, line2, line3, line4))
for i in range(len(candidates)):
line = str(f"{candidate[i]}: {str(percent_votes[i])} ({str(num_votes[i])})")
output.write('{}\n'.format(line))
line5 = "-----------"
line6 = str(f"Winner: {winning_candidate}")
line7 = "-----------"
output.write('{}\n{}\n{}\n'.format(line5, line6,line7))
| true
|
faaf4b222a3b9e120d0197c218bcd6e25c3422a4
|
bwblock/Udacity
|
/CS101/quiz-median.py
| 621
| 4.21875
| 4
|
#! /usr/bin/env python
# Define a procedure, median, that takes three
# numbers as its inputs, and returns the median
# of the three numbers.
# Make sure your procedure has a return statement.
def bigger(a,b):
if a > b:
return a
else:
return b
def biggest(a,b,c):
return bigger(a,bigger(b,c))
def median(a,b,c):
big1 = bigger(a,b)
big2 = bigger(b,c)
big3 = bigger(a,c)
max = biggest(a,b,c)
if big1 == big2:
return big3
if max == big1:
return big2
else:
return big1
print(median(1,3,2))
#>>> 2
print(median(9,3,6))
#>>> 6
print(median(7,8,7))
#>>> 7
| true
|
a759beda8dd1ef2309a0c200c3442bed4228f455
|
naotube/Project-Euler
|
/euler7.py
| 616
| 4.21875
| 4
|
#! /usr/bin/env python
# By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13,
# we can see that the 6th prime is 13.
# What is the 10001st prime number?
primes = [2,3]
def is_prime(num):
"""if num is a prime number, returns True, else returms False"""
for i in primes:
if num % i == 0:
return False
return True
def next_prime(num):
"""returns a first prime number larger than num"""
while 1:
num = num + 1
if is_prime(num):
return num
i = 2
while len(primes) < 10002:
i = next_prime(i)
primes.append(i)
print(primes[10000])
| true
|
cd9902d851dd5f7d4527d6bb80fa8abf13ef59c7
|
ubaidahmadceh/python_beginner_to_expert
|
/isdigit_function.py
| 218
| 4.25
| 4
|
number = input("Enter your number : ")
if number.isdigit():
print("this is numeric (0-9)")
elif number.isalpha():
print("this is string !!")
else:
print("This is not numeric , this is symbol or alphabet")
| true
|
95a17e11a79f68563c393524c22b6f45b0365599
|
rob256/adventofcode2017
|
/python3/day_2/day_2_part_1.py
| 977
| 4.15625
| 4
|
from typing import List
def checksum_line(numbers_list: iter) -> int:
"""
Given a list of numbers, return the value of the maximum - minimum values
"""
min_number = max_number = numbers_list[0]
for number in numbers_list[1:]:
min_number = min(min_number, number)
max_number = max(max_number, number)
return max_number - min_number
def get_number_list_from_line(number_list_string: str) -> List[int]:
return list(map(int, number_list_string.split()))
def checksum_spreadsheet(spreadsheet_string: str) -> int:
total_checksum = 0
for number_list_string in spreadsheet_string.split('\n'):
number_list = get_number_list_from_line(number_list_string)
total_checksum += checksum_line(number_list)
return total_checksum
def main():
with open('input.txt') as input_file:
input_text = input_file.read().rstrip()
print(checksum_spreadsheet(input_text))
if __name__ == '__main__':
main()
| true
|
e6886af2f0373dea4fac1f974cfca7574bca353b
|
daniel-cretney/PythonProjects
|
/primality_functions.py
| 481
| 4.4375
| 4
|
# this file will take a number and report whether it is prime or not
def is_primary():
number = int(input("Insert a number.\n"))
if number <= 3:
return True
else:
divisor = 2
counter = 0
for i in range(number):
if number % divisor == 0:
counter += 1
if counter > 0:
return False
else:
return True
if __name__ == "__main__":
print(is_primary())
| true
|
48ea70aaf45047d633f7469efd286ddcfb1a4ec3
|
jamesjakeies/python-api-tesing
|
/python3.7quick/5polygon.py
| 347
| 4.53125
| 5
|
# polygon.py
# Draw regular polygons
from turtle import *
def polygon(n, length):
"""Draw n-sided polygon with given side length."""
for _ in range(n):
forward(length)
left(360/n)
def main():
"""Draw polygons with 3-9 sides."""
for n in range(3, 10):
polygon(n, 80)
exitonclick()
main()
| true
|
1f7ed4325ab493a60d95e04fa38d22d30578a966
|
jamesjakeies/python-api-tesing
|
/python3.7quick/4face.py
| 622
| 4.25
| 4
|
# face.py
# Draw a face using functions.
from turtle import *
def circle_at(x, y, r):
"""Draw circle with center (x, y) radius r."""
penup()
goto(x, y - r)
pendown()
setheading(0)
circle(r)
def eye(x, y, radius):
"""Draw an eye centered at (x, y) of given radius."""
circle_at(x, y, radius)
def face(x, y, width):
"""Draw face centered at (x, y) of given width."""
circle_at(x, y, width/2)
eye(x - width/6, y + width/5, width/12)
eye(x + width/6, y + width/5, width/12)
def main():
face(0, 0, 100)
face(-140, 160, 200)
exitonclick()
main()
| false
|
29362f4276d7ac83c520b89417bed94d2a771a4f
|
jamesjakeies/python-api-tesing
|
/python_crash_tutorial/Ch1/randomwalk.py
| 352
| 4.25
| 4
|
# randomwalk.py
# Draw path of a random walk.
from turtle import *
from random import randrange
def random_move(distance):
"""Take random step on a grid."""
left(randrange(0, 360, 90))
forward(distance)
def main():
speed(0)
while abs(xcor()) < 200 and abs(ycor()) < 200:
random_move(10)
exitonclick()
main()
| true
|
51578c97eb0b4a7478be114fa2eca98b713613ca
|
WillDutcher/Python_Essential_Training
|
/Chap05/bitwise.py
| 674
| 4.375
| 4
|
#!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
# Completed Chap05: Lesson 21 - Bitwise operators
x = 0x0a
y = 0x02
z = x & y
# 02x gives two-character string, hexadecimal, with leading zero
# 0 = leading zero
# 2 = two characters wide
# x = hexadecimal display of integer value
# 08b gives eight-character string, binary, with leading zeroes
# 0 = leading zeroes, where applicable
# 8 = 8 characters wide
# b = binary display of integer value
print(f'(hex) x is {x:02x}, y is {y:02x}, z is {z:02x}')
print(f'(bin) x is {x:08b}, y is {y:08b}, z is {z:08b}')
print("&\tAnd")
print("|\tOr")
print("^\tXor")
print("<<\tShift left")
print(">>\tShift right")
| true
|
1ce0280f860821796f022583f2b5b96950f587b9
|
WillDutcher/Python_Essential_Training
|
/Chap05/boolean.py
| 670
| 4.1875
| 4
|
#!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
# Completed Chap05: Lesson 23 - Comparison operators
print("\nand\t\tAnd")
print("or\t\tOr")
print("not\t\tNot")
print("in\t\tValue in set")
print("not in\t\tValue not in set")
print("is\t\tSame object identity")
print("is not\t\tNot same object identity\n")
print("*"*50,"\n")
a = True
b = False
x = ( 'bear', 'bunny', 'tree', 'sky', 'rain' )
y = 'tree'
if a and b:
print('expression is true')
else:
print('expression is false')
if y in x:
print("Yep, it is.")
else:
print("Nope, it's not.")
if y is x[0]:
print("Yes, that's the same.")
else:
print("No, they're different.")
| true
|
9be5e6cad8942160830e3d4bcca8c66dcac52370
|
Avinashgurugubelli/python_data_structures
|
/linked_lists/singly_linked_list/main.py
| 2,546
| 4.46875
| 4
|
from linked_list import LinkedList
from node import Node
# Code execution starts here
if __name__ == '__main__':
# Start with the empty list
linked_list_1 = LinkedList()
# region nodes creation
first_node, second_node, third_node = Node(), Node(), Node()
first_node.data = 5
second_node.data = 10
third_node.data = 36
# endregion
# region assigning nodes to linked list
linked_list_1.head = first_node
'''
Three nodes have been created.
We have references to these three blocks as first,
second and third
linked_list_1.head second_node third_node
| | |
| | |
+----+------+ +----+------+ +----+------+
| 5 | None | | 10 | None | | 36 | None |
+----+------+ +----+------+ +----+------+
'''
linked_list_1.head.next = second_node # Link first node with second
'''
Now next of first Node refers to second. So they
both are linked.
linked_list_1.head second_node third_node
| | |
| | |
+----+------+ +----+------+ +----+------+
| 5 | o-------->| 10 | null | | 36 | null |
+----+------+ +----+------+ +----+------+
'''
second_node.next = third_node # Link second node with the third node
'''
Now next of second Node refers to third. So all three
nodes are linked.
linked_list_1.head second third
| | |
| | |
+----+------+ +----+------+ +----+------+
| 5 | o-------->| 10 | o-------->| 36 | null |
+----+------+ +----+------+ +----+------+
'''
lst_Length = linked_list_1.get_list_length
print('length of linked List: '+ str(lst_Length))
linked_list_1.print_list()
# endregion
# region Node insertion
linked_list_1.insert_node_at_position(0, 112) # Insertion at beginning
linked_list_1.insert_node_at_position(linked_list_1.get_list_length, 236) # Insertion at end
linked_list_1.insert_node_at_position(3, 99)
# endregion
# region node deletion
linked_list_1.delete_node_at_position(0)
linked_list_1.delete_node_at_position(3)
linked_list_1.delete_node_at_position(linked_list_1.get_list_length)
# end region
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.