blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
fd6f4950b4fdd76631619868f22938333061c7e3 | kheraankit/coursera | /interactive_python_rice/rock_paper_scissors_lizard_spock.py | 2,975 | 4.28125 | 4 |
# The key idea of this program is to equate the strings
# "rock", "paper", "scissors", "lizard", "Spock" to numbers
# as follows:
#
# 0 - rock
# 1 - Spock
# 2 - paper
# 3 - lizard
# 4 - scissors
import random
# helper functions
def number_to_name(number):
"""
This function accepts a 'number' as a key and
... | true |
2b6117afba9745fddf4f5622132b528848badc9a | bellajcord/Python-practice | /controlflow.py | 2,822 | 4.4375 | 4 | # Logical operators
# and
(1 > 2) and (2 < 3)
# multiple
(1 == 2) or (2 == 3) or (4 == 4)
##################################
### if,elif, else Statements #####
##################################
# Indentation is extremely important in Python and is basically Python's way of
# getting rid of enclosing brackets like... | true |
0352bb392701674291b3c5d2ce0af52a5834e9d4 | NathanontGamer/Multiplication-Table | /multiplication table.py | 894 | 4.46875 | 4 | #define function called multiplication table
def muliplication_table ():
#input number and number of row
number = int(input("Enter column / main number: "))
number_row = int(input("Enter row / number that (has / have) to times: "))
#for loop with range number_row
for i in range (1, number_ro... | true |
5fb8a8668dbc03e0c18b3e98ec85662217cdb38b | suraj13mj/Python-Practice-Programs | /13. Python 05-06-20 --- Dictionary/Program3.py | 405 | 4.125 | 4 | #Program to read Student details into Dictionary and append it a List
college=[]
N=int(input("Enter No of Students:"))
for i in range(0,N):
stud={}
stud["roll"]=int(input("\nEnter Roll No:"))
stud["name"]=input("Enter Name:")
stud["per"]=float(input("Enter Percentage:"))
college.append(stud)
for stud in college:... | false |
01d46d24b6c692f85aec4efcba110013b0b0a579 | suraj13mj/Python-Practice-Programs | /10. Python 31-01-20 --- Lists/Program5.py | 218 | 4.21875 | 4 | #Program to sort a 2D List
lst=[[25,13],[18,2],[19,36],[17,3]]
def sortby(element): #sorts based on column 2
return(element[1])
print("Before Sorting:",lst)
lst.sort(key=sortby)
print("After Sorting:",lst) | true |
706558592b4863c72ef112dfc3ab98588d5f796b | suraj13mj/Python-Practice-Programs | /32. Python 06-03-20 --- File Handling/Program1.py | 1,247 | 4.34375 | 4 | #Program to demonstrate basic file operations in Python
def createFile(filename):
fh=open(filename,"w")
print("Enter File contents:")
print("Enter '#' to exit")
while True:
line=input()
if line=="#":
break
fh.write(line+"\n")
fh.close()
def appendData(filename):
fh=open(filename,"a")
print("Enter ... | true |
30342271877f7edcf5c7b66362c5955599dee4f7 | suraj13mj/Python-Practice-Programs | /38. Python 15-04-20 --- NumPy/Program2.py | 498 | 4.125 | 4 | # Program to read a m x n matrix and find the sum of each row and each column
import numpy as np
print("Enter the order of the Matrix:")
r = int(input())
c = int(input())
arr = np.zeros((r,c),dtype=np.int8)
print("Enter matrix of order "+str(r)+"x"+str(c))
for i in range(r):
for j in range(c):
arr[i,j] = int(inp... | true |
cc88f1c06b6491398275065144285e7ab8e033ca | Mhtag/python | /oops/10public_protected_pprivate.py | 862 | 4.125 | 4 | class Employee:
holidays = 10 # Creating a class variables.
var = 10
_protec = 9 # Protected variables can be used by classes and sub classes.
__private = 7 # Private Variables can be used by only this class.
def __init__(self, name, salary, role):
self.name = name
... | true |
1236969d33c8c56768f35f63367e8fd54db295ab | BALAVIGNESHDOSTRIX/py-coding-legendary | /Advanced/combin.py | 473 | 4.1875 | 4 | '''
Create a function that takes a variable number of arguments, each argument representing the number of items in a group, and returns the number of permutations (combinations) of items that you could get by taking one item from each group.
Examples:
combinations(2, 3) ➞ 6
combinations(3, 7,... | true |
7c2acffba62cb6408f085fb2bf233c1ac2714c64 | jotawarsd/Shaun_PPS-2 | /assignments_sem1/assign6.py | 375 | 4.3125 | 4 | '''
Assignment No: 6
To accept a number from user and print digits of number in a reverse order using function.
'''
num1 = input("number : ") #get input from user
def reverse(s1):
n = len(s1) - 1 #establish index of last digit
for i in range(n,-1,-1): #printing the number in reverse
print(s1[i]... | true |
6a32a530aa936c83f2f7853c530948a0a2fded0b | MaximSidorkin/test | /task_2.py | 448 | 4.375 | 4 | '''
2. Пользователь вводит время в секундах.
Переведите время в часы, минуты и секунды и выведите в формате чч:мм:сс.
Используйте форматирование строк.
'''
seconds = int(input('введите секунду - '))
hours = seconds // 3600
minutes = (seconds // 60) % 60
seconds = seconds % 60
print(f"{hours}:{minutes}:{seconds}")
| false |
b97639963d80069a0c86b5eac5b58cae944877fd | guohuacao/Introduction-Interactive-Programming-Python | /week2-Guess-The-Number.py | 2,559 | 4.21875 | 4 | # "Guess the number" mini-project
# This code runs under http://www.codeskulptor.org/ with python 2.7
#mini-project description:
#Two player game, one person thinks of a secret number, the other peson trys to guess
#In this program, it will be user try to guess at input field, program try to decide
#"higher", "lower"... | true |
e725ed708943e6bbfcd9edb3d44f1b685bf50d61 | shishir-kr92/HackerRank | /Algorithm/problem_solving/The_Time_In_Word.py | 1,632 | 4.21875 | 4 |
time = ["o' clock",
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine",
"ten",
"eleven",
"twelve",
"thirteen",
"fourteen",
"quarter",
"sixteen",
"seventeen",
... | false |
a98c0c257dc9f921fa02386b918b46ef8d009487 | zb14755456464/pythonCookbook | /第四章:迭代器与生成器/4.12 不同集合上元素的迭代.py | 864 | 4.21875 | 4 | # 问题
# 你想在多个对象执行相同的操作,但是这些对象在不同的容器中,你希望代码在不失可读性的情况下避免写重复的循环
#解决方案
"""
itertools.chain() 方法可以用来简化这个任务。 它接受一个可迭代对象列表作为输入,
并返回一个迭代器,有效的屏蔽掉在多个容器中迭代细节。 为了演示清楚,考虑下面这个例子
"""
from itertools import chain
a = [1, 2, 3, 4]
b = ['x', 'y', 'z']
for x in chain(a, b): # 都是循环遍历,a,b两个列表,为了避免这样的重复操作,可以使用chain
print(x)
#讨论
"""
... | false |
feed0a4b5bbb7163c3cd4cce74b7457d3b898a3d | zb14755456464/pythonCookbook | /第四章:迭代器与生成器/4.1 手动遍历迭代器.py | 1,066 | 4.21875 | 4 | # 问题
# 你想遍历一个可迭代对象中的所有元素,但是却不想使用for循环。
# 解决方案
#为了手动的遍历可迭代对象,使用 next() 函数并在代码中捕获 StopIteration 异常。 比如,下面的例子手动读取一个文件中的所有行
items = [1, 2, 3, 4]
it = iter(items)
def manual_iter():
try:
while True:
line = next(it)
print(line, end='')
except StopIteration: # ... | false |
e33f71ec867753fa1a5029f0891fad03c9fce52b | sachinsaxena021988/Assignment7 | /MovingAvarage.py | 599 | 4.15625 | 4 | #import numpy module
import numpy as np
#define array to for input value
x=np.array([3, 5, 7, 2, 8, 10, 11, 65, 72, 81, 99, 100, 150])
#define k as number of column
k=3
#define mean array to add the mean
meanarray =[]
#define range to loop through numpy array
for i in range(len(x)-k+1):
#in... | true |
19801fea421a78906fc5cd0de64b9ff864d85983 | polora/polora.github.io | /scripts_exercices_1/C6Ex3_moyenne_amélioré.py | 1,152 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @author : YF
# @date : octobre 2022
### Correction de l'exercice - Calcul d'une moyenne de 3 notes - version améliorée
# déclaration des variables et initiation
nb_notes=0
somme=0
moyenne=0
i=1
# demande du nombre de notes
while True:
try:
nb_notes=fl... | false |
4fa2954258c033bc635614a03bde2f888e9e360f | Veraxvis/PRG105 | /5.2/derp.py | 726 | 4.1875 | 4 | def main():
costs = monthly()
print("You spend", '$' + "{:,.2f}".format(costs) + " on your car per month.")
per_year = yearly(costs)
print("In total you spend", '$' + "{:,.2f}".format(per_year) + " on your car per year.")
def monthly():
car_payment = float(input("Please enter your monthly car paym... | true |
7a23e70d9095909a575ebcad73b29b016b8f4da0 | miklo88/cs-algorithms | /single_number/single_number.py | 1,612 | 4.125 | 4 | '''
Input: a List of integers where every int except one shows up twice
Returns: an integer
'''
'''
UPER UPER TIME
so this function takes in a list of ints. aka a list[1,2,3,4,5,6]
of nums where every int shows up twice except one so like list[1,1,2,2,3,4,4,5,5,6,6]
so i need to return the int that is only listed once... | true |
235df1baba7c9ffe9222dfee29da356e2a1762fa | timlax/PythonSnippets | /Create Class v2.py | 1,369 | 4.21875 | 4 |
class Animal(object):
"""All animals"""
alive = ""
# Define the initialisation function to define the self attributes (mandatory in a class creation)
def __init__(self, name, age):
# Each animal will have a name and an age
self.name = name
self.age = age
# The description... | true |
07f57f122c2f0f6f3f558d78a27ff656bab8ac24 | Pratyush-PS/tathastu_week_of_code | /day6/program11.py | 275 | 4.28125 | 4 | size= int(input("\nEnter your list size:"))
li=[]
for i in range(size):
li.append(int(input("Enter element {}:".format(i+1))))
print("\nGiven list is:",li)
max_product=1
for i in sorted(li)[-3:]:
max_product *=i
print("\nMaximum possible product is:",max_product)
| false |
06b37c4c13983bbe4f9446dc6736755b834f35c9 | LKlemens/university | /python/7zestaw/circle.py | 1,496 | 4.125 | 4 | #! /usr/bin/python2.7
# -*- coding: utf-8 -*-
from math import pi, sqrt
from point import Point
class Circle(object):
"""Klasa reprezentująca okręgi na płaszczyźnie."""
def __init__(self, x=0, y=0, radius=1):
if radius < 0:
raise ValueError('negative radius')
self.center = Point... | false |
c9894657052e2db7a9bafdf51ae0f63fe25258bb | mikkope123/ot-harjoitustyo | /src/city/city.py | 1,752 | 4.5 | 4 | import math
class City:
"""A class representing a city on the salesman's route.':
Attributes:
x1, x2: cartesian coordinates representing the location of the city on the map
"""
def __init__(self, x1: float, x2: float):
"""Class constructor that creates a new city
Args:
... | true |
b2035acc0a2b2d9a4e764809f20d64fee47e6aa0 | Filipe-Amorim1/Scripts-Python | /Aula16/Aula16_exemplos_TUPLAS.py | 1,335 | 4.25 | 4 | # Tupla é entre parenteses ()
# Lista é entre [] colchetes
# Dicionário é entre {} chaves
########### TUPLAS ##########
# tuplas são imutavéis
lanche = ('hamburguer','suco','pizza','pudim','alface')
print(lanche)
print(lanche[1])
print(lanche[3])
print(lanche[-2])
print(lanche[1:3]) # nesse caso como vimos , ele ... | false |
00fefe5e093ea3f4cc2561a0d1ff54c2509a9586 | Filipe-Amorim1/Scripts-Python | /Aula 19 Dicionários/Exemplos_aula19.py | 1,557 | 4.1875 | 4 | filme = {'Titulo':'star wars','Ano':1977,'Diretor':'George Lucas' }
print(filme.values())
print(filme.keys())
print(filme.items())
print()
# usando o for para interagir com a var filme
# esse comando é igual o enumerate para listas e tuplas
for k,v in filme.items():
print(f'O {k} é {v}')
del filme ['Diretor'] # ap... | false |
744e938d38501aea487ccc54554851dec46f3bd3 | Filipe-Amorim1/Scripts-Python | /Aula09/Desafio22aula09manistring.py | 1,477 | 4.3125 | 4 | # Ler o nome de uma pessoa e mostrar
# nome com todas letras maiúsculas
# todas minúsculas
# letras ao todo sem considerar espaços
# letras tem o primeiro nome
nome = str(input('Digite seu nome completo:')).strip() # o .strip no final é para eliminar os espaços no ínicio e no fim para não conta-los
print('Analisando s... | false |
7a93885bf363e77b5a2faa17f55e2c83e0006603 | Filipe-Amorim1/Scripts-Python | /Aula16/Desafio75_Aula16_analise_de_dados.py | 749 | 4.125 | 4 | # Desenvolva um programa que leia quatro valores pelo teclado e guarde-os em uma tupla. No final, mostre:
# A) Quantas vezes apareceu o valor 9.
# B) Em que posição foi digitado o primeiro valor 3.
# C) Quais foram os números pares.
digite = (int(input('Digite um valor: ')),
int(input('Digite um valor: ')),
... | false |
0cbcf5fc45f1ff8287a3bc01e3b61e78f32db9d1 | Filipe-Amorim1/Scripts-Python | /Aula14/Desafio63_Fibonacci1.0.py | 840 | 4.15625 | 4 | #Escreva um programa que leia um número N inteiro qualquer
# e mostre na tela os N primeiros elementos de uma Sequência de Fibonacci. Exemplo:
# 0 – 1 – 1 – 2 – 3 – 5 – 8
# É uma sucessão de números que, misteriosamente, aparece em muitos fenômenos da natureza.
# Descrita no final do século 12 pelo italiano Leonardo Fi... | false |
eac6933afc3d425a8e812527802619da6548b228 | Filipe-Amorim1/Scripts-Python | /Aula09/Desafio28_Aula10_.py | 876 | 4.1875 | 4 | # Fazer o PC pensar em um numero inteiro entre 0 e 5
# Usuario vai tentar descobrir qual foi o número esolhido pelo PC
# O programa deverá ecrever na tela se o usuário venceu ou perdeu
import random
import emoji
ale = int(random.randint(0,5))
num = int(input('Tente adivinhar o número que estou pensando de 1 até 5:').... | false |
395d1fab2a05c1ffb4ed95a51d41e55e3706685c | Filipe-Amorim1/Scripts-Python | /Aula 13/Aula13exemplos1.py | 1,192 | 4.125 | 4 | for c in range (0,6): # para c (c é o nome do laço pode ser qquer nome ) in (no) range (intervalo) 0 até 6 ,
print('oi') # sempre no útimo número o python vai parar ou sair do laço para o px comando. vai contar de 0 a 5 ou seja 6x saira ou parara no 7
print('Fim') # O print com a indentação mais re... | false |
dff9d0f6b9dca11422d9d97ff54352aca8e6eacf | Faranaz08/assignment_3 | /que13.py | 600 | 4.1875 | 4 | #write a py program accept N numbers from the user and find the sum of even numbers
#product of odd numbers in enterd in a list
lst=[]
even=[]
odd=[]
sum=0
prod=1
N=int(input("enter the N number:"))
for i in range(0,N):
ele = int(input())
lst.append(ele)
if ele%2==0:
even.append(ele)
... | true |
2b783a4762657b56447de189929a210aa8e69bac | exclusivedollar/Team_5_analyse | /Chuene_Function_3.py | 724 | 4.28125 | 4 | ### START FUNCTION
"""This function takes as input a list of these datetime strings,
each string formatted as 'yyyy-mm-dd hh:mm:ss'
and returns only the date in 'yyyy-mm-dd' format.
input:
list of datetime strings as 'yyyy-mm-dd hh:mm:ss'
Returns:
returns a list of strings where each element in
the returned... | true |
987de188f535849170f5d44dafef82c543ad1bb6 | sstagg/bch5884 | /20nov05/exceptionexample.py | 237 | 4.125 | 4 | #!/usr/bin/env python3
numbers=0
avg=0
while True:
inp=input("Please give me a number or the word 'Done': ")
if inp=="Done":
break
else:
x=float(inp)
avg+=x
numbers+=1
avg=avg/numbers
print ("The average is %.2f" % (avg)) | true |
cee079505a684ef5a58041492ed437eba43572b5 | JayAgrawalgit/LearnPython | /1. Learn the Basics/1.9 Functions/1. What are Functions.py | 1,282 | 4.5625 | 5 | # Functions are a convenient way to divide your code into useful blocks,
# allowing us to order our code, make it more readable, reuse it and save some time.
# Also functions are a key way to define interfaces so programmers can share their code.
# How do you write functions in Python?
# As we have seen on previous tu... | true |
a10abea0005837374d7908ed655aa4fddfe87e61 | JayAgrawalgit/LearnPython | /1. Learn the Basics/1.2 Variables and Types/1. Numbers.py | 628 | 4.4375 | 4 | # Python supports two types of numbers - integers and floating point numbers. (It also supports complex numbers, which
# will not be explained in this tutorial).
# To define an integer, use the following syntax:
myint = 7
print("Integer Value printed:",myint)
# To define a floating point number, you may use one of th... | true |
55d49ce7240c7af9c27430d134507103cc6739c7 | JayAgrawalgit/LearnPython | /1. Learn the Basics/1.11 Dictionaries/1. Basics.py | 688 | 4.15625 | 4 | # A dictionary is a data type similar to arrays, but works with keys and values instead of indexes.
# Each value stored in a dictionary can be accessed using a key,
# which is any type of object (a string, a number, a list, etc.) instead of using its index to address it.
# For example, a database of phone numbers could... | true |
a9ad5d63cd98a178b4efdf2343c9e4f083d42a24 | uc-woldyemm/it3038c-scripts | /Labs/Lab5.PY | 486 | 4.15625 | 4 | print("Hello Nani keep doing your great work")
print("I know you're busy but is it okay if i can get some information about you")
print("How many years old are you?")
birthyear = int(input("year: "))
print("What day you born")
birthdate = int(input("date: "))
print("Can you also tell me what month you were born")
bir... | true |
235bd7c02a7555c8d059e401b18bf9bb4c6ee2dc | PranilDahal/SortingAlgorithmFrenzy | /BubbleSort.py | 854 | 4.375 | 4 | # Python code for Bubble Sort
def BubbleSort(array):
# Highest we can go in the array
maxPosition = len(array) - 1
# Iterate through the array
for x in range(maxPosition):
# For every iteration, we get ONE sorted element.
# After x iterations, we have x sorted elements
# We don't swap on the... | true |
7a5ecb354bfdd283896bcbfdb5b177bd53b90b15 | vidyasagarr7/DataStructures-Algos | /GeeksForGeeks/Strings/WildCardMatching.py | 1,442 | 4.40625 | 4 |
"""
String matching where one string contains wildcard characters
Given two strings where first string may contain wild card characters and second string is a normal string.
Write a function that returns true if the two strings match. The following are allowed wild card characters
in first string.
* --> Matches wit... | true |
38333c31be9bf385cbc0ad0f612ce39907f30648 | vidyasagarr7/DataStructures-Algos | /GeeksForGeeks/LinkedList/MoveLastToFirst.py | 787 | 4.46875 | 4 | from GeeksForGeeks.LinkedList.SinglyLinkedList import LinkedList
"""
Move last element to front of a given Linked List
Write a C function that moves last element to front in a given Singly Linked List. For example, if the given Linked
List is 1->2->3->4->5, then the function should change the list to 5->1->2->3->4.
""... | true |
b5a1b48719e01685184f6546f5bac08e7804502e | vidyasagarr7/DataStructures-Algos | /Cormen/2.3-5.py | 761 | 4.125 | 4 |
def binary_search(input_list,key):
"""
Binary search algorithm for finding if an element exists in a sorted list.
Time Complexity : O(ln(n))
:param input_list: sorted list of numbers
:param key: key to be searched for
:return:
"""
if len(input_list) is 0:
return False
else ... | true |
f0420e011a39072b2edd46884b9bcdb1ede1270b | vidyasagarr7/DataStructures-Algos | /GeeksForGeeks/Arrays/CheckConsecutive.py | 1,492 | 4.125 | 4 | import sys
"""
Check if array elements are consecutive | Added Method 3
Given an unsorted array of numbers, write a function that returns true if array consists of consecutive numbers.
Examples:
a) If array is {5, 2, 3, 1, 4}, then the function should return true because the array has consecutive numbers
from 1 to 5... | true |
7eefbcb7099c14384b4046d2cfcece1fba35a473 | vidyasagarr7/DataStructures-Algos | /GeeksForGeeks/Strings/InsertSpaceAndPrint.py | 916 | 4.15625 | 4 |
"""
Print all possible strings that can be made by placing spaces
Given a string you need to print all possible strings that can be made by placing spaces (zero or one) in between them.
Input: str[] = "ABC"
Output: ABC
AB C
A BC
A B C
"""
def toString(List):
s = []
for x in List:
... | true |
dd9088ed2e952a61cbc2f117274edd650d4aae16 | vidyasagarr7/DataStructures-Algos | /GeeksForGeeks/LinkedList/ReverseAlternateKnodes.py | 1,182 | 4.15625 | 4 | from GeeksForGeeks.LinkedList.SinglyLinkedList import LinkedList
"""
Reverse alternate K nodes in a Singly Linked List
Given a linked list, write a function to reverse every alternate k nodes (where k is an input to the function)
in an efficient way. Give the complexity of your algorithm.
Example:
Inputs: 1->2->3-... | true |
57e66fcfe37a98d3b167627e8d0451ad9f37f567 | vidyasagarr7/DataStructures-Algos | /GeeksForGeeks/Arrays/ConstantSumTriplet.py | 1,203 | 4.25 | 4 | """
Find a triplet that sum to a given value
Given an array and a value, find if there is a triplet in array whose sum is equal to the given value.
If there is such a triplet present in array, then print the triplet and return true. Else return false.
For example, if the given array is {12, 3, 4, 1, 6, 9} and given su... | true |
6356464fb2f5e1c1440e0a5af8c7bc2ab5188183 | vidyasagarr7/DataStructures-Algos | /GeeksForGeeks/Arrays/TwoRepeatingNumbers.py | 1,133 | 4.28125 | 4 |
"""
Find the two repeating elements in a given array
You are given an array of n+2 elements. All elements of the array are in range 1 to n.
And all elements occur once except two numbers which occur twice. Find the two repeating numbers.
For example, array = {4, 2, 4, 5, 2, 3, 1} and n = 5
The above array has n + ... | true |
ee861e0efdb6e5515dd24ad97b15d2fecefde994 | vidyasagarr7/DataStructures-Algos | /GeeksForGeeks/LinkedList/NthElement.py | 877 | 4.125 | 4 | from GeeksForGeeks.LinkedList.SinglyLinkedList import LinkedList,Node
"""
Write a function to get Nth node in a Linked List
Write a GetNth() function that takes a linked list and an integer index and returns the data value stored in the node at that index position.
Example:
Input: 1->10->30->14, index = 2
Output:... | true |
c71547e58e1d6c3c5d5caade6d1091312a3d6f71 | vidyasagarr7/DataStructures-Algos | /GeeksForGeeks/Strings/PrintDistinctPermutations.py | 1,065 | 4.125 | 4 | """
Print all distinct permutations of a given string with duplicates
Given a string that may contain duplicates, write a function to print all permutations of given string
such that no permutation is repeated in output.
Examples:
Input: str[] = "AB"
Output: AB BA
Input: str[] = "AA"
Output: AA
Input: str[] = "... | true |
b5b4d136247ccd07ddc1da1a665775f36c1713a4 | vidyasagarr7/DataStructures-Algos | /Trees/SearchElement.py | 1,191 | 4.21875 | 4 | from Karumanchi.Trees import BinaryTree
from Karumanchi.Queue import Queue
def search_element(node,element):
"""
Algorithm for searching an element Recursively
:param node:
:param element:
:return:
"""
if not node:
return False
else:
if node.data == element:
... | true |
18858b1ec937e1850ab9ae06c83dc35d15d36c85 | vidyasagarr7/DataStructures-Algos | /609-Algos/Lab-2/BubbleSort.py | 513 | 4.28125 | 4 |
def bubble_sort(input_list):
"""
Bubble Sort algorithm to sort an unordered list of numbers
:param input_list: unsorted list of numbers
:return: sorted list
"""
for i in range(len(input_list)):
for j in range(len(input_list)-1-i):
if input_list[j]>input_list[j+1]:
... | true |
2f45a066f0b461b0992094cb8f515ce3f4dd2269 | vidyasagarr7/DataStructures-Algos | /GeeksForGeeks/Strings/ReverseWords.py | 420 | 4.4375 | 4 |
"""
Reverse words in a given string
Example: Let the input string be “i like this program very much”.
The function should change the string to “much very program this like i”
"""
def reverse_words(string):
words_list = string.split(' ')
words_list.reverse()
return ' '.join(words_list)
if __name__=='__m... | true |
e20c9d2168f9e5c23ef638185ae2e00adbb90dfa | vidyasagarr7/DataStructures-Algos | /Karumanchi/Searching/CheckDuplicates.py | 1,726 | 4.28125 | 4 |
from Karumanchi.Sorting import MergeSort
from Karumanchi.Sorting import CountingSort
def check_duplicates(input_list):
"""
O(n^2) algorithm to check for duplicates
:param input_list:
:return:
"""
for i in range(len(input_list)):
for j in range(i+1,len(input_list)):
if input... | true |
2ef19d4886644d077c1f53c97f7de400c7019540 | vidyasagarr7/DataStructures-Algos | /GeeksForGeeks/Arrays/Rearrange.py | 1,096 | 4.1875 | 4 |
"""
Rearrange an array so that arr[i] becomes arr[arr[i]] with O(1) extra space
Given an array arr[] of size n where every element is in range from 0 to n-1. Rearrange the given array so that
arr[i] becomes arr[arr[i]]. This should be done with O(1) extra space.
Examples:
Input: arr[] = {3, 2, 0, 1}
Output: arr[]... | true |
4b1793f6d8c391ad17ecdfabc74702886aa02ebc | vidyasagarr7/DataStructures-Algos | /Karumanchi/Selection/KthSmallest.py | 1,531 | 4.40625 | 4 | from Karumanchi.Sorting import QuickSort
def partition(list,start,end):
"""
Partition Algorithm to partition a list - selecting the end element as the pivot.
:param list:
:param start:
:param end:
:return:
"""
i=start-1
pivot = list[end]
for j in range(start,end):
if lis... | true |
d7f32f9626f66394f459babf3b22b0ad229a0203 | chenliang15405/python-learning | /study_day01-基础/11_切片.py | 553 | 4.21875 | 4 | """
切片:
语法:
序列[开始位置下标:结束位置下标:步长]
注意:
不包含结束位置的下标数据
步长是选取间隔,默认步长为1,步长是可选参数
"""
str = '0123456789'
print(str[2:]) # 如果不写结束,表示到结尾
print(str[:3]) # 如果不写开始,表示从头开始
print(str[:]) # 开始和结尾都不写,表示选取所有
print(str[-3:-1]) # 负数表示从后向前,-3 表示最后一个数
# 如果选取的方向和步长的方法冲突,那么无法选择数据 | false |
de78157337b2849f1bde3dceda7ce00ff7325e79 | chenliang15405/python-learning | /study_day07-python高级语法/06_创建property其他属性的方式.py | 1,154 | 4.21875 | 4 | """
在对象中,可以通过定义property的三种方式,来触发属性的更新等情况并进行计算:
1。 获取数据: 必须返回一个值,并且没有参数,可以通过计算返回一个值
@property
def price(self):
return 100
2. setter: 通过@<propertyname>.setter的定义形式,当给property装饰的变量赋值的时候触发此方法
@price.setter
def price(self, value):
# 传递的参数是赋值时的参数
... | false |
c7e45ee0ceb6dcb6edd694ef58b8eaf10cfcac41 | chenliang15405/python-learning | /study_day03-面向对象/文件/01_文件的基本操作.py | 2,059 | 4.40625 | 4 | """
python中操作文件的函数/方法:
1. open 函数: 打开文件,并返回文件操作对象
2. read 方法: 将文件内容读取到内存, 在同一个打开的文件中,读取一次,文件的指针会指向文件末尾,再次读取就读取不到数据
3. wirte 方法: 将制定内容写入到文件
4. close 方法: 关闭文件
打开文件的方式:
1. open() 函数: 默认的是以只读方式打开文件,只读不可写
2. open("文件名", "打开方式") 以指定的方式打开文件
打开方式:
r : 默认模式,以只读方式打开
w: 只... | false |
706d32805925b2d80a4c9c1be436dd3f19bd8d11 | buxuele/algo_snippet | /二叉树/sub_tree.py | 1,955 | 4.28125 | 4 | # python3 实现二叉树
# 最好是参考这篇再看一遍:
# https://www.cnblogs.com/maxiaonong/p/10060086.html
class Node:
def __init__(self, element, lchild=None, rchild=None):
self.element = element
self.lchild = lchild
self.rchild = rchild
class Tree:
def __init__(self, root=None):
self.root = root
... | false |
638c098b21f50c29ddbb8136459117a099677acc | educa2ucv/Material-Apoyo-Python-Basico | /Codigos/2-TiposDeDatos/Logico.py | 579 | 4.375 | 4 | """
En Python tenemos las siguientes operaciones logicas y operandos logicos:
Mayor estricto (>)
Mayor o igual (>=)
Menor estricto (<)
Menor o igual (<=)
Igualdad (==)
Diferente (!=)
Y lógico (and)
O lógico (or)
Negación lógico (not)
"""
"""e... | false |
270b0e19adea8d97c788ff31305616b65c516f76 | shenzekun/leetcode | /Sqrt_x.py | 844 | 4.15625 | 4 | """
实现 int sqrt(int x) 函数。
计算并返回 x 的平方根,其中 x 是非负整数。
由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。
示例 1:
输入: 4
输出: 2
示例 2:
输入: 8
输出: 2
说明: 8 的平方根是 2.82842...,
由于返回类型是整数,小数部分将被舍去。
思路:
由于 x^2是单调递增,因此使用二分法
"""
class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
... | false |
0f1edc71a026eac62eb4b641c0bd9ede2a98bbee | imran9891/Python | /PyFunctionReturns.py | 882 | 4.125 | 4 | #!/usr/bin/env python
# coding: utf-8
# <h3 align="center">Function Return</h3>
# In[ ]:
def sum1(num1, num2):
def another_func(n1,n2):
return n1 + n2
return another_func
def sum2(num1, num2):
def another_func2(n1,n2):
return n1 + n2
return another_func2(num1, num2)
print(sum1(10,... | true |
d7c4c21563a09c85d82d652626eb7f5230b9254d | khairooo/Learn-linear-regression-the-simplest-way | /linear regression.py | 1,829 | 4.4375 | 4 | # necessary packages
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error,r2_score
# generate random data-set
np.random.seed(0)
# generate 100 random numbers with 1d array
x = np.random.ran... | true |
efa056ec08f3358df04e1da1bdef6db73dec39c3 | chenlongjiu/python-test | /rotate_image.py | 936 | 4.25 | 4 | '''
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Follow up:
Could you do this in-place?
'''
class Solution(object):
def rotate(self, matrix):
for row in xrange(len(matrix)):
for col in xrange(row,len(matrix)):
matrix[row][col], ma... | true |
1290224ca58fbf8f17c968dcb9318ce6594845bd | geekysid/Python-Basics | /3. List, Set, Tuple/SetOperations.py | 1,967 | 4.4375 | 4 | print("SET OPERATIONS")
setA = {1, 2, 3, 4, 5, 6, 7, 8, 9}
setB = {2, 4, 6, 8, 10}
setC = {"2", "4", "6", "8"}
print(f"SetA : {setA}")
print(f"SetB : {setB}")
print(f"SetC : {setC}")
print()
print("==UNION (|)==") # returns every elements in two sets
print(f"setA.union(setB): {setA.union(setB)}")
pri... | false |
4debf55c34b266031b2c68890e629717f6043d76 | geekysid/Python-Basics | /4. Dictionary/Dictionary Challenge Modified 2.py | 1,714 | 4.21875 | 4 | # Modify the program so that the exits is a dictionary rather than a list, with the keys being the numbers of the
# locations and the values being dictionaries holding the exits (as they do at present). No change should be needed
# to the actual code.
locations = {0: "You are sitting in front of a computer learning Py... | true |
e75b0ab18452e7da90b5f6c81bc317224eaf24f1 | jmshin111/alogrithm-test | /merge two sorted list.py | 1,746 | 4.15625 | 4 | # A single node of a singly linked list
import sys
import timeit
class Node:
# constructor
def __init__(self, data=None):
self.data = data
self.next = None
# A Linked List class with a single head node
class LinkedList:
def __init__(self):
self.head = None
self.end = None... | true |
439f8e77560fa42094e061ba7c4e1bd71956b8fd | mohdelfariz/distributed-parallel | /Lab5-Assignment3.py | 1,284 | 4.25 | 4 | # Answers for Assignment-3
# Importing mySQL connector
import mysql.connector
# Initialize database connection properties
db_connection = mysql.connector.connect(
host="localhost",
user="root",
passwd="",
database="my_first_db"
)
# Show newly created database (my_first_db should be on th... | true |
453d4cfd55465b4793848e9ba7935aff0592dde1 | gopikris83/gopi_projects | /GlobalVariables.py | 401 | 4.25 | 4 | # -------- Defining variables outside of the function (Using global variables) ----------------
x = "Awesome"
def myfunc():
print (" Python is "+x)
myfunc()
# ---------- Defining variables inside of the function (Using local variables) --------------------------
x = "Awesome"
def myfunc():
x... | true |
07c316740d12e1696356fea2dfef3d0e224e5193 | ShalomVanunu/SelfPy | /Targil5.3.5.py | 342 | 4.15625 | 4 |
def distance(num1, num2, num3):
num1_num2 = abs(num2-num1)
num3_num2 = abs(num3-num2)
# print(num3_num2)
# print(num1_num2)
if (num1_num2 == 1 and num3_num2 > 2 ):
return True
else:
return False
print('distance(1, 2, 10)')
print(distance(1, 2, 10))
print('distance(4, 5, 3)')
prin... | false |
85fa0da795f8130c75bbdb6695fae9319234c74f | ShalomVanunu/SelfPy | /Targil7.3.1.py | 640 | 4.21875 | 4 |
def show_hidden_word(secret_word, old_letters_guessed):
hidden_word = []
for letter in secret_word:
if letter not in old_letters_guessed:
hidden_word.append(' _')
else:
hidden_word.append(letter)
return ' '.join(hidden_word)
def main(): # Call the function func
... | false |
c23b5e18a881d02083b06c9e0cca83197c62e928 | deficts/hackerrank-solutions | /PythonDataStructures/Lists.py | 489 | 4.21875 | 4 | MyList=[1,2,4,5]
#Agregar algo al final
MyList.append("hola")
print(MyList)
#Agregar algo en un cierto índice
MyList.insert(1,"mundo")
print(MyList)
#Remover un objeto pasado
MyList.remove("mundo")
print(MyList)
#Regresar y quitar un objeto de un indice o el ultimo
MyList.pop()
MyList.pop(0)
print(MyList)
#Quitar ... | false |
e65c2135625c668523ea865f75bc320b2cdab043 | gr8tech/pirple.thinkific.com | /Python/Homework3/main.py | 931 | 4.1875 | 4 | '''
Python Homework Assignment 3
Course: Python is Easy @ pirple
Author: Moosa
Email: gr8tech01@gmail.com
`If` statements; Comparison of numbers
'''
def number_match(num1, num2, num3):
'''
Functions checks if 2 or more of the given numbers are equal
Args:
num1, num2, num3
num1, num2, num3 can be an Integer or ... | true |
fbc4c72d145f853991cda9bba427f33de8ab8d08 | jagadeeshindala/python | /Project.py | 850 | 4.28125 | 4 | #Rock paper scissors game with computer
import random
#Function
def game(a,b):
if(a == b):
return None
if(a=="r"):
if(b=="s"):
return False
else:
return True
if(a=="s"):
if(b=="p"):
return False
else:
return True
if(a=="p"):
if(b=="w"):
return False
else:
return... | false |
1582966887ebcfcec8a2ddb74e0823cb7b72c95e | Chethan64/PESU-IO-SUMMER | /coding_assignment_module1/5.py | 212 | 4.25 | 4 | st = input("Enter a string: ")
n = len(st)
flag = 0
for i in st:
if not i.isdigit():
flag = 1
if(flag):
print("The string is not numeric")
else:
print("The string is numeric")
| true |
b024cf8229c1ea31c1299d283b52375d0c11ec10 | Abdelmuttalib/Python-Practice-Challenges | /Birthday Cake Candles Challenge/birthDayCakeCandles.py | 815 | 4.15625 | 4 |
####### SOLUTION CODE ########
def birthdayCakeCandles(candles):
## initializing an integer to hold the value of the highest value
highest = 0
## count of highest to calculate how many the highest value is found in the array
count_of_highest = 0
## iterate over the array to determine the high... | true |
067c383afe1a81e2b864b2f8d274c2e7768ed190 | shreyashg027/Leetcode-Problem | /Data Structure/Stacks.py | 504 | 4.125 | 4 | class Stack:
def __init__(self):
self.stack = []
def push(self, data):
if data not in self.stack:
self.stack.append(data)
def peek(self):
return self.stack[len(self.stack)-1]
def remove(self):
if len(self.stack) <= 0:
return 'No element in the s... | true |
4bce5f49c82972c9e7dadd48794bcc545e25095b | miketwo/euler | /p7.py | 704 | 4.1875 | 4 | #!/usr/bin/env python
'''
By listing the first six prime numbers:
2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10001st prime number?
'''
from math import sqrt, ceil
def prime_generator():
yield 2
yield 3
num = 3
while True:
num += 2
if is_prime(num):
... | true |
9e84eeb486846d437d69a8d08c717240cbb462a5 | TejaswitaW/Advanced_Python_Concept | /RegEx12.py | 260 | 4.125 | 4 | #use of function fullmatch in regular expression
import re
s=input("Enter string to be matched")
m=re.fullmatch(s,"abc")
if(m!=None):
print("Complete match found for the string:",m.start(),m.end())
else:
print("No complete match found for the string")
| true |
aa4804d2a19435b061d58c5855bee819aee31751 | TejaswitaW/Advanced_Python_Concept | /RegEx23.py | 232 | 4.5 | 4 | #Regular expression to find valid mobile number
import re
n=input("Enter mobile number")
v=re.search("^+91",n)
if v!=None:
print("It is a valid mobile number in India")
else:
print("It is not valid mobile number in India")
| false |
d139c57f5add5f8be6008fad651ea3eca04e4c39 | TejaswitaW/Advanced_Python_Concept | /ExceptionElse.py | 385 | 4.15625 | 4 | #Exception with else block
#else block is executed only when there is no exception in try block
try:
print("I am try block,No exception occured")
except:
print("I am except block executed when there is exception in try block")
else:
print("I am else block,executed when there is no exception in try block")
f... | true |
8784f56f872cea6ffab7517f482296ea9904a1b4 | SerdarKuliev/proj1 | /4/4-1.py | 622 | 4.15625 | 4 | #Реализовать скрипт, в котором должна быть предусмотрена функция расчета заработной платы сотрудника.
#В расчете необходимо использовать формулу: (выработка в часах*ставка в час) + премия.
#Для выполнения расчета для конкретных значений необходимо запускать скрипт с параметрами.
import my_func
print(str(my_func.my_f(in... | false |
57f541234da83f773c5e138adedb2caf20cfceb3 | SerdarKuliev/proj1 | /2/2-1.py | 1,320 | 4.125 | 4 | #1. Создать список и заполнить его элементами различных типов данных. Реализовать скрипт проверки типа данных каждого элемента.
#Использовать функцию type() для проверки типа. Элементы списка можно не запрашивать у пользователя, а указать явно, в программе.
my_list = [34, None, 3.14, "Yo!", [1,2,67], 8*5, '8*5', True,... | false |
1f4069a21af18b88a7ddf117162036d212f2135c | lfarnsworth/GIS_Python | /Coding_Challenges/Challenge2/2-List_Overlap.py | 1,133 | 4.375 | 4 | # 2. List overlap
# Using these lists:
#
# list_a = ['dog', 'cat', 'rabbit', 'hamster', 'gerbil']
# list_b = ['dog', 'hamster', 'snake']
# Determine which items are present in both lists.
# Determine which items do not overlap in the lists.
# #Determine which items overlap in the lists:
def intersection(list_a, list_b... | true |
f91c9dd7ea1c66a0a757d32dc00c3e1f0adef7e7 | udhayprakash/PythonMaterial | /python3/06_Collections/03_Sets/a_sets_usage.py | 1,219 | 4.40625 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
Purpose: Working with Sets
Properties of sets
- creating using {} or set()
- can't store duplicates
- sets are unordered
- can't be indexed
- Empty sets need to be represented using set()
- stores only immutable object - ... | true |
627c4ac2e040d41a4e005253e1dd7c20f9d5cf63 | udhayprakash/PythonMaterial | /python3/04_Exceptions/11_raising_exception.py | 1,248 | 4.28125 | 4 | #!/usr/bin/python3
"""
Purpose: Raising exceptions
"""
# raise
# RuntimeError: No active exception to reraise
# raise Exception()
# Exception
# raise Exception('This is an error')
# Exception: This is an error
# raise ValueError()
# ValueError
# raise TypeError()
# raise NameError('This is name error')
# NameErro... | true |
79eb6b4be07ee81b3a360a3fe2ab759947735a5e | udhayprakash/PythonMaterial | /python3/19_Concurrency_and_Parallel_Programming/02_multiprocessing/b1_process_pool.py | 1,587 | 4.40625 | 4 | """
Purpose: Multiprocessing with Pools
Pool method allows users to define the number of workers and
distribute all processes to available processors in a
First-In-First-Out schedule, handling process scheduling automatically.
Pool method is used to break a function into multiple small parts using
... | true |
1bad217136738b325f1dd38d8484904f13d69989 | udhayprakash/PythonMaterial | /python3/07_Functions/014_keyword_only_args.py | 1,541 | 4.3125 | 4 | #!/usr/bin/python3
"""
Purpose: Functions Demo
Function with Keyword ONLY args
Named arguments appearing after '*' can only be
passed by keyword
Present only in Python 3.X
"""
def servr_login(server_name, user_name, password):
print(
f"""
{server_name =}
{user_name =}
... | false |
6782bce539f905db7c05238f1b906edf054b5aeb | udhayprakash/PythonMaterial | /python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/a_function_based/f_custom_thread_class.py | 939 | 4.375 | 4 | #!/usr/bin/python
# Python multithreading example to print current date.
# 1. Define a subclass using Thread class.
# 2. Instantiate the subclass and trigger the thread.
import datetime
import threading
class myThread(threading.Thread):
def __init__(self, name, counter):
threading.Thread.__init__(self... | true |
0f39ba4fb7de201f9bf21ceac445f5246c785886 | udhayprakash/PythonMaterial | /python3/04_Exceptions/13_custom_exceptions.py | 1,183 | 4.15625 | 4 | #!/usr/bin/python3
"""
Purpose: Using Custom Exception
"""
# # Method 1 - stop when exception is raised
# try:
# votes = 0
# i = 0
# while i < 5:
# age = int(input('Enter your age:'))
# if age <= 0:
# raise Exception('Invalid Entry for the age!')
# elif age < 18:
# ... | false |
2e7734c27ca1713f780710c935c2981fa7bc0577 | udhayprakash/PythonMaterial | /python3/09_Iterators_generators_coroutines/02_iterators/e_user_defined_iterators.py | 926 | 4.65625 | 5 | #!/usr/bin/python3
"""
Purpose: Iterators
- To get values from an iterator objects
1. Iterate over it
- for loop
- converting to other iterables
- list(), tuple(), set(), dict()
2. To apply next()
... | true |
37b606ca02ac4bfd4e53e038c0280ee660d3277c | udhayprakash/PythonMaterial | /python3/10_Modules/04a_os_module/display_tree_of_dirs.py | 637 | 4.125 | 4 | #!/usr/bin/python
"""
Purpose: To display the tree strcuture of directories only , till three levels
test
sub1
sub2
subsub1
"""
import os
import sys
MAX_DEPTH = 3 # levels
given_path = sys.exec_prefix # input('Enter the path:')
print(given_path)
def display_folders(_path, _depth):
if _depth !=... | true |
f99296176c5701a5fe9cbc10d37767fa91ab06f4 | udhayprakash/PythonMaterial | /python3/15_Regular_Expressions/d_re_search.py | 965 | 4.59375 | 5 | """
Purpose: Regular Expressions
Using re.match
- It helps to identify patterns at the starting of string
Using re.search
- It helps to identify patterns at the ANYWHERE of string
"""
import re
target_string = "Python Programming is good for health"
# search_string = "python"
for search_strin... | true |
a9bafcaa72533199973fad8a3ea5ba444dadf162 | udhayprakash/PythonMaterial | /python3/14_Code_Quality/04_unit_tests/b_using_unittest_module/d_MultipleTestScripts_ex/mymod.py | 240 | 4.15625 | 4 | """
Purpose:
anagram
cat <--> act
"""
def is_anagram(a_word, b_word):
"""
>>> is_anagram('cat', 'act')
True
>>> is_anagram('tom', 'mat') is not True
True
"""
return sorted(a_word) == sorted(b_word)
| false |
e12c213d1234b0229d1a6e9c51de5d809c4a3968 | udhayprakash/PythonMaterial | /python3/02_Basics/01_Arithmetic_Operations/b_arithmetic_operations.py | 1,265 | 4.3125 | 4 | #!/usr/bin/python3
"""
Purpose: Arithmetic Operations
NOTE: PEP 8 recommends to place one space around the operator
"""
print("power operation **")
print("4 ** 2 = ", 4**2)
print("64 ** (1/2) = ", 64 ** (1 / 2)) # square root
print("64 ** (1/2.0) = ", 64 ** (1 / 2.0)) # square root
print("64 *... | false |
da46171c56e002b5bc69e5d5fc2264fe80d0e5a4 | udhayprakash/PythonMaterial | /python3/14_Code_Quality/01_static_typing/f_iterator.py | 375 | 4.125 | 4 | """
Purpose: Static typing
"""
from typing import Iterator
# Using Dynamic typing
def fib(n):
a, b = 0, 1
while a < n:
yield a
a, b = b, a + b
# Static typing
def fib1(n: int) -> Iterator[int]:
a, b = 0, 1
while a < n:
yield a
a, b = b, a + b
if __name__ == "__main_... | false |
a09bab1878819e6069d4afe189fcf43f63593695 | udhayprakash/PythonMaterial | /python3/14_Code_Quality/01_static_typing/g_example.py | 1,046 | 4.3125 | 4 | """
Purpose: Static typing
"""
from typing import Dict, List, Tuple
# Traditional Approach
my_data = ("Adam", 10, 5.7)
print(f"{my_data =}")
# Adding Typing
my_data2: Tuple[str, int, float] = ("Adam", 10, 5.7)
print(f"{my_data2 =}")
# --------------------------------
# A list of integers
# Traditional Approach
num... | false |
66c6cf5dc25e81f8e1adad58ac56c932f0d4a41e | udhayprakash/PythonMaterial | /python3/04_Exceptions/06_handling_multiple_exceptions.py | 761 | 4.1875 | 4 | #!/usr/bin/python3
"""
Purpose: Exception Handling
Exception Hierarchy
"""
# try:
# num1 = int(input("Enter an integer:"))
# num2 = int(input("Enter an integer:"))
# division = num1 / num2
# except Exception as ex:
# print(f"{ex =}")
# print("Please enter integers only (or) denominator is 0")
... | false |
5399535d50a3bc576a80fd1cd911b70a8891d6c6 | udhayprakash/PythonMaterial | /python3/10_Modules/03_argparse/b_calculator.py | 1,183 | 4.5 | 4 | #!/usr/bin/python
"""
Purpose: command-line calculator
"""
import argparse
def addition(n1, n2):
return n1 + n2
def subtraction(s1, s2):
return s1 - s2
def multiplication(m1, m2, m3):
return m1 * m2 * m3
# Step 1: created parser object
parser = argparse.ArgumentParser(description="Script to add two/... | true |
d85262260f5fcfc72b9d23bb046cc460d51bc8e3 | udhayprakash/PythonMaterial | /python3/14_Code_Quality/01_static_typing/k_Union_type.py | 610 | 4.21875 | 4 | """
Purpose: Union type
"""
from typing import Union
def is_even_whole(num) -> Union[bool, str]:
if num < 0:
return "Not a whole number"
return True if num % 2 == 0 else False
assert is_even_whole(10) is True
assert is_even_whole(19) is False
assert is_even_whole(-2) == "Not a whole number"
def is... | false |
ef14eb6c7361331b6c3ba966a7a128a48d7b0b45 | udhayprakash/PythonMaterial | /python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/c_locks/b1a_class_based_solution.py | 760 | 4.21875 | 4 | """
Purpose: Class based implementation of
synchronization using locks
"""
from threading import Lock, Thread
from time import sleep
class Counter:
def __init__(self):
self.value = 0
self.lock = Lock()
def increase(self, by):
self.lock.acquire()
current_value = self.value... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.