blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
c78d2209e973d885f5033c4baae57689b3f78479 | amplify-education/terrawrap | /terrawrap/utils/collection_utils.py | 783 | 4.25 | 4 | """Utilities for working with collections"""
from typing import Dict
def update(dict1: Dict, dict2: Dict) -> Dict:
"""
Recursively updates the first provided dictionary with the keys and values from the second dictionary.
Child dictionary and lists are merged, not replaced.
:param dict1: The dictionary to merge into.
:param dict2: The dictionary to merge.
:return: A merged dictionary.
"""
for key, value in dict2.items():
if isinstance(value, dict):
dict1[key] = update(dict1.get(key, {}), value)
elif isinstance(value, list):
original_value = dict1.get(key, [])
original_value.extend(value)
dict1[key] = original_value
else:
dict1[key] = value
return dict1
| true |
7a498f91f5f96e1951116a4805354bcf83a6e523 | zhrcosta/string-functions | /split_method_1.py | 1,064 | 4.28125 | 4 |
def splitM1(string):
# Função para separar uma frase ou texto, usando o espaço como separador, retornando uma lista de palavras.
# Todos os caracteres diferentes de " "(espaço) são armazenados temporariamente aqui.
word = ""
# Lista que será retornada com os grupos de caracteres.
word_list = []
for character in string:
# Cada valor diferente de (espaço) é concatenado em WORD.
if not character == " ":
word += character
# Ao detectar um espaço na condição acima o grupo de caracteres é adicionado a lista.
# E a variavel WORD é limpa para formação de uma nova palavra.
else:
if word != "":
word_list.append(word)
word = ""
# Ao final da execução do Loop For a variável WORD pode conter um grupo de caracteres que deve ser adicionado a lista.
if word != "":
word_list.append(word)
word = ""
return word_list
print(splitM1(" Where there is matter, there is geometry "))
| false |
9713d21d44e797fc0cc05051054a7f598a052d7a | himavardhank/py_practice-2 | /array_leftshift.py | 275 | 4.15625 | 4 | arr=[1,2,3,4,5]
n=int(input("enter how many elements to shift"))
print('origional',arr)
for i in range(0,n):
first=arr[0]
for j in range(0,len(arr)-1):
arr[j]=arr[j+1]
arr[len(arr)-1]=first
for i in range(0,len(arr)):
print(arr[i],end='')
| false |
27332172c61b44dbdbe1e0f87673d4f925548384 | GunSik2/python-alogorithm | /src/sort_bubble.py | 728 | 4.3125 | 4 | # Bubble Sort
# Time: O(n^2)
# Conceptual Diagram : https://www.tutorialspoint.com/data_structures_algorithms/bubble_sort_algorithm.htm
def bubbleSort(list):
keepOn = True
step = 1
while keepOn:
keepOn = False
for index in range(len(list) - 1):
if list[index] > list[index + 1]:
# swap two element
temp = list[index]
list[index] = list[index + 1]
list[index + 1] = temp
# need more cycle
keepOn = True
print("step " + str(step) + " : " + str(list))
step += 1
return list
if __name__ == "__main__":
list = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
print(bubbleSort(list))
| false |
823c9d90b1a0d9236fd0dd7d7b0a1c42703dbe18 | Charmi15/dailypractice | /oddeven.py | 239 | 4.15625 | 4 | numbers=(1,2,3,4,5,6,7,8,9)
count_odd=0
count_even=0
for x in numbers:
if not x%2:
count_even+=1
else:
count_odd+=1
print("no.of even numbers :",count_even)
print("no.of odd numbers :", count_odd)
| true |
43645fd86791b9ac5cd4bbe36aea21396c228981 | mehulchopradev/ivan-python-core | /function_objects.py | 1,043 | 4.15625 | 4 | def abc(): # function object -> abc (module)
i = 10 # int object -> i (abc)
j = 20 # int object -> j (abc)
m = 30 # int object -> m (abc)
# in python a function can be defined inside another function
def pqr(): # function object -> pqr (abc)
print(i) # inner function can access (get) the enclosing function variables (closures)
j = 40 # int object -> j (pqr)
print(j) # 40
# m = m + 40 # does not work
# print(m)
pqr()
print(j) # 20
print(m) # 30
abc()
# pqr() # this will not work
def mno(x): # function object -> mno (module)
def rty(y): # function object -> rty (mno)
return (y ** 2) + x
# in python a function can return another function
return rty
m = mno(1) # m -> function object <- rty
n = mno(2) # n -> function object <- rty
print(m(5))
print(n(5))
def fun(x): # function object -> fun (module)
return x ** 2
def pqr(y, f): # function object -> pqr (module)
return f(y)
# in python a function can be passed as an argument to another function
ans = pqr(5, fun)
print(ans) | false |
15f18b5321c2f8b43f0c5cb66cf65bcdd94bbcfd | yinruei/python- | /effective_python/method22.py | 2,139 | 4.125 | 4 | '''
假設你想要紀錄一些學生的成績,但事先並不知道他們的姓名。
你可以定義一個類別來將那些名字儲存在一個字典中,而非為每個學生使用一個預先定義的屬性
'''
class SimpleGradebook(object):
def __init__(self):
self._grades={}
def add_student(self, name):
self._grades[name]=[]
def report_grade(self, name, score):
self._grades[name].append(score)
def average_grade(self, name):
grades = self._grades[name]
# print(grades)
return sum(grades) / len(grades)
book = SimpleGradebook()
book.add_student('Isaac Newton')
book.report_grade('Isaac Newton', 90)
print(book.average_grade('Isaac Newton'))
print('--------------------------------------------------------------')
'''
假設你想要擴充SimpleGradebook類別,讓他維護一個串列來記錄以科目區分的成績,
而非只有整體成績。你可以修改_grades字典來將學生姓名(也就是鍵值)映射到另一個字典中(存放那些值)。
最內層的字典會將科目(鍵值)映射到成績(值)
'''
class BySubjectGradebook(object):
def __init__(self):
self._grades={}
def add_student(self, name):
self._grades[name]={}
def report_grade(self, name, subject, grade):
by_subject = self._grades[name]
print(type(by_subject))
grade_list = by_subject.setdefault(subject, [])
# setdefault前面必須是個字典,後面的參數(key,default),key是找尋的鍵值,defult是當鍵值不存在時,設定的默認鍵值
print(type(grade_list))
grade_list.append(grade)
def average_grade(self, name):
by_subject = self._grades[name]
total, count = 0, 0
for grades in by_subject.values():
total += sum(grades)
count += len(grades)
return total / count
book = BySubjectGradebook()
book.add_student('Albert Einstein')
book.report_grade('Albert Einstein', 'Math', 75)
book.report_grade('Albert Einstein', 'Math', 65)
book.report_grade('Albert Einstein', 'Gym', 90)
book.report_grade('Albert Einstein', 'Gym', 95)
print(book.average_grade('Albert Einstein'))
| false |
75729fdc3c873a4fed862340f4781274a7e22e4c | nandanreddy123/python_ipt | /task6_9.py | 464 | 4.1875 | 4 | num1=int(input('enter the first value'))
num2=int(input('enter the second value'))
action= input('press corresponding symbols for calculation')
if(action == '+'):
print('addition of',num1,',',num2,'is',num1+num2)
elif(action == '-'):
print('subtraction of',num1,',',num2,'is',num1-num2)
elif(action == '/'):
print('division of',num1,',',num2,'is',num1/num2)
elif(action == '*'):
print('multiplication of',num1,'and',num2,'is',num1*num2) | false |
6ec94b38dc5712ac3f1fdefaf91a9b5cb14e626e | gopi-123/python_projects | /Guess_me_python_project.py | 807 | 4.25 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 15 13:45:25 2018
@author: gopinath
"""
# Guess me Project - Similar to rolling a dice problem and guessing the number
#import random module
import random as a
#a is an alias to module random
#get input from the user
#type cast "string input" to integer value
guess= int(input("Please enter your guessing number between 1 to 2 \n"))
#print("your guess number:", guess)
#generate a random nubmer from 1 until 2
game_hidden_num= a.randint(1,2)
#print("game* num:" ,game_hidden_num)
#check whether it is right or wrong
#print("type(guess):",type(guess))
#print("type(game_num)", type(game_num))
if (guess==game_hidden_num):
print(" Congrats! you guessed it right")
else:
print("Sorry your guess was not right") | true |
3954b8ceb700a7c6b01b97ae6958f9b2730131e4 | elim723/PythonFun | /reverse_word_order.py | 213 | 4.3125 | 4 | #!/usr/bin/env python
# get users input
string = raw_input ('Give me a sentence please: ')
# reverse order
reverse = ' '.join (string.split (' ')[::-1])
# print results
print ('reversed: {0}'.format (reverse))
| true |
5540598b4ce0e4bc1a68096f17e25da93e55e31b | davishek7/PythonTest | /Swayam/ProductOfPrime.py | 659 | 4.28125 | 4 | """
A positive integer m is a prime product if it can be written as p×q,
where p and q are both primes.
Write a Python function primeproduct(m) that takes an integer m as input and
returns True if m is a prime product and False otherwise.
(If m is not positive, your function should return False.)
"""
from math import sqrt
def primeproduct(m):
for d1 in range(2,int(sqrt(m)+1)):
if m%d1==0:
d2=m/d1
return is_Prime(d1) and is_Prime(d2)
return False
def is_Prime(n):
for i in range(2,int(sqrt(n)+1)):
if n%i==0:
return False
return True
result=primeproduct(202)
print(result)
| true |
226a2d3619da9a036ce8b7c407f92fa5374880f0 | JonathanC13/python_ref | /14_sets/sets_removeDup.py | 1,445 | 4.15625 | 4 | # using sets have a list that has no duplicates
# sets are an unordered list of unique values, can do list functions except indexing
def sets_noDup(userList = "Input the list you would like to be put through a set (seperated by a space): "):
userIn = [int(x) for x in input(userList).split()]
result = set(userIn) #convert to set, removes duplicates
print(result)
import random
def ListOverlap():
list_size1 = random.randint(5, 10)
list_size2 = random.randint(5, 10)
# dynamic arrays
list1 = []
list2 = []
resultList = []
#for x in range(2, 30, 3): start, end, incre
for x in range(list_size1):
randValue = random.randint(0, 5)
list1.append(randValue)
for y in range(list_size2):
randValue = random.randint(0, 5)
list2.append(randValue)
for z in range(len(list1)):
# check for overlap
if list1[z] in list2:
resultList.append(list1[z])
# deal with duplicates by converting it into a set
finalList = set(resultList)
print("List 1 contains: ")
print (*list1, sep=', ')
print ("\n")
print("List 2 contains: ")
print (*list2, sep=', ')
print ("\n")
print ("The result List is: ")
print (finalList)
print("\n")
print("Turning set back to list, check if worked by getting an index[0]: ")
listlist = list(finalList)
print(listlist[0])
#sets_noDup()
ListOverlap()
| true |
b6f7322071b56309614fa7c6e436775abc4ad5f7 | sshukla31/misc_algos | /misc/jumble_word.py | 2,542 | 4.25 | 4 | """
This module performs word jumble operation.
The program accepts a string as input, and then return a list of words that can be created using the submitted letters. For example, on the input "dog", the program should return a set of words including "god", "do", and "go".
"""
def permutation(word, k=0, result=None):
"""
Perform word permutation
Args:
word (str): Word to perform permutation on
k=0 (int): Start index
result (list): List to store final result
Returns:
result (list): List of permuted words
Exception:
None
"""
if k == len(word):
result += ["".join(map(str, word))]
else:
for index in range(k, len(word)):
word[k], word[index] = word[index], word[k]
permutation(word, k + 1, result)
word[k], word[index] = word[index], word[k]
return result
def combination(k, available, used):
"""
Perform word combination
Args:
k=2 (int): combinations word count
available (str): Word to perform combination on
used (list): List to store final result
Returns:
used (list): List of word combinations
Exception:
None
"""
if len(used) == k:
yield list(used)
elif len(available) == 0:
pass
else:
head = available.pop(0)
used.append(head)
for c in combination(k, available, used):
yield c
used.pop()
for c in combination(k, available, used):
yield c
available.insert(0, head)
def search_file(word):
"""
Search file for a given word
Args:
word(string): String to be searched in File
Returns:
True in case of success or False
Exception:
OSError and IOError
"""
try:
with open('en_US.dic') as inf:
for line in inf:
if word.lower() == line.partition("/")[0].lower():
return True
except (OSError, IOError) as ex:
raise ex
return False
if __name__ == '__main__':
query = raw_input("Input word : ").strip()
if len(query) == 0:
print "Please enter some value"
else:
combs = []
result = []
for k in range(2, len(query) + 1):
for word in combination(k, list(query), []):
for element in permutation(word=word, result=[]):
if search_file("".join(element)):
result.append("".join(element))
print sorted(result)
| true |
6fc50251ed50c5a5bfddc5123f22fede612514fb | KonechyJ/PacManClone | /_pacman/_pacman/vector.py | 2,746 | 4.53125 | 5 | from math import sqrt
#start of vector class and variables used in the functions below
class Vector2(object):
def __init__(self, x=0, y=0):
self.x = x
self.y = y
self.thresh = 0.000001
#Simply can add and subtract vectors
def __add__(self, other):
return Vector2(self.x + other.x, self.y + other.y)
def __sub__(self, other):
return Vector2(self.x - other.x, self.y - other.y)
#functions to address a negative vector
def __neg__(self):
return Vector2(-self.x, -self.y)
##Simply can multiply and and divide vectors
def __mul__(self, scalar):
return Vector2(self.x * scalar, self.y * scalar)
def __div__(self, scalar):
if scalar != 0:
return Vector2(self.x / float(scalar), self.y / float(scalar))
return None
#Python 3 uses trueDiv
def __truediv__(self, scalar):
return self.__div__(scalar)
#This function allows us to say the two numbers that are extremely similar( but technically different) are actually the same
# Ex.) 3 == 3.000000001 if the type of comparison this function would allow
def __eq__(self, other):
if abs(self.x - other.x) < self.thresh:
if abs(self.y - other.y) < self.thresh:
return True
return False
#returns the hash Id to be used whenever needed
def __hash__(self):
return id(self)
#This Function alternatively returns the length of the vector, without requiring a square root
def magnitudeSquared(self):
return self.x ** 2 + self.y ** 2
# This functions allows us to return the actual length of a vector, while using the sqrt function
def magnitude(self):
return sqrt(self.magnitudeSquared())
#This function takes the magnitude of a vector in order to return a normalized value
def normalize(self):
mag = self.magnitude()
if mag != 0:
return self.__div__(mag)
return None
#this function returns the dot product of Vector Object
def dot(self, other):
return self.x * other.x, self.y * other.y
#This method lets us make a copy of a vector and create a new instance of it
def copy(self):
return Vector2(self.x, self.y)
#This function lets us convert our vectors into tuples
def asTuple(self):
return self.x, self.y
#And this functions lets function lets us turn the function into an int tuple
def asInt(self):
return int(self.x), int(self.y)
#This function is used to print out vectors for testing purpuses
def __str__(self):
return "<"+str(self.x)+", "+str(self.y)+">" | true |
c5cc0eb11c35fc88eff9ea89cf05e39ccb7f1b18 | mariomenjr/wgups | /app/models/route.py | 1,404 | 4.1875 | 4 |
class Route(object):
CONSTANT_SPEED = 18
def __init__(self, places):
self.places = places
self.time = 0
self.miles = 0
self.calculate_cost()
# this method sole purpose is helping us avoid duplicated code
# it provides a loop interface and a callback is provided
# so the actions in the call back get called in each loop
# passign origin and destination places
# as the system is traveling the route
# Complexity: O(n)
def travel_route(self, callback):
for i, origin in enumerate(self.places):
j = i + 1
if j == len(self.places): break
callback(origin, self.places[j])
# Complexity: O(n)
def calculate_cost(self):
# the whole cost in time and miles is calculated for this truck
def accumulate_props(origin, destination):
self.time = self.time + self.get_time_between_places(origin, destination)
self.miles = self.miles + self.find_distance_between_places(origin, destination)
self.travel_route(accumulate_props)
# Complexity: O(1)
def get_time_between_places(self, one, two):
distance = float(one.points[two.index])
return distance / self.CONSTANT_SPEED
# Complexity: O(1)
def find_distance_between_places(self, one, two):
return float(one.points[two.index])
| true |
784a163d9b0f0904dccd0af6d23636211abcf031 | Jvanschoubroeck/Topology-optimization | /binary_filter.py | 2,062 | 4.3125 | 4 | import numpy as np
def binary_filter(array, average, lb=0, ub=1):
"""Filter values of an array to lower and upper values without trespassing the average.
Parameters
----------
array: numpy array
Input array.
average: float
Upper bound for the average of the new array.
lb: float, optional
Lower boundary for values in return array.
ub: float, optional
Upper bounday for values in return array.
Returns
-------
array: numpy array
Array with values equal to lb and ub. The average of this array is equal or smaller to average.
Raises
------
ValueError
When the average is above the upper or below the lower bound.
Examples
--------
Examples should be written in doctest format, and should illustrate how
to use the function.
>>> x = np.array([[0.68, 0.24, 0.42], [0.49, 0.87, 0.79], [0.2, 0.2, 0.8]])
>>> binary_filter(x, .6)
array[[ 1. 0. 0.]
[ 1. 1. 1.]
[ 0. 0. 1.]]
>>> binary_filter(x, .6, .2, .8)
array[[ 0.8 0.2 0.2]
[ 0.8 0.8 0.8]
[ 0.2 0.2 0.8]]
"""
assert lb <= average, ('Average below lower bound.')
assert average <= ub , ('Average above upper bound.')
try:
number_of_elements = array.shape[0] * array.shape[1]
except IndexError:
number_of_elements = array.shape[0]
minimum_array_value = np.min(array)
for n, m in enumerate(reversed(np.sort(array.flatten()))):
elements_above_m = np.where(array > m)[0].shape[0]
new_array_average = ((elements_above_m * ub) + (number_of_elements - elements_above_m) * lb) / number_of_elements
if new_array_average > average:
minimum_array_value = np.sort(array.flatten())[-1 - (n - 1)]
break
new_array = array.copy()
new_array[np.where(new_array > minimum_array_value)] = ub
new_array[np.where(new_array != ub)] = lb
return new_array
| true |
cdadc3ba2e3e1566661c553b0fe29b7ee41336ff | DevelopGadget/Basico-Python | /Recursos Profe/Lists-Management.py | 1,623 | 4.46875 | 4 | #Creacion de una Lista
thislist = ["apple", "banana", "cherry"]
print(thislist)
#Acceso a los elementos
print(thislist[1])
#Cambiar el valor de un elemento
thislist[1] = "blackcurrant"
print(thislist)
#Iterar en una lista
for x in thislist:
print(x)
#Verificar si un elemento de la lista existe
if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")
#Longitud de una Lista
print(len(thislist))
#Adicionar un elemento al final de la lista
thislist.append("orange")
print(thislist)
#Insertar un elemento en una posicion especifica de la lista
thislist.insert(1, "orange")
print(thislist)
#Eliminar un especificado elemento de la lista
thislist.remove("blackcurrant")
print(thislist)
#Elimina el indice especificado...si no se coloca , elimina el ultimo de la lista
thislist.pop()
print(thislist)
#Elimina el indice especificado
del thislist[0]
print(thislist)
#vaciar una lista
thislist.clear()
print(thislist)
#Eliminar la lista completamente
del thislist
#print(thislist)
#Copiar una lista
fruits = ['apple', 'banana', 'cherry', 'orange']
x = fruits.copy()
print("Lista original:", fruits)
print("Copia de la Lista: ", x)
#Devolver el numero de elementos con un valor especificado en la lista
z = fruits.count("cherry")
print("cherry aparece ", z, " veces en la lista")
#Adicionar los elementos de una lista a otra lista
cars = ['Ford', 'BMW', 'Volvo']
fruits.extend(cars)
print("Lista Extendida ", fruits)
#Reversa o inversa de una lista
print("Lista original ", fruits)
fruits.reverse()
print("Lista invertida ", fruits)
#Ordenar una lista
fruits.sort()
print("Lista ordenada ", fruits) | false |
09b84f5e12dd6c76fadd76eb1660b508b87baeaf | DimitrijeKojic/IU7 | /semester 1/Python Labs/прога_семинар_1_11.py | 2,818 | 4.375 | 4 | # Квадратная матрица поменять минимальный элемент и дигональный элемент строки.
def getMatrix():
size = int(input('Введите размер квадрвтной матрицы: '))
matrix = [0] * size
print('Построчно введите элементы матрицы:')
for i in range(size):
matrix[i] = list(map(float, input('> ').split()))
return matrix, size
def printMatrix(matrix):
for i in range(len(matrix)):
print(matrix[i])
matrix, size = getMatrix()
for i in range(size):
minElIndex = 0
for j in range(size):
if matrix[i][j] < matrix[i][minElIndex]:
minElIndex = j
matrix[i][minElIndex],matrix[i][i] = matrix[i][i], matrix[i][minElIndex]
print(printMatrix(matrix))
#------------------------------------------------------------------------------
#Из квадратной матрицы убрать главную диагональ и нижний треугольник подвинуть вверх
n = int(input('Введите размер квадрвтной матрицы: '))
mat = []
for i in range(n):
x = list(map(int, input().split()))
mat.append(x)
print(mat)
for i in range(n):
for j in range(n-1):
if i >= j:
mat[i][j] = mat[i+1][j]
for i in range(n-1):
print(mat[i])
#------------------------------------------------------------------------------
# Сформировать квадратную матрицу ввида
# 1 2 3 4 5
# 2 1 2 3 4
# 3 2 1 2 3
# 4 3 2 1 2
# 5 4 3 2 1
n = int(input('Введите размер квадрвтной матрицы: '))
a=[n*[0] for i in range(n)]
for i in range(n):
a[0][i] = i+1
print(a[0][i], end=' ')
for i in range(1,n):
print('\n')
for j in range(i):
a[i][j] = a[i-1][j]+1
print(a[i][j], end=' ')
for j in range(i,n):
a[i][j] = a[i-1][j]-1
print(a[i][j], end=' ')
# или
M = int(input('\nВведите размер строки'))
matrix = [[i*1 for i in range(M)] for i in range(M)]
for i in range(1,M):
for j in range(M):
matrix[i][j] = matrix[i-1][(j + M - 1)% M]
[print(*i) for i in matrix]
#Найти сумму элементов матрицы под главной и побочной диагоналей и вкл их
M = int(input('\nВведите размер строки'))
matrix = [0]*M
for i in range(M):
matrix[i] = list(map(int,input().split()))
for i in range(M):
print(matrix[i])
S = 0
for i in range(M):
for j in range(M):
if (i >= j and j <= M - i - 1) or (i <= j and j >= M - i - 1):
S += matrix[i][j]
print(S)
| false |
adb82fe90b4072a6e3aba64bf08c6aa3a9a75ac2 | LorinChen/lagom | /lagom/transform/interp_curves.py | 2,049 | 4.125 | 4 | import numpy as np
def interp_curves(x, y):
r"""Piecewise linear interpolation of a discrete set of data points and generate new :math:`x-y` values
from the interpolated line.
It receives a batch of curves with :math:`x-y` values, a global min and max of the x-axis are
calculated over the entire batch and new x-axis values are generated to be applied to the interpolation
function. Each interpolated curve will share the same values in x-axis.
.. note::
This is useful for plotting a set of curves with uncertainty bands where each curve
has data points at different :math:`x` values. To generate such plot, we need the set of :math:`y`
values with consistent :math:`x` values.
.. warning::
Piecewise linear interpolation often can lead to more realistic uncertainty bands. Do not
use polynomial interpolation which the resulting curve can be extremely misleading.
Example::
>>> import matplotlib.pyplot as plt
>>> x1 = [4, 5, 7, 13, 20]
>>> y1 = [0.25, 0.22, 0.53, 0.37, 0.55]
>>> x2 = [2, 4, 6, 7, 9, 11, 15]
>>> y2 = [0.03, 0.12, 0.4, 0.2, 0.18, 0.32, 0.39]
>>> plt.scatter(x1, y1, c='blue')
>>> plt.scatter(x2, y2, c='red')
>>> new_x, new_y = interp_curves([x1, x2], [y1, y2], num_point=100)
>>> plt.plot(new_x[0], new_y[0], 'blue')
>>> plt.plot(new_x[1], new_y[1], 'red')
Args:
x (list): a batch of x values.
y (list): a batch of y values.
num_point (int): number of points to generate from the interpolated line.
Returns:
tuple: a tuple of two lists. A list of interpolated x values (shared for the batch of curves)
and followed by a list of interpolated y values.
"""
new_x = np.unique(np.hstack(x))
assert new_x.ndim == 1
ys = [np.interp(new_x, curve_x, curve_y) for curve_x, curve_y in zip(x, y)]
return new_x, ys
| true |
df054d8464f07f3233ec36da102f89500ec6efad | emmanuel2406/Week-1 | /Day00_Q2.py | 233 | 4.1875 | 4 | width = int(input("Enter the width:"))
height = int(input("Enter the height:"))
area = width * height
quad=''
if width == height:
quad += "Sqaure"
else:
quad += "Rectangle"
print("the area of the ",quad," is ",area)
| true |
f6c086c63e6ade2fd506e47567c906361744ea90 | HamzaB93/UWL_Level3_Foundation_Intro_to_Software_Dev | /Week9/Practical9ex3_3.py | 615 | 4.125 | 4 | print "\033[1;32mProgram Working\033[1;m"
def IsLeapYear(year): # function
if((year % 4) == 0): # these are all the IF rules for the entered number
if((year % 100) == 0): # these will check if the year entered can be divided by 4,100,400
if( (year % 400) == 0):
return 1
else:
return 0
else:
return 1
return 0
Year = 0
print "Program to check Leap Year"
print "Enter Year: ",
Year = input()
if( IsLeapYear(Year) == 1): # if the returned value if 1, it is a leap year.
print Year, "is a leap year"
else:
print Year, "is NOT a leap year"
| false |
68fc76b648e09fa0f33d96c8d2ce30afaf6b8e30 | HamzaB93/UWL_Level3_Foundation_Intro_to_Software_Dev | /Week7/ifstatementex.py | 327 | 4.125 | 4 | print "Why did the golfer carry an extra sock?"
userinput = raw_input ("Please press 'a' for the answer or 'r' for a rephrase ")
if userinput == "a":
print "In case he got a whole in one"
elif userinput == "r":
print "A golfer carries an extra sock while he was playing, why was that?"
else:
print "You need to press a"
| true |
3b52b155cf8427bb0ca8bbb9e641a6d9d1678bb1 | HamzaB93/UWL_Level3_Foundation_Intro_to_Software_Dev | /Week8/Practical8ex4_2.py | 593 | 4.25 | 4 | print "\033[1;32mProgram Working\033[1;m"
sentence = [str(raw_input("Type in your sentence and I will count how many words there are: "))]
# the sentence variable has a raw_input in list format []
for item in sentence: # the loop starts here
print len(item.split()) # the len function count the words in the string entered
break
newsentence = raw_input("Enter another sentene and I will show you it in reverse: ") # instruction
print newsentence, " In reverse it is: " ,newsentence[::-1] # ::-1 means count the string in reverse
# the reverse of the string entered is printed
| true |
6c3d40b63332407734fd1cc2b34108e48f7ffe6a | HamzaB93/UWL_Level3_Foundation_Intro_to_Software_Dev | /Week9/Practical9ex5.py | 1,650 | 4.21875 | 4 | print "\033[1;32mProgram Working\033[1;m"
def marktograde(a): # creating function for the first grade
if a >= 80: # if statements for the score entered
print "M1 grade: A"
elif a >= 70:
print "M1 grade: B"
elif a >= 60:
print "M1 grade: C"
elif a >= 50:
print "M1 grade: D"
elif a >= 40:
print "M1 grade: E"
elif a <= 39:
print "M1 grade: U"
mark = float(raw_input("Enter the percentage mark for module1: "))
marktograde (mark)# user input grade, the function is called upon, and will return grade
# this function is the same as the previous but for the second module grade
def marktograde2(b):
if b >= 80:
print "M2 grade: A"
elif b >= 70:
print "M2 grade: B"
elif b >= 60:
print "M2 grade: C"
elif b >= 50:
print "M2 grade: D"
elif b >= 40:
print "M2 grade: E"
elif b <= 39:
print "M2 grade: U"
mark2 = float(raw_input("Enter the second percentage mark for module2: "))
marktograde2(mark2)
def overall(c): # this function compares the two grades and gives average
if c >= 80:
print "Overall grade: A"
elif c >= 70:
print "Overall grade: B"
elif c >= 60:
print "Overall grade: C"
elif c >= 50:
print "Overall grade: D"
elif c >= 40:
print "Overall grade: E"
elif c <= 39:
print "Overall grade: U"
overallmark = (mark+mark2)/2 # working out average for the 2 scores
overall(overallmark) # the last function is called upon
| false |
a810f9be7f4520d3ead5b2a0b8abc685cf92b206 | Adam713/all-script-python-bash | /New Folder/Instagram-Posted-Sources-master/Syntax/Encryption.py | 792 | 4.5 | 4 | def encryption(string, step):
output = ""
for char in string:
# Every character has a numeric value,
# this is how the computer can understand it.
output += chr(ord(char) - step)
# We simply change the numeric value of the character,
# which results in another character.
return output
def decryption(string, step):
# Same thing, but reversed
output = ""
for char in string:
output += chr(ord(char) + step)
return output
if __name__ == "__main__":
string = "Encrypt me!"
step = 2
encrypted = encryption(string, step)
decrypted = decryption(encrypted, step)
print(f"Original: {string}")
print(f"Encrypted: {encrypted}")
print(f"Decrypted: {decrypted}")
| true |
fc6eb7a39c7c4012734cc35a76b61310f579867f | Adam713/all-script-python-bash | /New Folder/Instagram-Posted-Sources-master/Syntax/Functions.py | 1,092 | 4.28125 | 4 | def function(argument):
# Basic function that takes a single argument, which can be anything you like.
return argument
def gen_function(iterable):
# Generator function takes an iterable, manipulates the data, and returns a new iterable.
for element in iterable:
yield element
def recu_function(num):
# Recursive function returns itself until a certain value is reached.
if num == 1:
return num
else:
return num + recu_function(num-1)
# An anonymous or lambda function lets you create functions in one line,
# lets you return it as a variable and much more!
anon_function = lambda a, b: a + b
if __name__ == "__main__":
# This is the pythonic version of the main function.
# The main function is the first function that runs when a script is executed.
print(f"Standard Function: {function('python_genius')}")
print(f"Generator Function: {[*gen_function('python_genius')]}")
print(f"Recursive Function: {recu_function(5)}")
print(f"Anonymous Function: {anon_function(1, 2)}")
| true |
88c7ba4c50196afec7938769af800b85feaec9fe | KangFrank/Python_Start | /variables.py | 1,928 | 4.28125 | 4 | #!usr/bin/env Python3
#-*-coding:utf-8 -*-
#this one is liek your seripts with argv
def print_two(*args):
arg1,arg2=args
print("arg1:%r,atg2:%r"%(arg1,arg2))
#ok,that *args is actually pointless, we can just do this
def print_two_again(arg1,arg2):
print("arg1:%r,arg2:%r"%(arg1,arg2))
#function and file
from sys import argv
script,input_file=argv
def print_all(f):
print(f.raed())
def rewind(f):
f.seek(0)
def print_a_line(line_count,f):
print(line_count,f.readline())
current_file=open(input_file)
#caculation '+','-','*','/', I make it a class so that we can use it easily
class MATH_CACULATION:
def add(a,b):
print("ADDING %d+%d"%(a,b))
return a+b
def subtract(a,b):
print("SUBTRACTING %d+%d"%(a,b))
return a-b
def multiply(a,b):
print("MULTIPLYING %d*%d"%(a,b))
return a*b
def divide(a,b):
print("DIVIDING %d/%d"%(a,b))
return a/b
#more practice
def break_words(stuff):
"""This function will break up words for us."""
words=stuff.split('')
return words
def sort_words(words):
"""Sorts the wprds."""
return sorted(words)
def print_first_word(words):
"""Prints the first word after popping it off."""
word=words.pop(0)
print(word)
def print_last_word(words):
"""Prints the last word after popping it off."""
word=words.pop(-1)
print(word)
def sort_sentence(sentence):
"""Takes in a full sentence and returns the sorted words."""
word=break_words(sentence)
return sort_words(word)
def print_first_and_last(sentence):
"""Prints the first and last words of the sentence."""
words=break_words(sentence)
print_first_word(words)
print_last_word(words)
def print_first_and_last_sorted(sentence):
"""Sorts the words and then prints the first and last words of the sentence."""
words=sort_sentence(sentence)
print_first_word(words)
print_last_word(words) | true |
073ced41af783abb0f319d1837604ca1f001a67f | JerryYuan2008/driving-evaluation | /driving-evaluation.py | 524 | 4.15625 | 4 | country = input('please give your nation: ')
age = input('please give your age: ')
age = int(age)
if country == 'China':
if age >= 18:
print('you can have a driving license test')
else:
print('you are not allowed to have a driving license test')
elif country == 'America':
if age >= 16:
print('you can have a driving license test')
else:
print:('you are not allowed to have a driving license test')
else:
print('Sorry, this version only support China as well as America')
| false |
5c42fa31cbe122dead1c7319c4e18f8466f725fe | aleksiheikkila/HackerRank_Python_Problems | /Queens_Attack_II.py | 2,456 | 4.375 | 4 | '''
HackerRank problem
Domain : Python
Author : Aleksi Heikkilä
Created : Sep 2019
Problem : https://www.hackerrank.com/challenges/queens-attack-2/problem
'''
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the queensAttack function below.
def queensAttack(n, k, r_q, c_q, obstacles):
"""Complete the queensAttack function. It should return an integer that describes the number of squares the queen can attack.
queensAttack has the following parameters:
- n: an integer, the number of rows and columns in the board
- k: an integer, the number of obstacles on the board
- r_q: integer, the row number of the queen's position
- c_q: integer, the column number of the queen's position
- obstacles: a two dimensional array of integers where each element is an array of integers, the row and column of an obstacle
"""
# 8 directions
# traverse each until obstackle or out of board
# set of obstacles
obs = {(x,y) for (x,y) in obstacles}
# coordinate system. bottom left = (1,1). Let x be the width axis, y height.
DIRECTIONS = ["UP", "UPRIGHT", "RIGHT", "DOWNRIGHT", "DOWN", "DOWNLEFT", "LEFT", "UPLEFT"]
# single step dx,dy in different directions
STEPS = {"UP": (0,1), "UPRIGHT": (1,1), "RIGHT": (1,0), "DOWNRIGHT": (1,-1),
"DOWN": (0,-1), "DOWNLEFT": (-1,-1), "LEFT": (-1,0), "UPLEFT": (-1, 1)
}
num_reachable_squares = 0
for direc in DIRECTIONS:
dx, dy = STEPS[direc]
step_num = 1
while True:
curr_x = r_q + step_num * dx
curr_y = c_q + step_num * dy
# if out of board or stumbled into an obstacle, stop traversing this direction
if (curr_x < 1 or curr_x > n
or curr_y < 1 or curr_y > n
or (curr_x, curr_y) in obs):
break
else:
num_reachable_squares += 1
step_num += 1
return num_reachable_squares
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
nk = input().split()
n = int(nk[0])
k = int(nk[1])
r_qC_q = input().split()
r_q = int(r_qC_q[0])
c_q = int(r_qC_q[1])
obstacles = []
for _ in range(k):
obstacles.append(list(map(int, input().rstrip().split())))
result = queensAttack(n, k, r_q, c_q, obstacles)
fptr.write(str(result) + '\n')
fptr.close()
| true |
829da6f14fd0e3ed743fed360fef01d08988b2aa | aleksiheikkila/HackerRank_Python_Problems | /Sherlock_and_Anagrams.py | 1,074 | 4.125 | 4 | '''
HackerRank problem
Domain : Python
Author : Aleksi Heikkilä
Created : Aug 2020
Problem : https://www.hackerrank.com/challenges/sherlock-and-anagrams/problem
'''
#!/bin/python3
import math
import os
import random
import re
import sys
from collections import Counter
# Complete the sherlockAndAnagrams function below.
def sherlockAndAnagrams(s):
# A little bit too heavy
num_anagram_substrs = 0
for l in range(1, len(s)):
for left_start_pos in range(len(s)-l):
for right_start_pos in range(left_start_pos+1, len(s)-l+1):
left = s[left_start_pos:left_start_pos+l]
right = s[right_start_pos:right_start_pos+l]
if sorted(left) == sorted(right):
num_anagram_substrs += 1
return num_anagram_substrs
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
q = int(input())
for q_itr in range(q):
s = input()
result = sherlockAndAnagrams(s)
fptr.write(str(result) + '\n')
fptr.close()
| true |
aa11d339b2e8d6b52ae81ad7941f02670a93a040 | aleksiheikkila/HackerRank_Python_Problems | /Sock_Merchant.py | 1,001 | 4.28125 | 4 | '''
HackerRank problem
Domain : Python
Author : Aleksi Heikkilä
Created : Oct 2019
Problem : https://www.hackerrank.com/challenges/sock-merchant/problem
'''
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the sockMerchant function below.
def sockMerchant(n, ar):
"""
Complete the sockMerchant function . It must return an integer representing the number of matching pairs of socks that are available.
sockMerchant has the following parameter(s):
n: the number of socks in the pile
ar: the colors of each sock
"""
num_pairs = 0
counts = {}
for sock in ar:
counts[sock] = counts.get(sock, 0) + 1
for count in counts.values():
num_pairs += count // 2
return num_pairs
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
ar = list(map(int, input().rstrip().split()))
result = sockMerchant(n, ar)
fptr.write(str(result) + '\n')
fptr.close()
| true |
64716aca3c1a92d72330f4d4808e76e6e284607a | vaishaliyosini/Python_Concepts | /3.multiple_variable.py | 307 | 4.1875 | 4 | # assign values to multiple variables in a single line
a, b, c = 1, 2, 3
# assign values with different data types to multiple variables in a single line
a, b, c = 1, 3.5, "hello"
print (type(a)) # prints <type 'int'>
print (type(b)) # prints <type 'float'>
print (type(c)) # prints <type 'str'>
| true |
37482677ee9be8c67ae25c8cdc8cbff27e6dc659 | kmmcgarry/SecretSanta | /SecretSanta.py | 1,532 | 4.21875 | 4 | # SECRET SANTA ALGORITHM
import random
def SecretSantaGenerator(file):
# Take in a text file with an array of names with delimiter "|"
inFile = open(file,"r")
people = ""
# Append the names to a list, a list of strings
for line in inFile:
people += line
people = people.split("|")
# We now have a list of strings, where each index contains a different participant
# Randomly assign a secret santa by parsing through list, making sure no name is repeated
SecretSantaDict = {}
takenRecievers = []
for name in people:
while (True):
reciever = random.choice(people)
if reciever != name:
# Make sure reciever is not already taken
if reciever not in takenRecievers:
break
else:
continue
# Return a dictionary with the key = Secret Santa (giver) and value = receiver
SecretSantaDict[name]= reciever
takenRecievers.append(reciever)
return SecretSantaDict
# Take user input so the Secret Santa can figure out who their receiver is
def findReciever(dictionary):
print "Please enter your name to find out who you are Secret Santa to: "
name = raw_input()
if name in dictionary.keys():
print dictionary[name]
else:
print "This name is not on our list. Try again."
#COMMANDS
fileLocation = "/Users/kristen/Documents/Kristen_Codes/Secret_Santa/SecretSantaParticipants.txt"
findReciever(SecretSantaGenerator(fileLocation))
| true |
f86fbccebff6f13a7cd2947b9802c65a0bfe9174 | abhi-manyu/Python | /general/data_Types/fundamentsl_data_types/Boolean_String.py | 776 | 4.125 | 4 | # in python boolean value true or false is mentioned in Camelcase like below
# if we will write first letter in small it will through error
# like 'c' in python True and False are treated as '1' and '0'
# for string formatting we can use either '\n' or '''something''' or """something"""
# this will exactly print our output in the way we want
value = True
print(value)
print(type(value))
print(True + True) # 1+1=2
print(True + False) # 1+0=1
print(30 * '-')
print('string')
print(30 * '-')
name = input('enter ur name\n')
print('hello{}, \nu r welcome'.format(name))
address = input('enter ur country\n')
# print('sorry, {} got you,\nwelcome to {}'.format(name,address))
print('''sorry i got u "{}"
welcome to "{}"'''.format(name, address))
| true |
223baf18d35b67e984141f5316f59cc1684161ae | abhi-manyu/Python | /general/data_Types/fundamentsl_data_types/DataType.py | 1,060 | 4.5625 | 5 | # for converting from any base type to binary type integer, we can take help of bin()
# from decimal to binary
number1 = 89756
print("the decimal number {} in binary form is : {}".format(number1, bin(number1)))
# from octal to binary
number = 0o756
print("the octal number {} in binary form is : {}".format(number, bin(number)))
# from hexadecimal to binary
print('the hexadecimal number : 0xcb45 in binary form : {}'.format(bin(0xcb45)))
print(60 * '-')
# to octal integer
# from decimal to octal
print('the decimal number 42345 to octal is {}'.format(oct(42345)))
# from binary to octal
print('the binary number : 101111011 in octal format is : {}'.format(oct(0b101111011)))
# from hexadecimal to octal number:
print('the hexadecimal number dca45b in octal is {}'.format(oct(0xdca45b)))
print(60 * '-')
# for hexadecimal format : there is one method : hex()
# from binary to hexadecimal number
print('the binary number 101011101001 in hexadecimal is : {}'.format(hex(0b101011101001)))
| true |
8b678b17342cf5292722d564d4266f9b1f4ad03c | wuzhisheng/Python | /oldboy/day2/格式化输出1.py | 643 | 4.1875 | 4 | #格式化输出
'''
应用:想要字符串的某些位置变成动态的
'''
#(1)
name=input("名字:")
sex=input("性别:")
job=int(input("身高:"))
hobby=input("爱好:")
#%占位符 s字符串 d数字 f浮点数
information='''
name%s
sex:%s
high:%d
hobby:%s
''' %(name,sex,job,hobby)
print(information)
#(3)
dict = {'name':'wu','sex':'man','high':'188','hobby':'haha'}
information='''
name%(name)s
sex:%(sex)s
high:%(high)s
hobby:%(hobby)s
''' % dict
print(information)
#(3)
s1='我是%s,爱好%s,输出2%%' % ('wu','篮球')
print (s1)
#for 会遍历字符串每个元素
num="wzs"
for i in num:
print(i) | false |
7b811b810d2dffd4b44c0c394d5ea9c2afa1566f | mrbramhall/Martyr2Projects | /Python/ReverseAString/reverse_string.py | 267 | 4.40625 | 4 | # returns the given string with chars reversed
def reverse_string(s):
reversed_s = ""
for char in s[::-1]:
reversed_s += char
return reversed_s
def main():
print reverse_string("This will be reversed.")
if __name__ == "__main__":
main()
| true |
c4b49a6818aa287192155a2e7840601bc867d790 | thewinterKnight/Python | /dsa/Trees/1.py | 2,815 | 4.1875 | 4 | # How is a complete binary search tree implemented?
import random
class QueueNode:
def __init__(self, tree_node=None, next=None):
self.tree_node = tree_node
self.next = next
def get_tree_node(self):
return self.tree_node
def get_next(self):
return self.next
def set_next(self, new_node):
self.next = new_node
class Queue(QueueNode):
def __init__(self, head=None, tail=None):
# super().__init__()
self.head = head
self.tail = tail
def Enqueue(self, tree_node):
new_node = QueueNode(tree_node)
if self.tail is None and self.head is None:
self.head = new_node
self.tail = new_node
else:
self.tail.set_next(new_node)
self.tail = self.tail.get_next()
def get_front(self):
return self.head
def Dequeue(self):
if self.head is None:
return None
pop_node = self.head
self.head = self.head.get_next()
if self.head is None:
self.tail = None
return pop_node.get_tree_node()
def is_empty(self):
if self.head is None and self.tail is None:
return True
else:
return False
class TreeNode:
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = left
self.right = right
def get_data(self):
return self.data
def get_left(self):
return self.left
def get_right(self):
return self.right
def set_left(self, left_node):
self.left = left_node
def set_right(self, right_node):
self.right = right_node
class BinaryTree(TreeNode):
def __init__(self, root=None):
# super().__init__()
self.root = root
def level_order_traversal(self):
if self.root is None:
print("Tree does not exist\n")
return
traversal_queue = Queue()
traversal_queue.Enqueue(self.root)
while traversal_queue.is_empty() is False:
tree_node = traversal_queue.Dequeue()
print(tree_node.get_data())
if tree_node.get_left() is not None:
traversal_queue.Enqueue(tree_node.get_left())
if tree_node.get_right() is not None:
traversal_queue.Enqueue(tree_node.get_right())
def insert_node(binary_tree, data, queue):
new_node = TreeNode(data)
if binary_tree.root is None:
binary_tree.root = new_node
else:
queue_front = queue.get_front() # queue_front is a tree node that was put in the queue
tree_node = queue_front.get_tree_node()
if tree_node.get_left() is None:
tree_node.set_left(new_node)
elif tree_node.get_right() is None:
tree_node.set_right(new_node)
if tree_node.get_left() is not None and tree_node.get_right() is not None:
queue.Dequeue()
queue.Enqueue(new_node)
if __name__ == "__main__":
binary_tree = BinaryTree()
queue = Queue()
arr = list(range(1, 12))
random.shuffle(arr)
print(arr)
print("Converting to a complete binary tree...\n\n")
for i in arr:
insert_node(binary_tree, i, queue)
binary_tree.level_order_traversal()
| true |
5b3143892982d21e5395ace35676fc444e106775 | thewinterKnight/Python | /dsa/Arrays/3(copy).py | 763 | 4.125 | 4 | # How do you find the largest and smallest number in an unsorted integer array?
import random
def create_array(m, M):
arr = list(range(m,M+1))
inpt = input('Enter element to repeat(Enter N/n to skip) : ')
while inpt not in ['n', 'N']:
if int(inpt) >=m and int(inpt) <= M:
arr.append(int(inpt))
else:
print('Number out of range !')
inpt = input('Enter element to repeat(Enter N/n to skip) : ')
random.shuffle(arr)
return arr
def findminMax(arr):
m = float("inf")
M = -float("inf")
for num in arr:
if num < m:
m = num
elif num > M:
M = num
print(m, M)
if __name__ == '__main__':
arr = create_array(7, 51)
findminMax(arr)
| true |
3fce9b3d436afd6ce04bc68d8af9cb049a352f70 | timeeehd/ComputerVision | /MeanShift/histogram.py | 871 | 4.125 | 4 | import cv2
def histogram(image):
"""
Does histogram equalization by changing to color scheme to BGR, then to YUV.
After doing the histogram equalization in the YUV color scheme, transform back to
BGR and then RGB. Output this image.
Hints have been used by looking at this link:
https://stackoverflow.com/questions/31998428/opencv-python-equalizehist-colored-image
Args:
image: image in RGB in the data folder.
Output:
Equalized image in RGB
"""
img = cv2.imread(f"./Data/{image}", cv2.IMREAD_COLOR)
img_yuv = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)
img_yuv[:,:,0] = cv2.equalizeHist(img_yuv[:,:,0])
# transform yuv to bgr
img_output = cv2.cvtColor(img_yuv, cv2.COLOR_YUV2BGR)
# transform bgr to rgb
img_output_rgb = cv2.cvtColor(img_output, cv2.COLOR_BGR2RGB)
return img_output_rgb
| true |
80d117082b4e1d295300097456ac11f0642bfa0f | harryhawthorne/linkedlist | /LinkedList.py | 2,494 | 4.125 | 4 | class LinkedList:
# Create list with empty 'head' node
def __init__(self):
self.head = None
class Node:
# Each node has a value and a reference to next node
def __init__(self, value, next=None):
self.value = value
self.next = next
def addFirst(e, L):
# New head, with old head as it's next value
L.head = Node(e, L.head)
def addLast(e, L):
# Iterate through the linked list until there is no 'next' node.
if L.head:
current_node = L.head
while 1:
if current_node.next is None:
# Append new node
current_node.next = Node(e)
break
current_node = current_node.next
else:
L.head = Node(e)
def removeFirst(L):
# New head is the old heads 'next' node.
if L.head:
L.head = L.head.next
def removeLast(L):
if L.head:
# Iterate through linked list until there is no 'next' node.
current_node = L.head
while 1:
# Keep track of previously explored node
prev_node = current_node
if current_node.next is None:
# Remove last node by removing previous nodes 'next' reference
prev_node.next = None
break
current_node = current_node.next
def getFirst(L):
if L.head:
# Return integer value of last node
return L.head.value
else:
# If nothing in list, return None.
return None
def getLast(L):
if L.head:
current_node = L.head
# Iterate through the list until at linked list's last node
while 1:
if current_node.next is None:
# Returns integer value of last node
return current_node.value
current_node = current_node.next
else:
# If nothing in list, return None.
return None
def showList(L):
# List of node objects to be printed
to_print = []
if L.head:
current_node = L.head
to_print.append(current_node)
# Iterate through linked list, appending each node to to_print list.
while current_node.next is not None:
to_print.append(current_node.next)
current_node = current_node.next
# Print linked list node values with "->" between each.
string = " -> ".join(str(x.value) for x in to_print)
# Print the linked list if it contains any elements
if string:
print(string)
| true |
778139f342ccf6376ae750efb0ce03c11fede9f4 | jasonschoenleber/Practice | /loops_practice.py | 2,481 | 4.1875 | 4 | '''Exercise Question 1: Print First 10 natural numbers using while loop
Expected output:
0
1
2
3
4
5
6
7
8
9
10'''
# i = 0
# while i <= 10:
# print(i)
# i += 1
'''Exercise Question 2: Print the following pattern
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5'''
# newlist = []
# i = 1
# while i <= 5:
# newlist.append(i)
# i += 1
# print(newlist)
'''Exercise Question 3: Accept number from user and calculate the sum of all number between 1 and given number
For example user given 10 so the output should be 55'''
# summed = 0
# number = int(input('Give me a number: '))
# for i in range(1, number + 1, 1):
# summed += i
# print(summed)
'''Exercise Question 4: Print multiplication table of given number
For example num = 2 so the output should be
2
4
6
8
10
12
14
16
18
20'''
# number = int(input('Give me a number: '))
# i = 0
# for i in range(1, 11,1):
# print(number * i)
# i += 1
'''Exercise Question 5: Given a list iterate it and display numbers which are divisible by 5 and if you find number greater than 150 stop the loop iteration
list1 = [12, 15, 32, 42, 55, 75, 122, 132, 150, 180, 200]
Expected output:
15
55
75
150'''
# given_list = [12, 15, 32, 42, 55, 75, 122, 132, 150, 180, 200]
# n = len(given_list)
# for i in given_list:
# if i % 5 == 0 and i < 151:
# print(i)
'''Exercise Question 6: Given a number count the total number of digits in a number
For example, the number is 75869, so the output should be 5.'''
# number = input('Give me a number: ')
# counting = len(number)
# print(counting)
'''Exercise Question 7: Print the following pattern using for loop
5 4 3 2 1
4 3 2 1
3 2 1
2 1
1'''
# given_list = [5,4,3,2,1]
# i = 0
# print(given_list)
# for i in given_list:
# given_list = given_list[1:]
# print(given_list)
'''Exercise Question 8: Reverse the following list using for loop
list1 = [10, 20, 30, 40, 50]
Expected output:
50
40
30
20
10'''
# given_list = [10,20,30,40,50]
# for i in reversed(given_list):
# print(i)
'''Exercise Question 9: Display -10 to -1 using for loop
Expected output:
-10
-9
-8
-7
-6
-5
-4
-3
-2
-1'''
# for i in reversed(range(1, 11)):
# print(i * -1)
'''Exercise Question 10: Display a message “Done” after successful execution of for loop
For example, the following loop will execute without any error.
for i in range(5):
print(i)
So the Expected output should be:
0
1
2
3
4
Done!'''
# for i in range(5):
# print(i)
# print('Done!')
| true |
a4468c3d084c9ffc245359449864a5340b229651 | levayb/first-Si-week | /setC/assignment.py | 899 | 4.375 | 4 | #
# 2018.11.22
'''
n computer science there is a recurring problem which is how to sort a list of numbers.
In this assignment you get a flowchart of a possible solution and based on that you need
to write the equivalent python script. This is a simple sorting algorithm that
repeatedly steps through the list to be sorted, compares each pair of adjacent items
and swaps them if they are in the wrong order.
Implement the algorithm described by the flowchart in Python!
Improve your solution:
Structure your code: separate some logic into functions.
Modify your program so that it asks the user to give the list of numbers.
Submit your python script file.
(Please note that the second step ('Improve your solution')
is the inherent part of the assignment, not an extra.)
sorting_assignment.png
Besides programming knowledge, this assignment improves your skills to conform to requirements.
'''
| true |
64d75038be610a7d571a6519f1c4d7fb147db43a | crantz007/Capstone-Lab1 | /venv/part3.2.py | 495 | 4.3125 | 4 | # Write a 'guess the number' game. The computer should 'think' of a random number within a certain range
import random
guess_number =2
user = int(input("Enter a number between 1 and 100: "))
number = random.randint(1,100)
while user < guess_number :
print("Too low")
user = int(input("Enter a number between 1 and 100: "))
if user > guess_number :
print("Too high")
user = int(input("Enter a number between 1 and 100: "))
else:
print("Guess Number!!!")
| true |
f8023e6311779b5f98ea5eec5add071d195d3b7a | endy-see/AlgorithmPython | /ZuoShen/32-ReverseStackUsingRecursive.py | 525 | 4.15625 | 4 | """
用递归反转一个栈
"""
def reverse_stack(stack):
if not stack:
return
i = get_and_remove_last_element(stack)
reverse_stack(stack)
stack.append(i)
def get_and_remove_last_element(stack):
result = stack.pop()
if not stack:
return result
else:
last = get_and_remove_last_element(stack)
stack.append(result)
return last
if __name__ == '__main__':
stack = [1, 2, 3, 4, 5]
reverse_stack(stack)
while stack:
print(stack.pop())
| true |
ca927def1d6d2260cc8bc282f6b80fa402344a36 | endy-see/AlgorithmPython | /SwordOffer/50-Add.py | 1,035 | 4.15625 | 4 | """
不用加减乘除做加法
题目:写一个函数,求两个整数之和,要求在函数体内不得使用+、-、*、/四则运算符号
思路:把二进制的加法用位运算来替代。
1.第一步不考虑进位,对每一位相加。0加0、1加1的结果都是0,0加1、1加0都是1.这个异或的结果一样
2.接着考虑第二位进位,对0加0、0加1、1加0而言,都不会产生进位,只有1加1时会向前产生一个进位
此时可以想象成两个数先做位与运算,然后再向左移动一步。只有两个数都是1的时候,位与得到的结果是1
3.把前两个步骤的结果相加。第三步相加的过程依然是重复前面两步,直到不产生进位位置
"""
# -*- coding:utf-8 -*-
class Solution:
def Add(self, num1, num2):
# write code here
while num2 != 0:
sum = num1 ^ num2
jin_wei = (num1 & num2) << 1
num1 = sum
num2 = jin_wei
return num1
obj = Solution()
print(obj.Add(25, 9)) | false |
e8853f5105820141ce34845e9807e4f5b1993f92 | bhamburg/CIS_626 | /Week4/exercise7_1.py | 1,057 | 4.1875 | 4 | # The Rectangle class
# Author: Brian Hamburg
import math
class Rectangle:
# Construct a rectangle object
def __init__(self, width = 1, height = 2):
self.width = width
self.height = height
def getPerimeter(self):
return 2 * (self.width + self.height)
def getArea(self):
return self.width * self.height
def getWidth(self):
self.width = width
def getHeight(self):
self.height = height
def main():
# create first rectangle
rectangle1 = Rectangle(4,40)
print("Rectangle 1")
print("Width:",rectangle1.width)
print("Height:",rectangle1.height)
print("Area:",rectangle1.getArea())
print("Perimeter:",rectangle1.getPerimeter())
print()
# create second rectangle
rectangle2 = Rectangle(3.5,35.7)
print("Rectangle 2")
print("Width:",rectangle2.width)
print("Height:",rectangle2.height)
print("Area:",rectangle2.getArea())
print("Perimeter:",rectangle2.getPerimeter())
main()
| true |
bef1092f580fa4f2017d863cc6dc238d7e4c4dcc | adhishp/Python-Projects | /flower.py | 424 | 4.125 | 4 | import turtle
def flower():
#create screen
window = turtle.Screen()
window.bgcolor("green")
#Create Petals using triangle
flwr = turtle.Turtle()
flwr.speed(0.1)
n=0
def leaf():
flwr.circle(50)
for n in range(1,100):
leaf()
flwr.right(n)
flwr.fillcolor("red")
n=n+1
flwr.backward(300)
window.exitonclick()
flower()
| true |
dc3e3f98da4851b6163bef1edff8338b4ffee40d | JosephEmmanuel/python_files | /miletokm.py | 572 | 4.4375 | 4 | # This is a program that can convert kilometers to miles and also miles to kilometers.
# First, choose your conversion, you can choose kilometer -> mile or mile -> kilometer.
#
# Author : Joseph Emmanuel
# Date : 18-April-2019
#
choice=input("enter k for kilometer to mile or m for mile to kilometer:")
if choice=="k":
k=float(input("please enter a number in kilometer:"))
m=k/1.609344
print(k,"kilometers = ",m," miles")
if choice=="m":
m=float(input("please enter a number in miles:"))
k=m*1.609344
print(m,"miles = ",k," kilometers")
| true |
787c11c22235b72d66cb95055cb3d12a67cb04fe | avi527/Data-Structure-Algorithms | /Array/array_rotation.py | 396 | 4.1875 | 4 | #Program for array rotation
def leftRotate(arr, d, n):
for rotate in range(d):
leftRotatebyOne(arr, n)
def leftRotatebyOne(arr,n):
temp = arr[0]
for shift in range(n-1):
arr[shift] = arr[shift+1]
arr[n-1] = temp
def printArray(size,arr):
for i in range(size):
print ("% d"% arr[i], end =" ")
arr = [1,2,3,4,5,6,7]
n = 7
d = 2
leftRotate(arr,d,n)
printArray(n,arr) | false |
f520175beb2c0bf42cc8ddd08573af0f9edc9f9d | YashrajG/PythonAssessment | /Problem3.py | 709 | 4.25 | 4 | import functools
import ast
listOfStrings = ast.literal_eval(input("Enter a list of strings in python format : "))
lexList = ast.literal_eval(input("Enter the lexical order of alphabets as a list of strings in python format : "))
def compareStrings(s1, s2):
l = len(s1) if len(s1) < len(s2) else len(s2)
for i in range(l):
if s1[i] != s2[i]:
return lexList.index(s1[i]) - lexList.index(s2[i])
return len(s1) - len(s2)
listOfStrings.sort(key=functools.cmp_to_key(compareStrings))
print(listOfStrings)
#Output
# Enter a list of strings in python format : ['car','rat','cat']
# Enter the lexical order of alphabets as a list of strings in python format : ['r','c','t','a']
# ['rat', 'car', 'cat']
| true |
02841e9145b5cb16eae7b15547be0bbecb3cd2b6 | vaidehinaik/PracticeSession | /ValidPalindrome.py | 547 | 4.125 | 4 | def isPalindrome(s):
if type(s) is not str:
return False
if s is None or s == '' or len(s) == 1:
return True
start = 0
end = len(s)-1
while end >= start:
if not s[start].isalpha():
start += 1
continue
if not s[end].isalpha():
end -= 1
continue
if s[start].lower() != s[end].lower():
return False
else:
start += 1
end -= 1
return True
print(isPalindrome("A man, a plan, a canal: Panama"))
| true |
f66ac88f4d7b94829c1e3997b243c5a363791a5e | Mayur-Debu/Pyhton_Basic_Program | /built_in_function.py | 591 | 4.15625 | 4 | # a=10
# b=20
# print(sum((a,b))) #This is a builtin function, ctrl+left click to access it in the builtin.py file
"""Function in python language"""
def largest(num1,num2,num3):
"""This is a largest of three function and works with 3 variables
******** Please donot manipulate *****************"""
if(num1>num2 & num1>num3):
return num1
elif(num2>num3 & num2>num1):
return num2
else:
return num3
print(largest(12,13,14))
print(largest.__doc__) #This statement prints the doctype of the function.....(if exists) else it prints NONE | true |
884cdd34bdd7131419ee995bab6ced8acbc824e1 | alfaroqueIslam/Sprint-Challenge--Algorithms | /recursive_count_th/count_th.py | 640 | 4.21875 | 4 | '''
Your function should take in a single parameter (a string `word`)
Your function should return a count of how many occurences of ***"th"*** occur within `word`. Case matters.
Your function must utilize recursion. It cannot contain any loops.
'''
def count_th(word, n=0, x=0):
if word == '':
return x
if word[n]+word[n+1] == 'th' and n < len(word) - 1:
x = x + 1
n = n + 1
print(x)
if n == len(word) - 1:
return x
return count_th(word,n,x)
n = n + 1
if n == len(word) - 1:
print(x)
return x
else:
return count_th(word,n,x)
| true |
08f1db90023d63454f60eeccddb88bb518ff7319 | pattons-OSU/CS362_InClassActivities | /Week_7/word_count.py | 876 | 4.3125 | 4 | #! python3
"""
Simeon Patton
Inclass activity Week 7
CS362 - OSU Spring 2021
Word Count-
1. Ask the user for a sentence and determine the number of
words in that sentence.
Example - “This is an activity”, Output - 4.
2. Write tests for the above specification using unittest and
pytest.
3. Document the outputs in a pdf - (screenshots of the output
from unittest and pytest)
"""
def user_input():
## Taking in user input and returning it for use
usr_input = input("\nPlease enter a sentence to count:\n")
return usr_input
def string_split(string):
## Breaking user input into separate items and then counting them
separate = string.split()
count = len(separate)
print(f"\nOutput - {count}\n")
return count
if __name__ == "__main__":
string = user_input()
string_split(string) | true |
dc971788da07e06d3aa8fd35fe63a93736ca5f30 | Hesbon5600/AndelaInterview | /password.py | 1,666 | 4.4375 | 4 |
# Python program to check validation of password
# Module of regular expression is used with search()
import re
valid = [] #Store the valid password(s)
#takes in a list of password(s) as a parameter
def password_validate(passwords):
#flag is true if the conditions are met
#Otherwise, flag is set to false
flag = True
i = 0
#Looping through the list to verify each password
while i < len(passwords):
#Length must be more than 6 chars but less than 12 chars
if (len(passwords[i])<6 or len(passwords[i]) > 12):
flag = False
#Password must have a lowercase letter
elif not re.search("[a-z]", passwords[i]):
flag = False
#Password must have an uppercase letter
elif not re.search("[A-Z]", passwords[i]):
flag = False
#Password must have a number
elif not re.search("[0-9]", passwords[i]):
flag = False
#Password must have one of the special characters [#@$]
elif not re.search("[#@$]", passwords[i]):
flag = False
#If a password meets all the above conditions,
#It's appended to the list 'valid'
else:
valid.append(passwords[i])
#increment 'i' and go to the next item in the passwords list (if any)
i = i + 1
if len(valid) > 0:
print(", ".join(valid))
flag = True
return flag
else:
flag = False
return flag
password = input("Enter Password: \n")
passwords = password.split(',')
passwords = list(passwords)
password_validate(passwords) | true |
cded199e96f9abe92e034f59d521d3e8f4d23405 | LuisAzabache/Aprendiendo | /Ejercicios_clase_11.py | 1,091 | 4.125 | 4 | #solucion de ejercicio 1
numero_1=float(input("Introduce el primer numero: "))
numero_2=float(input("Introduce el segundo numero: "))
def devuelve_max(n1,n2):
if n1>n2:
print(n1)
elif n2>n1:
print(n2)
else:
print("son iguales")
print("el numero mas alto es: ")
devuelve_max(numero_1, numero_2)
#solucion de ejercicio 2
nombre=(input("Introduce nombre: "))
direccion=(input("Introduce direccion: "))
telefono=(input("Introduce telefono: "))
midiccionario={"Nombre":nombre, "Direccion":direccion,"Telefono":telefono}
print("Los personales son: ")
print(midiccionario["Nombre"])
print(midiccionario["Direccion"])
print(midiccionario["Telefono"])
#solucion del tercer ejercicio:
num1=float(input("Registra el primer numero: "))
num2=float(input("Registra el segundo numero: "))
num3=float(input("Registra el tercer numero: "))
def media_aritmetica(n1, n2, n3):
media=(n1+n2+n3)/3
return(media)
print("La media aritmetica es: ")
print(media_aritmetica(num1,num2,num3)) | false |
259c3732813dacab8e8d38e7c5252621c6cd8a5b | devecis/learning | /Week 2/Week_2_Hard.py | 761 | 4.125 | 4 | #Determine if a word or phrase is an isogram.
#An isogram (also known as a "nonpattern word") is a word or phrase without a repeating letter, however spaces and hyphens are allowed to appear multiple times.
#Examples of isograms:
#lumberjacks
#background
#downstream
#six-year-old
#The word isograms, however, is not an isogram, because the s repeats.
def isogram(word):
fuck = []
for letter in word:
fuck.append(letter)
if fuck.count(letter) > 1:
print("Nah dawg that shit ain't no isogram")
else:
print("You're muthafuckin right it's an isogram")
def main():
word = input('Enter a word to see if it is a isogram: ').lower()
isogram(word)
if __name__ == '__main__':
main()
| true |
866d8320361cfe3746ae8fae54798d1e3031aa88 | devecis/learning | /dog_calc.py | 394 | 4.125 | 4 | # Ask for dogs name
# ask user for dogs age
# multiply age by 7
# return answer "Your dog, {name}, is {age} years old in human years."
name = input("what is your dogs name? ")
age = int(input("How old is your dog? "))
# print(f'Your dog, {name}, is {human} years old in human years.')
print(f"You dog {name}, is", age * 7, "in human years")
print(f"{name} can't spell your, because he sucks") | false |
fbd451ae7116eedee1d7f5b854e17946f459fd88 | devecis/learning | /Python_Workout/Exercise01/Exercise01.py | 1,372 | 4.5 | 4 | """
Write a function (guessing_game) that takes no arguments.
When run, the function chooses a random interger between 0 - 100 inclusive
Then asks the user to guess what number has been chosen
Each time the user enters a guess, the program indicates one of the following:
- Too High
- Too Low
- Just right
If the user guesses correctly, the program exits. Otherwises , the user is asked to try agian
The program exits after the user guess correctly
Give user 3 tries
"""
from os import system, name
from time import sleep
import random
def clear(): # Used to clear the screen after session
if name == 'nt':
_ = system('cls')
answer = random.randint(1, 100) #picking as number between 1 and 100
def guessing_game(): #the guessing game. The user input is in here instead of main because the user has to do it 3 times
for i in range(3):
user_guess = int(input("Guess a number between 1 - 100, you only get 3 tries. "))
if user_guess == answer:
print(f"Right! The answer is {user_guess}")
break
elif user_guess < answer:
print(f"Your guess of {user_guess} is too low!")
elif user_guess > answer:
print(f"Your guess of {user_guess} is too high!")
def main():
guessing_game()
sleep(2)
clear()
if __name__ == "__main__":
main() | true |
e4b66c127920b388f317a4d468d4696385bd1a86 | joshua-dubbeld/cp1404practicals | /prac_05/emails.py | 796 | 4.15625 | 4 | """
CP1404 Practical
Store names from email input in dictionary
"""
emails_dict = {}
email = input("Email: ")
while email != "":
email_alias = email.split('@')
name_list = email_alias[0].split('.')
name = ' '.join([word for word in name_list]).title()
choice = input("Is your name {}? (Y/n) ".format(name))
while choice.lower() not in "yn":
print("Invalid choice.")
choice = input("Is your name {}? (Y/n) ".format(name))
if choice.lower() == 'y':
emails_dict[email] = name
elif choice.lower() == 'n':
name = input("Name: ").title()
emails_dict[email] = name
else:
print("Something went wrong...")
email = input("Email: ")
print()
for word in emails_dict:
print("{} ({})".format(emails_dict[word], word))
| false |
0d55d71ecfdac435661283bc7a51eea9961605cd | dennismingming/hackerrank | /Grading Students.py | 2,777 | 4.3125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[3]:
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'gradingStudents' function below.
#
# The function is expected to return an INTEGER_ARRAY.
# The function accepts INTEGER_ARRAY grades as parameter.
#
def gradingStudents(grades):
# Write your code here
result = grades
for i in range(len(grades)):
if grades[i] > 35 and 5 - grades[i]%5 < 3:
result[i] = grades[i] + (5 - grades[i] % 5)
else:
result[i] = grades[i]
tuple(result)
return result
# In[5]:
grades = [73, 67, 38, 33]
gradingStudents(grades)
# HackerLand University has the following grading policy:
#
# Every student receives a grade in the inclusive range from 0 to 100.
# Any grade less than 40 is a failing grade.
# Sam is a professor at the university and likes to round each student's grade according to these rules:
#
# If the difference between the grade and the next multiple of 5 is less than 3, round grade up to the next multiple of 5.
# If the value of grade is less than 38, no rounding occurs as the result will still be a failing grade.
# For example, grade = 84 will be rounded to 85 but grade = 29 will not be rounded because the rounding would result in a number that is less than 40.
#
# Given the initial value of grade for each of Sam's n students, write code to automate the rounding process.
#
# Function Description
#
# Complete the function gradingStudents in the editor below. It should return an integer array consisting of rounded grades.
#
# gradingStudents has the following parameter(s):
#
# - grades: an array of integers representing grades before rounding
#
# Input Format
#
# The first line contains a single integer, n , the number of students.
# Each line i of the n subsequent lines contains a single integer,grades[i] , denoting student i's grade.
#
# Constraints
#
# - $ 1 \leq n \leq 60 $
# - $ 0 \leq grade[i] \leq 100$
#
# Output Format
#
# For each grades[i], print the rounded grade on a new line.
#
# Sample Input 0
#
# 4
# 73
# 67
# 38
# 33
#
# Sample Output 0
#
# 75
# 67
# 40
# 33
#
# Explanation 0
#
# <img src = https://s3.amazonaws.com/hr-challenge-images/0/1484768684-54439977a1-curving2.png>
#
# Student 1 received a 73, and the next multiple of 5 from 73 is 75. Since , the student's grade is rounded to .
# Student received a , and the next multiple of from is . Since , the grade will not be modified and the student's final grade is .
# Student received a , and the next multiple of from is . Since , the student's grade will be rounded to .
# Student received a grade below , so the grade will not be modified and the student's final grade is .
# In[ ]:
| true |
363432dbaff3621786098f0b3fcef389f23fa00e | jokercell-lab/biotest-one | /pizza.py | 472 | 4.15625 | 4 | print("Welcom to Pizza order system ")
size = input("what size pizza do you want? S, M, or L ")
add_pepper = input("do you want add pepper? Y or N ")
extra_cheese = input("do you want extra cheese? Y or N ")
price = 0
if size == "S":
price += 15
elif size == "M":
price += 20
else:
price += 25
if add_pepper == "Y":
if size == "S":
price += 2
else:
price += 3
if extra_cheese == "Y":
price += 1
print(f"your price is :${price}") | true |
e3ec8a59883476454b946426e4fdc52ec19c4fc6 | nodejsera/python-snippets | /lists.py | 1,675 | 4.46875 | 4 | #Creating a List
list1 = [ "r" , "a" , "j" , "a" , "t" ]
list2 = [1,2,3,4,5]
list3 = [1 , "a" , 3 , "j", 3]
#Accessing values in a List
print("Printing the whole list1 ==>", list1)
print("Printing element 2 of list 3 ==>" , list3[1])
print("Printing the 1 element from the right of list 2 ==>", list2[-1])
print("Printint all the elements except 1st of list 1 ==>" , list1[1:])
print("Printing the middle 3 values of list 2 ==> " , list2[1:4])
#Updating List elements
print("Value at list1[2] is ==> " , list1[2])
list1[2]= "newvalue"
print("New Value at list1[2] is ==> " , list1[2])
#Deleting List elements
print("The elements of list2 are ==> " , list2)
del list2[2] #deleting the 3rd element of list 2 using 'del' keyword
print("Now the elements of list2 are ==>" , list2)
print("The new value at list2[2] is ==>" , list2[2])
#Basic List Operations
print("Length of list1 is ==> " , len(list1))
print("Let's concatenate list1 and list2 ==>", list1+list2) #Conctenation is performed using '+' operator
P = ['5']
print("Let's perform repetition operation on P", P * 5)
print("Let's check membership operation on 3 in list2==>" , 3 in list2 );
print("");
#Built-in functions in LISTS
T = [ 2,4,6,7,9,4]
print("The total length of list elements using len method == >" , len(T))
print("The max element of the list elements using max method == >" , max(T))
print("the min element of the list elements using min method == >", min(T))
tuple = ( 2 , 4 , 6 )
s = "Rajatshram"
print("We have a tuple T ==>" , tuple)
lista = list(tuple);
listb = list(s);
print("Converting a tuple into list == > " , lista)
print("Converting a string into list == > " , listb)
| false |
bcc391da8d80afe3e9a3d4a71dcc796030823cf7 | diegoshakan/algorithms-python | /Exe4.9.py | 646 | 4.15625 | 4 | '''Dados 10 números digitados pelo usuário, construa um algoritmo para mostrar a
média apenas dos números menores que zero.'''
cont = 0
soma = 0
menor = 0
while cont < 10:
num = int(input('Digite um número: '))#Recebe um número, acontecerá 10 vezes
if num < 0: #se o número for menor que zero ele entra em um contador
menor = menor + 1 #este é o contador para saber qnts números negativos existem.
soma = soma + num #vai somar apenas os números negativos para fazer sua média.
cont = cont + 1 #contador para dar fim ao processo
print(soma / menor) #soma dos números negativos, dividido pelas vezes que
| false |
11bd63b669e0d3bfac947f11407bfdbb014accb0 | anirban-1009/lpthw3 | /calci.py | 595 | 4.125 | 4 | print("Enter the first number:")
a = float(input('>'))
print("Enter the second number:")
b= float(input('>'))
print("Enter the operation to be donefrom the range of (+, -, *, /, %, remainder):")
c= input('>')
if (c=='+'):
d = a+b
print("The sum is:",d)
elif (c=='-'):
d = a-b
print("The difference is:",d)
elif (c=='*'):
d = a*b
print("The product is:",d)
elif (c=="/"):
d = a/b
print("The Quoteint is:",d)
elif (c=="remainder"):
print("the remainder is:",d)
elif (c=="%"):
d= a/b*100
print("The percentage is:",d,"%")
else:
print("the function is unknown") | true |
45581a5baae44e05f4a37181dea11408cbaccf5e | pvish2/pythonBasics | /src/intro/python_intro.py | 1,972 | 4.125 | 4 | """
Python is a strongly-typed, dynamic interpreted language.
- Python DOES DO type checking! But it does it at runtime
- Python translates the code at runtime: it is an INTERPRETED language
"""
foo = "5" + 4 # Will raise an error
def bar(num):
if num > 3:
print(num + 2)
else:
print("5" + 4)
bar(4) # Life is good
bar(2) # Life is hell
# For reference, read:
# https://hackernoon.com/i-finally-understand-static-vs-dynamic-typing-and-you-will-too-ad0c2bd0acc7
"""
Duck typing: behaviour is more important than type
"""
class Duck:
def quack(self):
return 'Quack!'
class CrazyGoat:
def quack(self):
return 'Quack!'
class Dog:
def bark(self):
return 'Bau!'
class DuckRecogniser:
def check_duck(self, animal):
try:
if animal.quack() == 'Quack!':
print('Yes, it is a duck')
except AttributeError:
print('It is not a duck!')
duck = Duck()
crazy_goat = CrazyGoat()
dog = Dog()
dr = DuckRecogniser()
dr.check_duck(duck)
dr.check_duck(crazy_goat)
dr.check_duck(dog)
# This has deeper repercussions on OOP. Can read for further reference:
# https://hackernoon.com/python-duck-typing-or-automatic-interfaces-73988ec9037f
# For a detailed discussion on EAFP, please read:
# https://jeffknupp.com/blog/2013/02/06/write-cleaner-python-use-exceptions/
"""
Zoom on Python variables
"""
a = 5
b = a # variable 'b' gets the value of 'a'?
b = b + 5
print(a)
print(b) # All good so far, a=5 and b=10
w = [1, 2, 3]
z = w # variable 'bz gets the value of 'w'?
w.append(4)
print(w)
print(z) # What???
def simple_function(var_one, var_two):
var_one = var_one + 4
var_two = var_two + 5
simple_function(a, b)
print(a)
print(b) # All good so far, a=5 and b=10
def another_simple_function(var_one, var_two):
var_one.append(5)
var_two.append(6)
another_simple_function(w, z)
print(w)
print(z) # What??? | true |
c6aa8809344a9a1f91276908dfc9d6ff0aa91cef | samishken/Python-basics | /SequenceTypes/tupletype.py | 665 | 4.34375 | 4 | """
Tuple cannot be modified like a list.
We can't use the following methods in Tuple
append, extend, insert, remove, clear
"""
tpl=(40, 50, 50, 'xyz')
print(tpl)
tpl=(40,)
# with comma its considered as tuple
print(type(tpl))
tpl=(40)
# without comma its considered as integer
print(type(tpl))
tpl=(40, 50, 40, 'xyz')
print(tpl) # print all elements in the tuple
print(tpl[3]) # give me the element that's is the third index
print(tpl*3) # multiply the tuple 3 times
print(tpl.count(40)) # how many 40 inside a tuple
print(tpl.index('xyz')) # what's the index number of that element
lst=[67, 54, 'xyz']
print(type(lst))
tpl1=tuple(lst)
print(type(tpl1))
| true |
f0b8756a8082e0b70af32de7cd07cdefe16e46f0 | samishken/Python-basics | /DataTypes/dictionaryType.py | 337 | 4.28125 | 4 | dict1={1:"John", 2:"Bob", 3:"Bill"}
#keys = 1,2,2
#values of keys = John, Bob, Bill
print(dict1)
print(dict1.values())
print(dict1.items())
#list only keys
k=dict1.keys()
for i in k:print(i)
# print only values
v=dict1.values()
for i in v:print(i)
#pass key
print(dict1[3])
#Delete
# delete one of the keys
del dict1[3]
print(dict1) | false |
a3125d328dc5f2aa8996a612ef39440afd0fe249 | chrisjdavie/Sorting | /InsertionSortPart1/src/FirstGo.py | 1,854 | 4.46875 | 4 | #!/bin/python
'''
Solving the hackerrank Insertion Sort Part 2 puzzle.
https://www.hackerrank.com/challenges/insertionsort2
----------------------
Sorting
One common task for computers is to sort data. For example, people might want to see all their files on a computer sorted by size. Since sorting is a simple problem with many different possible solutions, it is often used to introduce the study of algorithms.
Insertion Sort
These challenges will cover Insertion Sort, a simple and intuitive sorting algorithm. We will first start with an already sorted list.
Insert element into sorted list
Given a sorted list with an unsorted number e in the rightmost cell, can you write some simple code to insert e into the array so that it remains sorted?
Print the array every time a value is shifted in the array until the array is fully sorted. The goal of this challenge is to follow the correct order of insertion sort.
Guideline: You can copy the value of e to a variable and consider its cell "empty". Since this leaves an extra cell empty on the right, you can shift everything over until V can be inserted. This will create a duplicate of each value, but when you reach the right spot, you can replace it with e.
Input Format
There will be two lines of input:
Size - the size of the array
Arr - the unsorted array of integers
Output Format
On each line, output the entire array every time an item is shifted in it.
----------------------
Created on 24 Jan 2016
@author: chris
'''
def insertionSort(ar):
e = ar[-1]
for i in range(1,len(ar)):
ar[-i] = ar[-i-1]
if ar[-i] < e:
ar[-i] = e
break
for a in ar: print a,
print
else:
ar[0] = e
for a in ar: print a,
m = input()
ar = [int(i) for i in raw_input().strip().split()]
insertionSort(ar) | true |
2f9fa0b4c20b6423090c296d9fddc3ac86ba2d51 | leonardo-lorenzon/coursera_courses | /data_structures_and_algorithms/fibonacci.py | 265 | 4.1875 | 4 | # Uses python3
def fibonacci(n):
n1 = 0
n2 = 1
if n == 0:
last_fibonacci = 0
else:
last_fibonacci = 1
i = 2
while i <= n:
last_fibonacci = n2 + n1
n1 = n2
n2 = last_fibonacci
i += 1
return last_fibonacci
n = int(input())
print(fibonacci(n)) | false |
8d78fd1a2820bfd7bcf4dfb867b452dd3806be22 | whugue/dsp | /python/q8_parsing.py | 1,374 | 4.375 | 4 | """
#The football.csv file contains the results from the English Premier League.
# The columns labeled Goals and Goals Allowed contain the total number of
# goals scored for and against each team in that season (so Arsenal scored 79 goals
# against opponents, and had 36 goals scored against them). Write a program to read the file,
# then print the name of the team with the smallest difference in for and against goals.
# The below skeleton is optional. You can use it or you can write the script with an approach of your choice.
"""
#Read In CSV Data as a Nested List
import csv
def read_data(data):
return list(csv.reader(open(data)))
football=read_data("football.csv")
#Compute the difference between G and GA for each team. Return a dict with the team name as key & diff as value
def calc_score_diff(parsed_data):
d={}
for i in range(1,len(parsed_data)): #start at index 1 to skip over variable names :)
d[parsed_data[i][0]]=abs(float(parsed_data[i][5])-float(parsed_data[i][6]))
return d
difference=calc_score_diff(football)
#Return the Team Name (dictionary key) with the minimum difference between G and GA
def get_team(d):
min_value=1000
for key in d:
if d[key] < min_value:
min_value_team=key
min_value=d[key]
return min_value_team
#Print Team Name
print get_team(difference) | true |
03dcce3fe232235610d92ddff11de3fa9f634dc0 | addovej-suff/python_alg_gb | /lesson_1/task_1.py | 529 | 4.21875 | 4 | # Найти сумму и произведение цифр трехзначного числа, которое вводит пользователь.
# Блок-схема: https://drive.google.com/open?id=1Mb3nxW5B_Xbh2wN7RyawK_5kkR8pPdB6
n = int(input('Введите трехзначное число (100-999): '))
first = n // 100
second = n % 100 // 10
third = n % 10
print(f'Сумма цифр числа: {first + second + third}')
print(f'Произведение цифр числа: {first * second * third}')
| false |
ae859af5ca39aff083075b336cf4a763f1448a3c | nisbweb/NISBXtreme-2020 | /Question 2/solution.py | 699 | 4.1875 | 4 |
# Fast fibonacci algorithm
# You can read up on more of the math behind this here:
# http://en.wikipedia.org/wiki/Fibonacci_number#Matrix_form
def fibonacci(n):
v1, v2, v3 = 1, 1, 0
for rec in bin(n)[3:]:
calc = v2*v2
v1, v2, v3 = v1*v1+calc, (v1+v3)*v2, calc+v3*v3
if rec=='1':
v1, v2, v3 = v1+v2, v1, v2
return v2
# Function to generate the sum of N fibonacci numbers
# Sum(F(n)) = F(n+2) -1
# You can get more information on the above from here
# https://en.wikipedia.org/wiki/Fibonacci_number#Combinatorial_identities
def fibonacciSummation(n):
return fibonacci(n+2)-1
if __name__ == "__main__":
n = int(input())
print(fibonacciSummation(n)) | false |
68e9220e68f5e0093d75b37d6c302f8e11269bff | seismatica/PCC | /10/8.py | 519 | 4.15625 | 4 | # Read files containing cats and dogs' name, and print them out. If file does not exist, print error
def print_file(filename):
try:
open(filename)
except FileNotFoundError:
print(filename + " not found.")
else:
with open(filename) as file_object:
content = file_object.read()
print(filename + ": ")
print(content)
def main():
filename_list = ["cats.txt", "dogs.txt"]
for filename in filename_list:
print_file(filename)
main() | true |
fd0d7a21caabda81f0b6e52e5a410151829effab | shashwat-dash/python-task-1 | /program1.py | 513 | 4.28125 | 4 | #1.Create an inner function to calculate the addition in the following way
# Create an outer function that will accept two parameters ‘a’ and ‘b’
# Create an inner function inside an outer function that will calculate the addition of ‘a’ and ‘b’
# At last, an outer function will add 5 into addition and return it
def outerFun(a, b):
square = a**2
def innerFun(a,b):
return a+b
add = innerFun(a, b)
return add+5
result = outerFun(5, 10)
print(result) | true |
e301c255841d2ac13165d915120846e4f7fa9785 | a-yev/python_practice | /Pandas exercises/DataFrame/23. Rename columns of a given DataFrame.py | 429 | 4.625 | 5 | # Write a Pandas program to rename columns of a given DataFrame.
# start
# import modules
import pandas as pd
d = {'col1': [1, 2, 3], 'col2': [4, 5, 6], 'col3': [7, 8, 9]}
df = pd.DataFrame(data=d)
print(("Original DataFrame") + str(df))
df.columns = ['Column1', 'Column2', 'Column3']
df = df.rename(columns={'col1': 'Column1', 'col2': 'Column2', 'col3': 'Column3'})
print(("New DataFrame after renaming columns:") + str(df))
| true |
70a40086889005605c8a4f45378ab0a1d55784ca | a-yev/python_practice | /Pandas exercises/DataSeries/19. Frequency counts of unique value of dataseries.py | 412 | 4.125 | 4 | # Write a Pandas program to calculate the frequency counts of each unique value of a given series.
# start
# import modules
import pandas as pd
import numpy as np
num_series = pd.Series(np.take(list('098712347890134587613'), np.random.randint(8, size=32)))
print("Original Series:")
print(num_series)
print("Frequency of each unique value of the said series.")
result = num_series.value_counts()
print(result)
| true |
a7deb373dc2c5650f9d1c0995224f1fb2a21509d | JeandsGomes/POO | /Multithreading/thread.py | 1,818 | 4.375 | 4 |
'''
Tread
* Executar várias threads é similar a executar prograas ao mesmo tempo;
* Entretanto existem alguns beneficios de se utilizar threads;
* Multiplas threads em um processo compartilham o mesmo espaço de dados;
* Dessa forma, ela podem compartilhar informações e se comunicar mais facilmente;
* Threads são usualmente chamados de processos-leves, ou seja, elas possuem um menor custo
computacional que um processo.
* Uma thread possui um inicio, uma sequência de execuções e uma conclusão;
* Uma thread pode:
* Ser interrompida;
* Ser colocada em espera.
'''
'''
O módulo threading
* tun() - O método é o ponto de partida para execução de uma thread;
* start() - o método start() inicia a thread chmado o método run();
* join() - o método join() espera a thread terminar;
* isAlive() - esse método verifica se a thread ainda está em execução;
* getName() - retorna o nome da thread.
* setName() - atribui um nome á thread.
* threading.activeCount() - retorna a quantidade de threads ativas.
* threading.enumerate() - retorna uma lista com todas as threads executando
atualmente.
'''
import threading
import time
class myThread(threading.Thread):
def __init__(self,nome,contador,delay):
threading.Thread.__init__(self)
self.nome = nome
self.contador = contador
self.delay = delay
#self.sinc = sinc
def run(self):
print("Iniciando" + self.nome)
#self.sinc.acquire()
print_time(self.nome, self.contador, self.delay)
#self.sinc.release()
print("Finalizando "+ self.nome)
def print_time(threadName, contador, delay):
while contador:
time.sleep(delay)
print("{} - {}: {}".format(15-contador,threadName, time.ctime(time.time())))
contador -= 1 | false |
45f5225c6c82bfeff1f4fc627ce755cd1ca551ed | jmuckian/EulerProjectPy | /Problem9.py | 605 | 4.21875 | 4 | """
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a2 + b2 = c2
For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
ANSWER: 31875000
"""
import math
def pythagorean(a, b):
c = math.sqrt(pow(a, 2) + pow(b, 2))
return c
a = 3
b = 4
c = pythagorean(a, b)
while a + b + c < 1001:
while a + b + c < 1001:
if a + b + c == 1000:
print a, b, c, a * b * c
b += 1
c = pythagorean(a, b)
a += 1
b = a + 1
c = pythagorean(a, b)
| false |
0303082edd88c36cd7a2833cb2c98bf69a845967 | Marco1704/mundo-python | /Mundo_1/ex032.py | 347 | 4.375 | 4 | from datetime import date
year = int(input('Enter the Year? or enter 0 to analyse the current one? '))
if year == 0:
year = date.today().year #grabs the value of the current year on the machine.Breakbreak
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
print(f'{year} is a leap year')
else:
print(f'{year} is not a leap year') | false |
6794c4bccbd2c59e647c065a84be453552072fa7 | Marco1704/mundo-python | /Mundo_2/ex059.py | 1,089 | 4.25 | 4 | from time import sleep
first = int(input('Enter the first value: '))
second = int(input('Enter the second value: '))
option = 0
while option != 5:
print(''' [1] Sum the values
[2] Multiple the values
[3] Higher value
[4] Enter new values
[5] Exit
''')
option = int(input('Enter your option: '))
if option == 1:
s = first + second
sleep(1)
print(f'\nThe Sum of the values is {s}')
elif option == 2:
m = first * second
sleep(1)
print(f'The product of the values is {m}')
elif option == 3:
if first > second:
sleep(1)
print(f'{first} is the higher value')
else:
sleep(1)
print(f'{second} is the higher value')
elif option == 4:
first = int(input('Enter the first new value: '))
second = int(input('Enter the second new value: '))
elif option == 5:
print('Exiting....')
sleep(1)
else:
print('\nInvalid option, Try again!')
print('-=-' *20)
print('End of the program, see you soon!') | true |
866d9d6e5db26afed69f99cea162989395bec9dc | Marco1704/mundo-python | /Mundo_3/ex077.py | 342 | 4.125 | 4 | words = ('learn', 'programming', 'language', 'python', 'course', 'free', 'study', 'practice',
'work', 'market', 'programmer', 'future')
vowels = ('a','e','i','o','u')
for w in words:
print(f'\nIn the word {w.upper()} we have', end=' ')
for letter in w:
if letter.lower() in vowels:
print(letter, end=' ')
| false |
7d903539e71cd9e1d5d17930178038222df41e77 | Marco1704/mundo-python | /Mundo_2/ex042.py | 590 | 4.125 | 4 | print('-=-' * 25)
print('Analyse the line segments values and indicate if they can form a triangle ')
print('-=-' * 25)
a = float(input('Enter the value of the first segment: '))
b = float(input('Enter the value of the second segment: '))
c = float(input('Enter the value of the third segment: '))
if a < b + c and b < a + c and c < a + b:
print('The segments can form a triangle', end='')
if a == b == c:
print(" equilateral")
elif a == b and a != c:
print(" isosceles")
else:
print(" scalene")
else:
print('The segments CANNOT form a triangle') | true |
b2a0d6e675f90f6194f5d8e1b0e51ab9cf9601f0 | Marco1704/mundo-python | /Mundo_2/ex044.py | 979 | 4.1875 | 4 | purchase = float(input('What is the total of the purchase? £'))
option = int(input('''Choose between the following payment options
[1] Cash - Full payment
[2] Card - Full payment
[3] Card - 2x
[4] Card - 3x plus
Enter you option? '''))
if option == 1:
payment = purchase - (purchase * .10)
print(f'The total with 10% of discount will be £{payment:.2f}')
elif option == 2:
payment = purchase - (purchase *.05)
print(f'The total with 5% of discount will be £{payment:.2f}')
elif option == 3:
payment = purchase
installment = purchase / 2
print(f'Your total will be £{payment:.2f} paid in 2 x of £{installment:.2f}')
elif option == 4:
cardpay = int(input('How many times you want to split the payments? '))
payment = purchase + (purchase * .20)
installment = payment / cardpay
print(f'Your purchase of £{purchase:.2f} will be split in {cardpay}x of £{installment:.2f} \nThe purchase total with interest will be £{payment:.2f}')
| true |
5f7a7e5279cab09dc97c4fd089d6948cd4631404 | TrishaAndalene/mySchoolProject | /Learning step/Basic/tebakangka.py | 349 | 4.125 | 4 | angkaTersimpan = 23
angkaDitebak = int(input("Masukkan Angkanya :"))
while angkaDitebak != angkaTersimpan :
if angkaDitebak > angkaTersimpan :
print("Terlalu besar")
elif angkaDitebak < angkaTersimpan :
print("Terlalu kecil")
angkaDitebak = int(input("Masukkan Angkanya :"))
if angkaDitebak == angkaTersimpan :
print("Selamat,Anda benar !") | false |
e9bb5f8360a93ec0b630adc6a08846b57876062a | Hussain-007/automation_l2 | /59.py | 1,359 | 4.34375 | 4 | '''59. Create file called "stringop.py" which has following functions
i) functions to sort numbers( Use loops for sorting, do not use built in function)
ii) function to search given element through binary search method.
( Refer to net for the Binary search algorithm)
iii) function to reverse the given string
Write new program in file strpackage.py such that you import functions of file "stringop.py" to your new program
'''
#stringop.py
def list_sort(arr):
for i in range(len(arr)-1):
for j in range(len(arr)-1):
if arr[j] > arr[j+1]:
temp = arr[j]
arr[j] = arr[j+1]
arr[j+1] = temp
print("Sorted:", arr)
def binarySearch(list1, item):
list1.sort()
first = 0
last = len(list1)-1
found = False
while first<=last and not found:
midpoint = (first+last)/2
if list1[midpoint] == item:
found = True
return found
else:
if item < list1[midpoint]:
last = midpoint-1
else:
first = midpoint+1
return found
def list_rev(l):
print(l.reverse())
print("reversed:", l)
list_sort([23,81,42,51,31])
print("binarySearch([23,81,42,51,31]):", binarySearch([23,81,42,51,31]))
| true |
360068d9f541f5f21e4b57e0c3551b325fb0bc7e | Hussain-007/automation_l2 | /23.py | 283 | 4.5625 | 5 | __doc__ = '''
Find the area of Circle given that radius of a circle.
( Use pi value from Math module)
'''
import math
PI = math.pi
radius = int(input("Enter the Radius Of the Circle: "))
print("Area Of Circle: {:.02f}".format(PI*radius*radius))
if __name__ == '__main__':
pass | true |
0b5f57bd08daa03a68071ec2dfca5bbd8b74592f | Hussain-007/automation_l2 | /45.py | 528 | 4.3125 | 4 | '''45. Write a program to check given string is Palindrome or not. ( Use function Concepts and Required keyword, Default parameter concepts)
That is reverse the given string and check whether it is same as original string, if so then it is palindrome.
Example : String = "Malayalam" reverse string = "Malayalam" hence given string is palindrome.
'''
def isPal(s):
if s == s[::-1]:
print(s,"is a palindrome")
else:
print(s,"is NOT a palindrome")
s = input("enter atring")
isPal(s) | true |
25fd82f6caa174dc7acd72080b0de31e092a6b94 | Hussain-007/automation_l2 | /21.py | 816 | 4.59375 | 5 | __doc__ = '''
Using the built in functions on Numbers perform following operations
a) Round of the given floating point number
example : n=0.543 then round it next decimal number , i.e n=1.0
Use round() function
b) Find out the square root of a given number. ( use sqrt(x) function)
c) Generate random number between 0, and 1 ( use random() function)
d) Generate random number between 10 and 500. ( use uniform() function)
e) Explore all Math and Random module functions on a given number/ List.
( Refer to tutorial for Math & Random functions list)
'''
import math
import random
n=0.543
print(round(n))
print(math.sqrt(4))
result = random.random()
print(result)
result = random.uniform(10,500)
print(result)
if __name__ == '__main__':
pass | true |
0942f7f18432c00a2b5b9cd71189fc57cf64859a | Hussain-007/automation_l2 | /43.py | 479 | 4.25 | 4 | '''43. Write a program to search given element from the list. Use your own function to search an element from list.
Note: Function should receive variable length arguments and search each of these arguments present in the list.
'''
def findelement(list1,a):
if a in list1:
print("Element is Present")
else:
print("Element is absent")
list1 = input("Enter elements of list ")
a= input("Enter element to be searched")
findelement(list1,a) | true |
55a570bf920cdee10c66062d0de137a606d8332d | Hussain-007/automation_l2 | /32.py | 1,755 | 4.5625 | 5 | '''32.Write a program to perform following operations on List.
Create 3 lists List1,List2 and List3
a. Find the length of each list and print(it
b. Find the maximum and minimum element of each list
c. Compare each list and determine which list is biggest & which list is smallest.
d. Delete first and last element of each list and print(list contents.'''
list1=[1,2,3,4,5,6,7]
list2=['a','b','c','d','e']
list3=['abc','def','edd']
print(list1)
print(list2)
print(list3)
print("Length of list1=",len(list1))
print("Length of list2=",len(list2))
print("Length of list3=",len(list3))
print("Max of list1=",max(list1))
print("Min of list1=",min(list1))
print("Max of list2=",max(list2))
print("Min of list2=",min(list2))
print("Max of list3=",max(list3))
print("Min of list3=",min(list3))
if list1>list2 and list1>list3:
print("\nlist1 is the biggest",list1)
elif list2>list1 and list2>list3:
print("\nlist2 is the biggest",list2)
else:
print("\nlist3 is the biggest",list3)
if list1<list2 and list1<list3:
print("\nlist1 is the smallest",list1)
elif list2<list1 and list2<list3:
print("\nlist2 is the smallest",list2)
else:
print("\nlist3 is the smallest",list3)
print("\nList1 before removing 1st and last element using Pop method")
print(list1)
print("\nList1 after removing 1st and last element using pop method")
list1.pop(0);list1.pop(-1)
print(list1)
print("List2 before removing 1st and last element using Pop method")
print(list2)
print("List2 after removing 1st and last element using pop method")
list2.pop(0);list2.pop(-1)
print(list2)
print("List3 before removing 1st and last element using Pop method")
print(list3)
print("List3 after removing 1st and last element using pop method")
list3.pop(0);list3.pop(-1)
print(list3)
| true |
2eccf0908c13745681327ba600d316d077db5302 | weiranfu/cs61a | /functions/processing_linked_list/remove_certain_values.py | 1,343 | 4.375 | 4 | def remove_all(link , value):
"""Remove all the nodes containing value. Assume there exists some
nodes to be removed and the first element is never removed.
>>> l1 = Link(0, Link(2, Link(2, Link(3, Link(1, Link(2, Link(3)))))))
>>> print(l1)
<0 2 2 3 1 2 3>
>>> remove_all(l1, 2)
>>> print(l1)
<0 3 1 3>
>>> remove_all(l1, 3)
>>> print(l1)
<0 1>
"""
"*** YOUR CODE HERE ***"
if link is not Link.empty:
if link.rest is not Link.empty:
while link.first == value:
link.first = link.second
link.rest = link.rest.rest
remove_all(link.rest, value)
else:
if link.first == value:
# Here we will encounter an problem: if the list.first of the last linked list == value, we cannot get rid of the last linked list.
# We cannot change the link.rest of last link to be Link.empty.
# So we need to detect the link.first of the next link whether is value or not.
"*** YOUR CODE HERE ***"
# Official answer:
if link.rest is not Link.empty:
if link.rest.first == value: # if the last
link.rest = link.rest.rest
remove_all(link, value)
else:
remove_all(link.rest, value)
| true |
45ea965ce460f335ed08f39c9847c0de44829b8f | weiranfu/cs61a | /functions/generator/iterate_even_numbers.py | 475 | 4.5625 | 5 | def evens(start, end):
"""A generator function that returns even numbers between start and end.
>>> list(evens(2, 10))
[2, 4, 6, 8]
>>> list(evens(1, 10))
[2, 4, 6, 8]
>>> t = evens(2, 10)
>>> next(t)
2
>>> next(t)
4
"""
even = start + (start % 2) # This expressing doesn't need to decide whether start is even or odd. (start % 2) is either 1 or 0.
while even < end:
yield even
even += 2
| true |
80b6b122af40cd5ed2dfc45cb55d9c022a93eb5d | weiranfu/cs61a | /functions/processing_tree/tree/long_paths.py | 1,937 | 4.125 | 4 | def long_paths(tree, n):
"""Return a list of all paths in tree with length at least n.
The path is represented as a linked list of node values that starts from root and ends at leaf.
The length of a path is the number of edges in the path (i.e. one less than the number of nodes in the path).
Paths are listed in order from left to right.
>>> t = Tree(3, [Tree(4), Tree(4), Tree(5)])
>>> left = Tree(1, [Tree(2), t])
>>> mid = Tree(6, [Tree(7, [Tree(8)]), Tree(9)])
>>> right = Tree(11, [Tree(12, [Tree(13, [Tree(14)])])])
>>> whole = Tree(0, [left, Tree(13), mid, right])
>>> for path in long_paths(whole, 2):
... print(path)
...
<0 1 2>
<0 1 3 4>
<0 1 3 4>
<0 1 3 5>
<0 6 7 8>
<0 6 9>
<0 11 12 13 14>
>>> for path in long_paths(whole, 3):
... print(path)
...
<0 1 3 4>
<0 1 3 4>
<0 1 3 5>
<0 6 7 8>
<0 11 12 13 14>
>>> long_paths(whole, 4)
[Link(0, Link(11, Link(12, Link(13, Link(14)))))]
"""
"*** YOUR CODE HERE ***"
if tree.is_leaf():
if n <= 0: # if n <= 0, which means the longth of paths is greater than n, because everytime you add a node, n = n-1
return [Link(tree.label)]
return [] # if n > 0, return a [].
else:
paths = []
for b in tree.branches:
paths += long_paths(b, n-1)
return [Link(tree.label, path) for path in paths] # if paths is [], then this will return []
#Official answer:
"*** YOUR CODE HERE ***" # the answer is much conciser than mine.
paths = []
if n <= 0 and tree.is_leaf():
paths.append(Link(tree.label))
for b in tree.branches:
for path in long_paths(b, n-1):
paths.append(Link(tree.label, path))
return paths # if no condition satisfied, return [].
| true |
aa05c22a090a1f2817964815f38eb8f58353ffab | weiranfu/cs61a | /functions/processing_tree/tree/add_trees.py | 2,912 | 4.3125 | 4 | # Define the function add_trees, which takes in two trees and returns a new tree where each corresponding node from the first tree is added with the node from the second tree.
# If a node at any particular position is present in one tree but not the other, it should be present in the new tree as well.
def add_trees(t1, t2):
"""
>>> numbers = tree(1, [tree(2,[tree(3), tree(4)]), tree(5, [tree(6, [tree(7)]), tree(8)])])
>>> print_tree(add_trees(numbers, numbers))
2
4
6
8
10
12
14
16
>>> print_tree(add_trees(tree(2), tree(3, [tree(4), tree(5)])))
5
4
5
>>> print_tree(add_trees(tree(2, [tree(3)]), tree(2, [tree(3), tree(4)])))
4
6
4
>>> print_tree(add_trees(tree(2, [tree(3, [tree(4), tree(5)])]), \
tree(2, [tree(3, [tree(4)]), tree(5)])))
4
6
8
5
5
"""
"*** YOUR CODE HERE ***"
if is_leaf(t1) and is_leaf(t2):
return tree(label(t1) + label(t2))
elif is_leaf(t1):
return tree(label(t1) + label(t2), branches(t2))
elif is_leaf(t2):
return tree(label(t1) + label(t2), branches(t1))
else:
b = [] # b is used to store the mutual branch of branches(tree1) and branches(tree2).
b_left = [] # b_left is used to store surplus branches of tree1 or tree2. eg: if tree1 has 3 branches, tree2 has five branches. Then b_left is used to store the surplus two branches of tree2.
len1, len2 = len(branches(t1)), len(branches(t2))
if len1 < len2:
b_left = branches(t2)[(len2-len1):]
if len1 > len2:
b_left = branches(t1)[(len1-len2):]
branches_tuples = zip(branches(t1), branches(t2)) # Put the mutual branch of two branches together into a tuple iterator.
for branch_tuple in list(branches_tuples): # Using list(iterator) to get all the tuples in a list. and branch_tuple means a tuple of corresponding branch of tree1 and tree2.
branch1, branch2 = branch_tuple # branch1 and branch2 is correspond to two elements in the tuple respectively.
branch = add_trees(branch1, branch2) # add two corresponding branch together.
b.append(branch) # Store the new branch into b.
return tree(label(t1) + label(t2), b + b_left) # the new branches are b + b_left.
# Official answer:
"*** YOUR CODE HERE ***"
b1, b2 = branches(t1), branches(t2)
if len(b1) > len(b2):
b2 += [tree(0)] * (len(b1) - len(b2)) # pad the shorter tree's branches with tree(0), after pad the shorter tree, these two trees have exactly same number of branch.
if len(b2) > len(b1):
b1 += [tree(0)] * (len(b2) - len(b1))
return tree(label(t1)+label(t2), [add_trees(b[0], b[1]) for b in zip(b1, b2)])
| true |
430c3b5a30cff99ff43ff1ede4ee3b7c810f99b8 | dhinesh-hub/pycode-excercise | /solutions/01_palindrome_or_not.py | 505 | 4.25 | 4 | #Find if sting is palindrome or not
"""Logic 1:
-Add input string to stack
-Pop the stack to a new string
-Compare the string for palindrome"""
palindrome_str = input("Enter the string:")
tmp_lst = []
reverse_str = ''
for i in palindrome_str:
tmp_lst.append(i)
print(tmp_lst)
for i in range(0,len(tmp_lst)):
reverse_str = reverse_str + tmp_lst.pop()
print(reverse_str)
if palindrome_str == reverse_str:
print("String is a palindrome")
else:
print("String is not a palindrome") | true |
3c2908a346a0a39176c2cccd6cf3ad16ecb825fa | dhinesh-hub/pycode-excercise | /anagram.py | 658 | 4.125 | 4 | def anagram_check(str1,str2):
list_str1 = [0]*26
list_str2 = [0]*26
print list_str1
print list_str2
for c in str1:
res1 = ord(c) - 97 #ord gives ASCII value of a charcter 97 ASCII value of a
print res1
list_str1[res1] = list_str1[res1] + 1
print list_str1
for c in str2:
res2 = ord(c) - 97 #ord gives ASCII value of a charcter
print res2
list_str2[res2] = list_str2[res2] + 1
print list_str2
for i in range(0,26):
if list_str1[i] != list_str2[i]:
return 'Strings not a anagram'
print 'Strings are anagram'
print anagram_check('azllo','lloza')
| false |
18a93dbf3dc7e7621674865812fc6901909730b2 | mainaak/python-learning | /if_statements.py | 831 | 4.1875 | 4 | # gender = input("What's your gender? (male/female)\n")
# gender = gender.lower()
#
# name: str
# pizza: str
# name = input("What's your name?\n")
# pizza = input("Do you like pizza? (yes/no)\n")
#
# condition_check = pizza.lower() == 'yes' or pizza.lower() == "y"
#
# if gender == 'male':
# if condition_check:
# print(name + " likes pizza and is male")
# else:
# print(name + " doesn't like pizza and is male")
# elif gender == 'female':
# if condition_check:
# print(name + " likes pizza and is female")
# else:
# print(name + " doesn't like pizza and is female")
def find_max(n1, n2, n3):
if n1 > n2:
if n1 > n3:
return n1
else:
return n3
elif n2 > n3:
return n2
else:
return n3
print(find_max(20, 86, 93))
| false |
019733a1977613aad4d782c1b7bf004f1bfa2b99 | icpac/FMC | /Git/MatrizElementalInversa.py | 666 | 4.375 | 4 | # -*- coding: utf-8 -*-
""" Por inspección encontrar la matriz inversa de una
matriz elemental
"""
__autor__ = "Tlacaelel Icpac"
__email__ = "tlacaelel.icpac@gmail.com"
import numpy as np
def PrintMul(a, b):
print("Matriz:\n", a)
print("Producto: \n", np.matmul(a, b))
a = np.array(
[
[0, 1],
[1, 0]
]
)
b = np.array(
[
[1, 0],
[5, 1]
]
)
binv = np.array(
[
[1, 0],
[-5, 1]
]
)
c = np.array(
[
[1, 0, 0],
[0, 1, -3],
[0, 0, 1]
]
)
cinv = np.array(
[
[1, 0, 0],
[0, 1, 3],
[0, 0, 1]
]
)
PrintMul(a, a)
PrintMul(b, binv)
PrintMul(c, cinv) | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.