blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
b0ddbc1dc24e5b345953154bcbff30b69f29b319
joaovictor-loureiro/data-science
/data-science/exercicios/livro-introducao-a-programacao-com-python/capitulo-3/exercicio3-13.py
319
4.28125
4
# Exercício 3.13 - Escreva um programa que converta uma temperatura digitada em # °C em °F. temperatura_celsius = float(input('\nInforme a temperatura em °C: ')) temperatura_fahrenheit = ((9 * temperatura_celsius) / 5) + 32 print('\n%.1f°C é igual a %.1f°F.\n' % (temperatura_celsius, temperatura_fahrenheit))
false
9222aa4054e45621c3069408745952dbf4420f7f
rayraib/holbertonschool-higher_level_programming
/0x06-python-classes/6-square.py
1,724
4.3125
4
#!/usr/bin/python3 class Square(): '''Represent a square''' def __init__(self, size=0, position=(0, 0)): '''Initialize the data for each instance object''' self.size = size self.position = position @property def size(self): '''Getter method - Get __size field value''' return self.__size @size.setter def size(self, value): '''Setter method - Sets __size field value''' if (isinstance(value, int) is False): raise TypeError("size must be an integer") elif value < 0: raise ValueError("size must be >= 0") else: self.__size = value @property def position(self): '''Getter method - get __position field data''' return self.__position @position.setter def position(self, value): '''Setter method - set __position field data''' if not isinstance(value, tuple) or len(value) != 2: raise TypeError("position must be a tuple of 2 positive integers") elif not isinstance(value[0], int) or value[0] < 0 or\ not isinstance(value[1], int) or value[1] < 0: raise TypeError("position must be a tuple of 2 positive integers") else: self.__position = value def area(self): '''Calculate area of the instance square''' return (self.size * self.size) def my_print(self): '''prints square with # character''' if self.size is 0: print() else: for k in range(self.position[1]): print() for i in range(self.size): print("{}{}".format(" " * self.position[0], "#" * self.size))
true
01869664a8e27caa1a989773a539097769c68fa2
poojataksande9211/python_data
/python_tutorial/excercise_3/practice_excercise_3/list_of_1st_and_last_5_element_sqr.py
353
4.15625
4
#Write a Python program to generate and print a list of first and last 5 elements where the values are square of numbers between 1 and 20 (both included). def square_first_last(l): lic=[] for i in l: lic.append(i**2) print (lic[:5]) print (lic[-5:]) num=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20] square_first_last(num)
true
37c6d27efc5a6c5cb4c841ca40614225f65da56a
poojataksande9211/python_data
/python_tutorial/excercise_5_dictionaries/update_method_dic.py
602
4.46875
4
#update method in dictionary :=update the dictionary with key and value pair user_info={ 'name':'pooja ganvir', 'age':45, 'last_name':'ganvir', 'fav_mov':['take off','majali'], } more_info={'state':'maharashtra','dist':['wardha','nagpur']} user_info.update(more_info) print(user_info) #---------------- # more_info={'name':'savita','state':'maharashtra','dist':['wardha','nagpur']} # user_info.update(more_info) #suppose name is present in dic1 so it will replace the name or update name of dic2 # print(user_info) #----------------------------- # user_info.update({}) # print(user_info)
false
e6c691f5f204a50ffd3166edbc121bc0efb0a840
poojataksande9211/python_data
/python_tutorial/excercise_2/func_square_no.py
319
4.21875
4
#Write a Python function to create and print a list where the values are square of numbers between 1 and 30 # total=0 # for i in range(1,31): # total=(i**2) # print(total) #.................................. def square(): total=0 for i in range(1,31): total=(i**2) print(total) square()
true
9199ffd962212b426f2551a5be5f333eee6e3b8a
poojataksande9211/python_data
/python_tutorial/excercise/string_empty.py
286
4.4375
4
#check empty or not # name="abc" # if name: # print ("string is not empty") # else: # print("string is empty") #...................................... name=input("enter your name :") if name: print(f"you type your name is {name}") else: print("you didnt type your name")
true
0edee2d20705544e8842784f5e6fd600f56c67b5
poojataksande9211/python_data
/python_tutorial/excercise_11_decorators/decorotors_intro2.py
804
4.5625
5
#decorators intro(inhance the functionality of other function) #decorators is a function which increse the functionality of other function # def decorator_function(any_func): # def wraper_func(): # print("this is awesome function") # any_func() # return wraper_func # def func1(): # print("this is function1") # def func2(): # print("this is function 2") # var=decorator_function(func2) # var() #--------------------------------------- #@ symbol use for the decorators def decorator_function(any_func): def wraper_func(): print("this is awesome function") any_func() return wraper_func @decorator_function #this is shortcut def func1(): print("this is function1") func1() @decorator_function def func2(): print("this is function 2") func2()
true
cb623927f373522fe0e167beb8ff95aca5bb39d4
poojataksande9211/python_data
/python_tutorial/excercise_6_sets/set_intro.py
645
4.1875
4
#what is set:unordered collecton of unique items,we can not store list,tuple,dictionary in set s={1,2,3,4,3,3} #repeated value count only at once print(s)#in set there is no key value #----------------------- #suppose we want to replace unique item in list use set method l=[1,2,3,4,5,6,4,4,4,5,6,4,8,9,2] # sa=set(l) sa=list(set(l)) print(sa) #---------- #add data to set s1={1,2,3,4,5} s1.add(6) s1.add(7) s1.add(6) print(s1) # remove method s1.remove(4) print(s1) #clear() method # s1.clear() # print(s1) #copy method s1_copy=s1.copy() print(s1_copy) #---------------- s2={1,1.0,2.9,"pooja","AMIT"}#1.0 not print bcoz 1.0 treat as 1 print(s2)
true
e4a019ddd36d6b824db10ea8e084075592d59d9b
poojataksande9211/python_data
/python_tutorial/excercise_8_args/args_with_normal_parameter.py
1,015
4.28125
4
#args with normal parameter # def multiply(*args): #parameter # multiply=1 # for i in args: # multiply *=i # return multiply # print(multiply(1,2,3,4)) #argument #---------------------------- # def multiply(num,*args): #parameter # multiply=1 # # print(num) # # print(args) # for i in args: # multiply *=i # return multiply # print(multiply(2,2,3)) #(first 2 is not a part of args its a part of num) #------------------------------------- # def multiply(num,*args): #parameter ######### # multiply=1 # # print(num) # # print(args) # for i in args: # multiply *=i # return multiply # print(multiply())#it gives an error(you have to pass 1 argument bcoz u define parameter num) #--------------------------------- def multiply(num1,num2,*args): #parameter multiply=1 # print(num) print(args) for i in args: multiply *=i return multiply print(multiply(2,2,3,4)) #you pass 2 parameter hence u have to pass 2 argument
true
e662e5a58beb8831d6d61dc6d3438a4b51111112
poojataksande9211/python_data
/python_tutorial/excercise_12_generators/write_first_generator.py
300
4.21875
4
#write first generator with generator function #generator can form by using two fun #1.generator func #2.generator comprehension def nums(n): for i in range(1,n+1): yield(i) # print(nums(10)) numbers=list(nums(10)) for num in numbers: print(num) # for num in numbers: # print(num)
true
5fdd68d4111c46230d39c350c0507f00c23d7381
poojataksande9211/python_data
/python_tutorial/excercise_5_dictionaries/summury.py
1,197
4.3125
4
#dictionry summury # d={'name':'pooja','age':23}#name and age are key....pooja and 24 are value # print(d)#there is no indexing in dictionary # d1=dict(name='harshit',age=23) # print(d1) d3={ 'name':'pooja', 'age':23, 'fav_mov':['ddlj','fun'], 'fav_song':['tu hi re','angat mazi ya'], } print(d3) #how to access data from dic print(d3['name']) # print(d1['age']) #add data to empty dic # empty_dic={} # empty_dic['key1']='value2' # empty_dic['key2']='value2' # print(empty_dic) #check key present in dic using in # if 'names' in d3: # print("present") # else: # print("not present") #how to iterated over dictionary for key,value in d3.items(): print(f"{key} and {value}") #print all keys # for i in d3: # print(i) #to print all values # for i in d3.values(): # print(i) #most common method in dict(get method) # print(d3['name']) # print(d3.get('name'))#method is used to acces key it returns none when key is not present in dic # print(d3.get('names')) #to delete item #pop ....take 1 argument which is key name # popped=d3.pop('name') # print(popped) # print(d3) #popitem...it delete randomely items popped_item=d3.popitem() print(popped_item) print(d3)
false
d9fbb76195ed392f905422669c9a4365f509ba1a
poojataksande9211/python_data
/python_tutorial/excercise_10_enumerate_function/zip_func_part_2.py
393
4.3125
4
#zip_func_Part_2 # l1=[1,2,3,4] # l2=[5,6,7,8] l3=[(1,5),(2,6),(3,7),(4,8)] #convert l3 to l1 l2 #zip with * operator # print(list(zip(*l3))) # l1,l2=list(zip(*l3)) # print(list(l1)) # print(list(l2)) #---------------------------------------- #program for find greatest of l1 l2 pair l1=[1,2,3,4] l2=[5,6,7,8] new_list=[] for pair in zip(l1,l2): new_list.append(max(pair)) print(new_list)
false
4e833d7a264be8537fefc9782785854b33389b1d
poojataksande9211/python_data
/python_tutorial/excercise/center_method.py
475
4.46875
4
name="harshit" #suppose we want to print *harshit* then use center method print(name.center(9,"*")) #(we wrote 9 bcz "harshit is a 7 character string +2 star means 9") print(name.center(11,"*")) print(name.center(11,"&")) print(name.center(13,"*")) name1="she is more beautifull and she is good dancer" #suppose we dont know the length of the string and we print *string* then 1st find the length print(len(name1)) print(name1.center(len(name1)+2,"*")) #(we want 2 star hence wrote 2)
true
70cedc7c5397d051ebd8409d86f0cc26869668fe
poojataksande9211/python_data
/python_tutorial/excercise_3/add_data_to_list.py
245
4.34375
4
# #add data to list # fruits=['mango','anar','peru'] # fruits.append('banana') #append method is used to add the items at last # print(fruits) #............................ fruits=[] fruits.append("grapes") fruits.append("manggop") print(fruits)
false
43fb29a993b7e7ac38ca61545213696ccf6f366c
jmplz14/PTC-programacion-tecnica-y-cientifica
/Sesion2/ejercicio2.py
452
4.1875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Oct 4 10:49:33 2019 @author: jose """ import math num_valores = 3 x1 = float(input("Introduzca el x1: ")) x2 = float(input("Introduzca el x2: ")) x3 = float(input("Introduzca el x3: ")) media = (x1+x2+x3)/num_valores sumatorita = (x1-media)**2 + (x2-media)**2 + (x3-media)**2 desviacion_tipica = math.sqrt(sumatorita/num_valores) print("La desviacion tipica es ", desviacion_tipica)
false
f1bb4bd2c3b030caa7128a2b96c02c0e52814dcb
svinodha/python-practice
/Divisors.py
327
4.28125
4
#Code to find the divisors of a given number. For ex, 13 is a divisor of 26 because 26 / 13 has no remainder number = int(raw_input("Enter a number: ")) number_range = range (1, number+1) new_list = [] for i in number_range : if (number % i) == 0: new_list.append(i) print "The divisors of %d are %s" %(number, new_list)
true
6791a2d708837df84cbd0b683ab143abeb65d853
iam3mer/NivelatorioEnAlgoritmia
/MetodosDeOrdenamiento/insertionSort.py
875
4.21875
4
#! /usr/bin/python2.7.8 # -*- coding: utf-8 -*- # Python program for implementation of InsertionSort import argparse from math import floor from time import clock def INSERTIONSORT(A): for j in range(1,len(A)): key = A[j] i = j-1 while i>=0 and A[i]>key: A[i+1] = A[i] i = i-1 A[i+1] = key #print(A) # Sorted list. # end INSERTIONSORT def ORDERDATAFILE(nums): parser = argparse.ArgumentParser() parser.add_argument("-f", "--file", help="Nombre del archivo a procesar.") args = parser.parse_args() with open(args.file) as file: data = file.read() for word in data.split(): nums.append(int(word)) t_ini = clock() INSERTIONSORT(nums) t_fin = clock() if args.file: print (args.file, (t_fin - t_ini)) # end READDATAFILE if __name__ == "__main__": nums = [] ORDERDATAFILE(nums)
true
be512898c8a41d93d18ebe72cf1e970216788841
RafidaZaman/Python-Lab-1
/Problem 2.py
628
4.46875
4
#2) Write a Python function that accepts a sentence of words from user and display the following: # a) Middle word # b) Longest word in the sentence # c) Reverse all the words in sentence #b) def find_longest_word(Sentence): longest_word = max(Sentence, key=len) print("Longest word : ",longest_word) return longest_word words = input('Please enter a few words') Sentence = words.split() find_longest_word(Sentence) #c) sentence="My name is Jacqueline Fernandez Dsouza" def reversed_words(revers): return ' '.join(word[::-1] for word in revers.split()) print("Reversed Sentence :",reversed_words(sentence))
true
060428298682705dccc5964d5af833605a61693d
maoxifeng/gitex
/fold2/c3.py
1,283
4.125
4
# -*- coding: utf-8 -*- # funtion of class # function 1 class Student( object): ''' this is a Student class ''' count = 0 books = [] def __init__( self, name, age): self.name = name self.age = age self.__address = 'Shanghai' def printInstanceInfo( self): print "%s is %d years old" %( self.name, self.age) pass wilber = Student( "Wilber", 28) wilber.printInstanceInfo( ) # function 2 class Student( object): ''' this is a Student class ''' count = 0 books = [] def __init__( self, name, age): self.name = name self.age = age @classmethod def printClassInfo( cls): print cls.__name__ print dir( cls) pass Student.printClassInfo( ) wilber = Student( "Wilber", 28) wilber.printClassInfo( ) # function 3 class Student( object): ''' this is a Student class ''' count = 0 books = [] def __init__( self, name, age): self.name = name self.age = age @staticmethod def printClassAttr( ): print Student.count print Student.books pass Student.printClassAttr( ) wilber = Student( "Wilber", 28) wilber.printClassAttr( )
false
9ccdf203bbc7d3de74ee95c1458e6960adcf670d
Alfredo369/My-homework-assigment-4
/hmwk_4/hmwk_4.py
1,168
4.125
4
# problem 2-1 message = "Hello to whom ever is reading this" print(message) # problem 2-2 message = "This is problem 2-2" print(message) # problem 2-3 first_name = "alfredo" last_name = 'nino' full_name = first_name + " " + last_name print(full_name) message = 'Hello, ' + full_name.title() + '!'' ' "Would you like to learn some Python today?" print(message) # problem 2-4 first_name = "alfredo" last_name = 'nino' full_name = first_name + " " + last_name print(full_name.upper()) print(full_name.lower()) print(full_name.title()) # problem 2-5 quote = 'Ben Parker once said, "Great power comes with great responsibilities."' print(quote) # problem 2-6 famous_person = 'William Shakespeare' massage_1 = ' once said, "Frailty, thy name is woman!"' print(famous_person + massage_1) # problem 2-7 name = '\t' 'Bob ' '\n' '\t' "flanders" print(name) favorite_language = 'python ' favorite_language.rsplit() # problem 2-8 print(2 + 6) print(4 * 2) print(10 - 2) print(16 / 2) # problem 2-9 favorite_number = 118 message = 'your favorite number is ' + str(favorite_number) print(message) # problem 2-10 # Alfredo Nino homework 4 class ID 18
false
0affe12fb8bedc9956d601ea15c1709dcd97738a
ALMR94/Practicas-python-6
/9 - Lista sin repeticiones.py
646
4.15625
4
# -*- coding: cp1252 -*- """Antonio Li Manzaneque- 1 DAW - Prctica 6 - Ejercicio 9 - Escribe un programa que permita crear una lista de palabras y que, a continuacin, cree una segunda lista con las palabras de la primera, pero sin palabras repetidas (el orden de las palabras en la segunda lista no es importante).""" a=(int(raw_input("Cuntas palabras tiene la lista? "))) n=1 li=[] for n in range (a): print "Dime la palabra",n+1 b=raw_input() n+1 li.append(b) print "La primera lista creada es",li for i in range(len(li)-1, -1, -1): if li[i] in li[:i]: del(li[i]) print "La lista sin repeticiones es",li
false
468797d349f623e8760690024acb291c803250b9
czchuang/hackbright_intro
/quiz_dict_file.py
1,147
4.15625
4
#counts how many times a letter appears in a file def counts_letters(doc): with open(doc) as doc: my_doc = doc.read().lower() letter_counts = {} alphabet = "abcdefghijklmnopqrstuvwxyz" for character in my_doc: if character in alphabet: if character not in letter_counts: letter_counts[character] = 1 elif character in letter_counts: letter_counts[character] += 1 return letter_counts print counts_letters("one_fish_two_fish.txt") #counts how many times each word appears in a file def counts_words(doc): with open(doc) as doc: my_doc = doc.read().lower() my_doc = my_doc.replace("\n"," ") punctuation = ".,!;`~-:;'/?!@3$%^&*" word_counts = {} no_punctuation = "" #strips punctuation from text file for character in my_doc: if character not in punctuation: no_punctuation += character #splits text file into list no_punctuation = no_punctuation.split() #counts words in text file for word in no_punctuation: if word not in word_counts: word_counts[word] = 1 elif word in word_counts: word_counts[word] += 1 return word_counts print counts_words("one_fish_two_fish.txt")
true
dcc63568bb03d4bb1a71ce10e5949d6577fa6b5d
parshuramsail/PYTHON_LEARN
/paresh27/a5.py
413
4.25
4
#write a program that prints the integers from 1 to 100.but for multipkes of three print "fizz" instead of numbers . #and for the mutiples of five print"buzz".for numbers which are multiples of both three and five print'fizzbuzz' for i in range(1,101): if i%3==0 and i%5==0: print("FIZZBUZZ") elif i %3==0: print("FIZZ") elif i % 5==0: print('BUZZ') else: print(i)
true
9092c61f5cee29a049674b4d2854c6d7e2879220
parshuramsail/PYTHON_LEARN
/paresh33/a3.py
203
4.3125
4
#write a program to reverse a string def reverse(str1): rstr1="" index=len(str1) while index>0: rstr1+=str1[index-1] index=index-1 return rstr1 print(reverse("1234abcd"))
true
1fe0c6f1426c97fd5dc4c0ba1b0a7d30d7705d1f
parshuramsail/PYTHON_LEARN
/paresh33/a6.py
477
4.15625
4
# accept string and calculate the upper and lower case letters. def string_test(s): d={"UPPER_CASE":0,"LOWER_CASE":0} for c in s: if c.isupper(): d["UPPER_CASE"]+=1 elif c.islower(): d["LOWER_CASE"]+=1 else: pass print("original string:",s) print("no of upper case characters:",d["UPPER_CASE"]) print("no of lower case characters :",d["LOWER_CASE"]) string_test("the quick brown fox")
true
34a8dca67b8312e63ceec83481ae652bb06278e6
peterkabai/python
/algorithm_problems/hackerrank_kattis/coin_change.py
1,118
4.15625
4
def coin_itterative(coins, total): # First the list of coin values are sorted, because we have to # itterate through them smallest to largest. coins.sort() # The combinations have a length of total plus one # because we can also have one way of selecting a value of zero. # So, the zero index is also set. combinations = [0] * (total + 1) combinations[0] = 1 # We itterate through each coin, smallest to largest. for value in coins: # Convert the str from the input to an int value = int(value) # For each coin we see how many ways we can get each total for index in range(len(combinations)): # If the value of the coin is less than the total we want, # then we can possibly use it in a combination if index >= value: # The number of combinations is increased combinations[index] += combinations[index - value] return combinations[total] # Read the input total = int(input()) num_coins = int(input()) coins = input().split(" ") print(coin_itterative(coins, total))
true
51f08923c447c0c3c7578bd0fc671637be0444ac
kammradt/faculdade-matematica-aplicada
/sistemas-lineares-interativo/linear.py
2,969
4.25
4
# Importa uma biblioteca Python2 que trabalha com equacoes matematicas import numpy as np # Sera tomado como exemplo o seguinte sistema linear: # x -2y -2z = -1 # x -y +z = -2 # 2x +y +3z = 1 # Linha 1 = x -2y -2z = -1 # Linha 2 = x -y +z = -2 # Linha 3 = 2x +y +3z = 1 # O programa recebe do usuario a quantida de equacoes que ele deseja inserir (Serao transformadas em uma matriz depois). # Nesse caso, temos 3 linhas, entao qtd_linhas = 3 qtd_linhas = int(input('Digite a quantidade de linhas do sistema linear desejado: ')) # Nesse caso, temos tambem 3 incognitas, entao qtd_variaveis = 3 # O programa recebe a quantidade de incognitas que existira em cada uma das linhas. qtd_variaveis = int(input('Digite a quantidade de variaveis (incognitas): ')) print('\n') # Agora o programa ira montar dinamicamente, com a ajuda do usuario. # O objetivo e montar a seguinte matriz (baseado no sistema linear usado como exemplo) # | 1 -2 -2 | -1 | # | 1 -1 1 | -2 | # | 2 1 3 | 1 | matriz = [] respostas = [] for numero_linha, linha in enumerate(range(qtd_linhas)): # Para cada linha informada, sera criada uma lista [] que tera dentro dela armazenada cada uma das variaveis daquela linha. # Ou seja, linha_construida ao fim do range() de 3 (que e qtd_linhas), sera: linha_construida = [1, -2, -2] linha_construida = [] for numero_variavel,variavel in enumerate(range(qtd_variaveis)): entrada = int(input('Digita a variavel '+str(numero_variavel+1)+' da linha: ' + str(numero_linha+1)+': ')) linha_construida.append(entrada) # Recebemos o valor de x, y, z para uma determinada linha, e entao colocamos dentro de linha_construida resposta = int(input('Digita a resposta da linha: ' + str(numero_linha+1)+': ')) # Aqui recebemos o valor para a coluna da direita. Por exemplo, para a primeira linha [1, -2, -2], reposta sera = -1 print('\n') respostas.append(resposta) # Resposta se encontra como uma matriz vetor de um elemento [-1], porem assim que o 'for' continuar, ira receber -2 e por fim 1 matriz.append(linha_construida) # Apos as 3 variaveis serem recebis pelo usuario, uma linha sera montada, como dito anteriormente. A primeira linha_construida sera: # [1, -2, -2]. Dentro de matriz, estamos colocando essa linha. # Matriz sera uma lista com varias listas dentro. Ou seja, no caso do exemplo, uma lista com 3 'listas/linhas dentro'. # Ao fim, 'matriz' possui a seguinte configuracao = [[1, -2, -2],[1, -1, 1],[2, 1, 3]] # E 'respostas' possui a seguinte configuracao = [-1, -2, 1] # Apenas usamos as matrizes contruidas para informar ao numpy qual matriz e qual. # A = matriz montada pelo usuario de incognitas -> [[1, -2, -2],[1, -1, 1],[2, 1, 3]] # B = matriz montada pelo usuario de respostas -> [-1, -2, 1] A = np.array(matriz) B = np.array(respostas) # Resolucao usando a biblioteca print('Resposta: ') print(np.linalg.solve(A, B ))
false
e49a28a89b02a828bdb1b00c0b38247d48318097
ryndovaira/leveluppythonlevel1_300321
/topic_08_functions/examples/13_default_append_2.py
810
4.375
4
a = 55 # немутабельный int lst_tmp = [1, 2, 3] # мутабельный (изменяемый) list def append_default(element=a, lst=[], lst2=lst_tmp): lst.append(element) lst2.append(element) # изменили состояние переменной lst_tmp return element, lst, lst2 print(f'append_default() = {append_default()}') # (55, [55], [1, 2, 3, 55]) print(f'lst_tmp = {lst_tmp}\n') # [1, 2, 3, 55] a = 77 lst_tmp.append('a') print(f'append_default() = {append_default()}') # (55, [55, 55], [1, 2, 3, 55, 'a', 55]) print(f'lst_tmp = {lst_tmp}\n') # lst_tmp = [1, 2, 3, 55, 'a', 55] print(f'append_default() = {append_default()}') # (55, [55, 55, 55], [1, 2, 3, 55, 'a', 55, 55]) print(f'lst_tmp = {lst_tmp}\n') # [1, 2, 3, 55, 'a', 55, 55]
false
06afbd0a0b359a1e17533943fa538cdf3ebe4652
ryndovaira/leveluppythonlevel1_300321
/topic_09_enum/examples/2_enum_with_auto_for.py
849
4.25
4
from enum import Enum, auto # класс Animal - это перечисление class Animal(Enum): # элементы перечисления, константы (не изменяются) # элементы имеют имена и значения # функция auto() автоматически присваивает элементу значение от 1 до N-1 с шагом 1 cat = auto() # 1 dog = auto() # 1 + 1 = 2 frog = auto() # 2 + 1 = 3 duck = auto() # 3 + 1 = 4 if __name__ == '__main__': # перечисления — это итерируемые объекты, т.е. все элементы можно перебрать в цикле for element in Animal: print(element) print(f"name = {element.name}") print(f"value = {element.value}\n")
false
05fdfbb5523842e00b3ce8a05687735f85245994
ryndovaira/leveluppythonlevel1_300321
/topic_02_syntax/practice/loop_2_sum_numbers.py
1,106
4.125
4
""" Функция sum_numbers. Принимает строку string содержащую целое число больше или равное 0. Пример: '123', '00', '0603', '0054310003323566767'. Вернуть сумму этих чисел. Пример: string='0603', result=9 (0+6+0+3). Строка не должна содержать пробелов или любых других символов, то есть должна корректно конвертироваться в int. Подсказка: isdigit() Если строка не соответствует этим требованиям, то вернуть None. Пример (с ошибкой): '765eew', '5 57 767', '$ewe23', '664.232', ''. """ def sum_numbers(string): # if not string: # return None if not string.isdigit(): return None my_sum = 0 for my_symbol in string: # if not my_symbol.isdigit(): # return None my_sum += int(my_symbol) return my_sum if __name__ == '__main__': print(sum_numbers("4*6")) print("0603".isdigit())
false
62b50201f73172ddbf12809ff9a16e075743086c
AndreySperansky/TUITION
/_STRUCTURES/NUMBER/SUM/best_sum_of_3num.py
1,038
4.5
4
"""3.Реализовать функцию my_func(), которая принимает три позиционных аргумента, и возвращает сумму наибольших двух аргументов.""" def bestsum_two(num1, num2, num3): """ Функция принимает три параметра, используется динамическая типизация :param nam1: Число (int, float) :param num2: Число (int, float) :param num3: Число (int, float) :return: Сумма двух наибольших из трех """ max_num = max(num1, num2, num3) + max(min(num1, num2), min(num1, num3), min(num2, num3)) #Alternative # max_num = '' # if num1 > num2: # if num2 > num3: # max_num = num1 + num2 # else: # max_num = num1 + num3 # else: # if num2 < num3: # max_num = num2 + num3 # return print(max_num) a = 3 b = 5.5 c = 7.2 bestsum_two(a, b, c)
false
ea15536e26e6d0e95f0abe0b36fc654c9e7240fa
AndreySperansky/TUITION
/_STRUCTURES/NUMBER/Complex/cmoplex_sum_mult_1.py
767
4.25
4
''' В соответствии с математическими правилами, сумма и произведение определенных комплексных чисел будет выглядеть так: a + b = (a.x + b.x) + (a.y + b.y)i a * b = (a.x * b.x - a.y * b.y) + (a.x * b.y + a.y * b.x)i Для описания комплексных чисел создадим структуру данных. Она будет содержать два поля, описывающих действительную и мнимую части. ''' # Вариант 1. Использование встроенного типа данных complex: a = input() b = input() a = complex(a) b = complex(b) suma = a + b mult = a * b print(suma) print(mult)
false
3de7c4d0d367aa938d0387ecaf14d7e42dedb926
AndreySperansky/TUITION
/FUNCTIONAL/VarArgs/keywords_only.py
670
4.1875
4
"""A byte of Python""" def total(initial=5, *numbers, extra_number): """После параметра типа'*' (кортеж) подразумевается только параметр типа '**' (словарь) даже если перед параметром отсутствуют две звездочки""" count = initial for number in numbers: count += number count += extra_number print(count) total(10, 1, 2, 3, extra_number=50) #total(10, 1, 2, 3) # Вызовет ошибку, поскольку мы не указали значение # аргумента по умолчанию для 'extra_number'.
false
465f0e281c13006d1ade389789fc62d6eb84a457
AndreySperansky/TUITION
/And_Or/or_true.py
577
4.1875
4
# Добавление элемента в список # Классический способ def add_to_list(input_list = None): if input_list is None: input_list = [] input_list.append(2) return input_list result = add_to_list([0,1]) print(result) result = add_to_list() print(result) # Через OR def add_to_list(input_list = None): # используем свойство or вместо условие input_list = input_list or [] input_list.append(2) return input_list result = add_to_list([0,1]) print(result) result = add_to_list() print(result)
false
bd12e119f12c5affdfbb8af4a9decb3ff7893fb2
AndreySperansky/TUITION
/FUNCTIONAL/Sorted/Sorted_1.py
816
4.25
4
numbers = [1, 5, 3, 5, 9, 7, 11] # Сортировка по возрастанию print(sorted(numbers)) # Сортировка по убыванию print(sorted(numbers, reverse = True)) # Набор строк names = ['Max', 'Alex', 'Rate',] # сортировка по алфавиту print(sorted(names)) # Город, численность населения cities = [('Москва', 100000), ('Лас=Вегас', 500000), ('Астрахань', 20000)] # Такая сортировка сработает по алфавиту print(sorted(cities)) # как отсортировать по численности населения? def sort_population(city): return city[1] print(sorted(cities, key = sort_population)) # Lambda print(sorted(cities, key = lambda city: city[1]))
false
f9d9b3f46dbb09b43907a983d551c83c18daddf9
AndreySperansky/TUITION
/FUNCTIONAL/Map/miles_to_km.py
591
4.40625
4
def miles_to_kilometers(num_miles): """ Converts miles to the kilometers """ return num_miles * 1.6 """MAP сфункцией созданной пользователями""" mile_distances = [1.0, 6.5, 17.4, 2.4, 9] kilometer_distances = list(map(miles_to_kilometers, mile_distances)) print(kilometer_distances) # [1.6, 10.4, 27.84, 3.84, 14.4] # То же самое только с lambda аункцией mile_distances = [1.0, 6.5, 17.4, 2.4, 9] kilometer_distances = list(map(lambda x: x * 1.6, mile_distances)) print(kilometer_distances) # [1.6, 10.4, 27.84, 3.84, 14.4]
false
ca6450dd6c5e0cf8d536aa9a0d039a8a6aa90bf6
AndreySperansky/TUITION
/RECURSION/Super_Recursion/task_3/task_3_1.py
965
4.1875
4
""" 3. Сформировать из введенного числа обратное по порядку входящих в него цифр и вывести на экран. Например, если введено число 3486, то надо вывести число 6843. Подсказка: Используйте арифм операции для формирования числа, обратного введенному Пример: Введите число: 123 Перевернутое число: 321 ЗДЕСЬ ДОЛЖНА БЫТЬ РЕАЛИЗАЦИЯ ЧЕРЕЗ ЦИКЛ """ try: NUM = abs(int(input("Введите число: "))) NUM_REV = 0 while NUM > 0: digit = NUM % 10 NUM = NUM // 10 NUM_REV *= 10 NUM_REV = NUM_REV + digit print("Реверсное число равно: ", NUM_REV) except ValueError: print('Ошибка, нужно ввести целое число!')
false
8c16d5d792199d53d370c1385d681b4dc33fd6c2
AndreySperansky/TUITION
/_STRUCTURES/Modul_Collection/examples/oredereddict_3.py
859
4.25
4
from collections import OrderedDict """В Python 3.5 и более ранних обычный dict, вы заметите, что данные в нем неупорядоченные""" NEW_DICT = {'python': 3, 'java': 4, 'perl': 1, 'javascript': 2} print(NEW_DICT) """Бывают ситуации, когда нужно выполнить цикл над ключами в словаре в определенном порядке. Например, нужно отсортировать ключи, чтобы перебрать их по порядку.""" KEYS = NEW_DICT.keys() KEYS = sorted(KEYS) for key in KEYS: print(key, NEW_DICT[key]) # теперь OrderedDict DCT = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2} NEW_DICT = OrderedDict(sorted(DCT.items())) print(NEW_DICT) for key in NEW_DICT: print(key, NEW_DICT[key])
false
05a437f3f45155caafbece09078c8ae4347aa8e3
AndreySperansky/TUITION
/CONDITIONS/Ternary_Operator/ternary_compare_ab.py
588
4.3125
4
# Программа Python для демонстрации вложенного тернарного оператора a, b = 10, 20 print("Both a and b are equal" if a == b else "a is greater than b" if a > b else "b is greater than a") # Вышеуказанный подход можно записать так: # Программа Python для демонстрации вложенного тернарного оператора a, b = 10, 20 if a != b: if a > b: print("a is greater than b") else: print("b is greater than a") else: print("Both a and b are equal")
false
9c936ae04a78400a7e8a2dd5c38239e353cf0973
chrisbonifacio/hello-world
/LearningTimeAndDates/LearningTimeAndDates/LearningDateTime.py
2,496
4.8125
5
#If I want to know how many days until my birthday, first I need today's date #The datetime class allows us to get the current date and time #The import statement gives us access to #the functionality of the datetime class import datetime #today is a function that returns today's date currentDate = datetime.date.today() print(currentDate) # You can access different parts of the date print(currentDate.year) print(currentDate.month) print(currentDate.day) #What date does 12/06/09 represent? #What if you want to display the date with a specific format? #Different countries and different users like different date formats, #often the default isn't what you need #There is always a way to handle it, but it will take a little time and extra code #strftime allows you to specify the date format # %b: month abbreviated # %B: full month name # %Y: full year # %y: 2 digit year # %a: day of week abbreviated # %A: day of week # Full list at strftime.org print (currentDate.strftime("%a %b %d, %Y")) # Could you print out a wedding invitation? print(currentDate.strftime ("Please attend our event on the evening of %A the 3rd, month of %B, in the year %Y")) #What if I don't want English? #In programmer speach we call that Localization #By default the program uses the language of the machine it's running on #But... since you can't always realy on PC settings it is possible to force #Python to use a particular language. #It just takes more time and more code. If you need to do that, check out #the babel Python library at http://babel.pocoo.org/ birthday = input("What is your birthday?") print("Your birthday is " + birthday) #How do we convert input from a string into a date? birthdate = datetime.datetime.strptime(birthday, "%m/%d/%Y") #Why did we list datetime twice? #Because we are calling the strptime function #which is part of the datetime class #which is in the datetime module print("Your birth month is " + birthdate.strftime("%B")) import datetime currentDate = datetime.date.today() userInput = input("Please enter your birthday: ") birthday = datetime.datetime.strptime(userInput, "%m/%d/%Y") print(birthday) #But what if the user doesn't enter the date in the format I specify in strptime? #Your code will crash so... #Tell the user the date format you want birthday = input("What is your bithday? (mm/dd/yyyy)") print(birthday) #You can also add Error Handling
true
cfd4444b2eedc6a3ea0ba16dd719f419ab6fdfc6
jb-neubauer/Anti-virus
/python/linuxconfig.org/lesson10.py
712
4.375
4
if (5 ** 2 >= 25): print("It's true!") print("If is great") if( (5 **2 >= 25) and (4 * 2 < 8) or (35 / 7 > 4) ): print("Booleans make If even more powerful") if (not (5 ** 2 >= 25)): print("biarro") else: print("Check your math") if ( ( 5 ** 2 <= 25) and (35 / 7 >4) and (4 ** 2 > 10) and (3 ** 2 < 10) ): print("Everything looks good.") else: print("Your math is a little off") if (5 ** 2 > 25): print("It is greater") elif (5 ** 2 < 25): print("It is less") elif (5 ** 2 == 25): print("It is equal") else: print("That makes no sense") a = 10 b = 15 c = 20 d = 25 if (a > b): if (a + b >= d): d -= c elif (a + b >= c): c -= b else: b -= a elif (b > c): print(b - c) else: print(d)
false
32a79498ac057c3f6f65d57d47ad8a8b49f2e28c
aparajita2508/learning-python
/script/Exe30.py
489
4.21875
4
# Here comes elif :-) people = 30 cars = 40 buses = 15 if cars > people and #people < buses: print "We should take the cars" elif cars < people: print "We should not take the cars" else: print "We can't decide.." if buses > cars: print "there are too many buses.." elif buses < cars: print "May be we could take the buses." else: print "We still can't decide.." if people > buses: print "Alright, let's just take the buses." else: print "Fine, let's stay home then."
true
412f74994424d4faba394af1a6bb8041a69a9610
roy23c/python-art
/angle_art.py
1,265
4.25
4
import turtle import random # reads in input and checks for numeric input def numeric_input(num_str): input_string = input('input ' + num_str + ': ') while not input_string.isnumeric(): print(num_str + ' must be an integer') input_string = input('input ' + num_str + ': ') return int(input_string) # generates random rgb color def generate_color(): random.seed() r = random.randint(0, 255) g = random.randint(0, 255) b = random.randint(0, 255) return r, g, b # draw a pattern with specified angle and iteration number def draw_specific_pattern(angle, iterations): turtle.title('Patterns') turtle.setup(1280, 1200) turtle.hideturtle() turtle.bgcolor('black') turtle.colormode(255) turtle.speed(40) print('drawing pattern...') for i in range(0, iterations): turtle.color(generate_color()) turtle.forward(2 * i) turtle.right(angle) print('pattern drawn') turtle.done() # draw a pattern with a random angle def draw_random_pattern(): ang = random.randint(0, 360) draw_specific_pattern(ang, 400) angle_ = numeric_input('angle') iterations_ = numeric_input('iterations') draw_specific_pattern(angle_, iterations_) # draw_random_pattern()
true
4e793edacd68d156bebd0e51d10ad86ec7522fd0
Incogniter/incognito
/conditions.py
2,038
4.15625
4
#conditon or comparison (AND,OR) #AND has higher predcdence than OR age = int(input('Enter the age:')) if (age > 16 and age < 65): print("have a good day") else: print('Enjoy your day') print() age = int(input('Enter the age:')) if(age < 16 or age > 65): print('have a good day') else: print("go do ur work") print() #challange Name = input('Enter the name:') Age = int(input('Enter the age:')) if(Age >= 16 and Age <= 31 ): print('Welcome to the holiday {0}'.format(Name)) else: print("oops only 18-31 are allowed sorry") print() #boolean expressions true or false #AND has higher predcdence than OR #AND operator stop checking as soon as it finds a false #OR operator stops checking as soon as it finds a true day = "sunday" temperature = 30 raining = False if((day == "sunday" and temperature < 27) or raining): print('go swiming') else: print('learn python') #in boolean expression all zero are considered to be false #constant and zero of any numeric types and empty is considered to be false if 0: print('True') else: print('false') print() #name is an empty string name = input('please enter your name:') if name: print('hello {}'.format(name)) else: print('Motherfucker just enter the name') name =input('Enter your name') print('hello {}'.format(name)) print() today = "friday" print('day' in today) print('fri' in today) #here in operator evaluates the first thing exists in the second print("----------") #checking IN and NOT IN #IN Mylove = "sheryl priscilla" letter = input('Enter the letter you wanna find:') if (letter in Mylove): print('{0} is in {1}'.format(letter,Mylove)) else: print("SORRY I dont need any letter that wasnt included in My love") print() #NOT IN activity = input('whats your plan today?') if ('movie' not in activity.casefold()): print('I want to watch movie') else: print("I want to learn python")
true
02b686990d4f61cf4639203132e10b4878b37eee
Incogniter/incognito
/Write.py
1,214
4.1875
4
# # creates a txt file using python # cities = ["Nagercoil", "marthandam", "Thuckalay", "Monday market", ] # with open("cities.txt", 'w') as city_file: # for city in cities: # print(city, file=city_file) # use "file" function to create as a txt file cities = [] with open("cities.txt", 'r') as city_file: for city in city_file: cities.append(city.strip('\n')) # .strip(\n) os used to remove the space between the lines and renoves \n from the list print(cities) for city in cities: print(city) print("_"*50) # To understand .strip() , it removes the values only from the start and end of the string print("abino".strip('a')) print("abino".strip('i')) print("abino".strip('o')) print("_"*50) imelda = "More Mayhem", "Imelda MAy", "2011", ( (1, "Pulling the Rug"), (2, "Psycho"), (3, "Mayhem"), (4, "Kentish Town Waltz")) with open("imelda3.txt", 'w') as imelda_file: print(imelda, file=imelda_file) with open("imelda3.txt", 'r') as imelda_file: contents = imelda_file.readline() imelda = eval(contents) # eveluvate = eval print(imelda) title, artist, year, tracks = imelda print(title) print(artist) print(year) print(tracks)
false
3aa03399061d420e02efe3adea64a3b8f11b382f
Incogniter/incognito
/panindrome.py
989
4.25
4
#palindrome def palindrome_string(string): backward = string[: : -1].casefold() return backward== string.casefold() #word = input("enter the string to be checked:") #if palindrome_string(word): # print("{} is a palindrome".format(word)) #else: # print("{} is not a palindrome".format(word)) def palindrome_sentence(sentence): string= "" for char in sentence: #The isalnum() method returns True if all the characters are alphanumeric,/n # meaning alphabet letter(a - z) and numbers(0 - 9). #Example of characters that are not alphanumeric: (space)! # %&? etc if char.isalnum(): string += char #backward = string[: : -1].casefold() #return backward== string.casefold() return palindrome_string(string) word = input("enter the sentence to be checked:") if palindrome_sentence(word): print("{} is a palindrome".format(word)) else: print("{} is not a palindrome".format(word))
true
1476f658a6b1b35f5cabbdc501c4d60034ea56c1
Incogniter/incognito
/learned.py
261
4.15625
4
#zip() function even = [2, 4, 6, 8] odd = [1, 3, 5, 7] products =[] #zip() function is used in matrix(list and tuples) arithmetic operation for num1,num2 in zip(even,odd): products.append(num1 * num2) sum = sum(products) print(products) print(sum)
true
0cc4154295cd3a8983d21ab65a7e484254664969
csyu1/project-euler
/0004.py
430
4.15625
4
from itertools import product from utils import is_palindrome three_digits = range(100, 1000) """ A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers. """ print(max((i * j, i, j) for i, j in list(product(three_digits, three_digits)) if is_palindrome(i * j)))
true
36319494c6568435b02a1cd7903cefbce8fbbacf
MarquezLuis96/CompThink_Python
/04 - Structured Data, Mutability & High Level functions/01 - Functions like objects/obj_functions.py
1,314
4.59375
5
# Date: 2020/11/017 # Author: Luis Marquez # Description: # This is a simple program to learn about how to use a function like an object # # #mult_x_2: This function return the n number multiplied by 2 def mul_x_2(n): """ This function return the n number multiplied by 2 The n number is the number that will be rmultiplied This function return the value after the operation Example: mult-x_2(2) -> 4 """ return n*2 #plus_x_2: This function return the n number multiplied by 2 def plus_x_2(n): """ This function return the n number plus 2 The n number is the number that will be plused This function return the value after the operation Example: plus_x_2(3) -> 5 """ return n+2 #operation: This function make the operation def op(f, numbers): results = [] for number in numbers: result = f(number) results.append(result) return results #Run: This is the function in which we'll run other functions written on this program def run(): """ This funtion run other functions written on our program Doesn't have any parameter Doesn't return anything """ # #Main: This is the main function of the program if __name__ == "__main__": run()
true
604517a01a0d113190118a1542bd380db6e408c0
MarquezLuis96/CompThink_Python
/02 - Numeric Programs/01 - Brute-force Search/Exact_Divisor_(Brute-force_Search).py
810
4.25
4
# Date: 2020/11/05 # Author: Luis Marquez # Description: # This program evaluates an exact divisor for a number using # the Brute-Force Search Algorithm, modularizing the solution # #validate def validate(): pass #e_divisor(): It's the foundamental function of the program def e_divisor(): #candidate candidate = 1 #number to evaluate number = int(input(f"\nType an integer number to find its exact divisor.\nNumber:")) print(f"\n") if (number == 0): print(f"0 doesn't have a divisor") else: while (candidate <= number): if (number%candidate == 0): print(f"{number}/{candidate} = {number/candidate}\n") candidate += 1 #run def run(): e_divisor() #main() if __name__ == "__main__": run()
true
f8fd70a54a804b7d3e0ec4ae145108806993f676
Anri-Lombard/python-course
/Section4/c57ch1.py
284
4.25
4
sentence = input("Please write any sentence you want with random words capitalized, then I will try to extract the " "capital letters: ") uppercase_letters = "" for char in sentence: if char.isupper(): uppercase_letters += char print(uppercase_letters)
true
f90dd7d29f21e6c62143b25505bf88a4bbe9b881
gerardoojeda/Python
/CLASS7_IFESLE&CONDITIONS_EDXCOURSE.py
2,674
4.34375
4
import sys # Condition Equal a = 5 a == 6#will return False # Greater than Sign i = 6 i > 5#will return true # Inequality Sign i = 2 i != 6#will return true # Use Equality sign to compare the strings "ACDC" == "Michael Jackson"#would return false # Compare characters 'B' > 'A'#this would use the ASCII values in which b is bigger tha a so would return True #Note: Upper Case Letters have different ASCII code than Lower Case Letters, # which means the comparison between the letters in Python is case-sensitive. #-------------------------------------------------------------------------------------------------------- # If statement example age = 19 #age = 18 # expression that can be true or false if age >18: # within an indent, we have the expression that is run if the condition is true print("you can enter") # The statements after the if statement will run regardless if the condition is true or false print("move on") #------------------------------------------------------------------------ # Else statement example age = 18 # age = 19 if age > 18: print("you can enter") else: print("go see Meat Loaf") print("move on") #---------------------------------------------------------------- # Elif statment example age = 18 if age > 18: print("you can enter") elif age==18: print("go to see pink floyd") else: print("go see Meat Loaf") print("move on") #---------------------------------------------------------------------------- # Condition statement example album_year = 1983 album_year = 1970 if album_year > 1980: print("album is older than 1980") print('do something..') #---------------------------------------------------------------------------------- # Condition statement example #album_year = 1983 album_year = 1970 if album_year > 1980: print("Album year is greater than 1980") else: print("less than 1980") print('do something..') #----------------------------------------------------------------------------------- #and condition # Condition statement example album_year = 1980 if (album_year > 1979) and (album_year < 1990): print("Album year was in between 1980 and 1989") print("") print("Do Stuff..") #------------------------------------------------------------------------------- # Condition statement example #or statement album_year = 1980 if(album_year < 1980) or (album_year > 1989): print ("Album was not made in the 1980's") else: print("The Album was made in the 1980's ") #------------------------------------------------------------------------------ #nnot album_year = 1986 if not (album_year == 1984): print ("Album year is not 1984") else: print("Album is from 1984")
true
2c77c6d34b3ee78dd3e12adce82eb87ee0bb1814
diego-guisosi/python-norsk
/02-beyond-the-basics/03-decorators/01-functions.py
977
4.3125
4
# functions can be defined inside other functions: local functions # everytime the outer function runs, the inner function is created again and assigned to last_letter store = [] def sort_by_last_letter(strings): # local function below def last_letter(s): return s[-1] store.append(last_letter) print(last_letter) return sorted(strings, key=last_letter) if __name__ == '__main__': sorted_by_last_letter = sort_by_last_letter(['hello', 'from', 'a', 'local', 'function']) sorted_by_last_letter = sort_by_last_letter(['hello', 'from', 'a', 'local', 'function']) sorted_by_last_letter = sort_by_last_letter(['hello', 'from', 'a', 'local', 'function']) print(sorted_by_last_letter) print(store) # it's important to know that local functions are not members of the containing functions # they are only function name binding on the containing function body # so, this kind of call does not work: sort_by_last_letter.last_letter
true
db0efd272157bc6bb6793c89c95df36daaebdc9e
diego-guisosi/python-norsk
/02-beyond-the-basics/03-decorators/05-nonlocal-var-bindings.py
1,052
4.1875
4
import time message = 'global' def enclosing(): message = 'enclosing' def local(): nonlocal message message = 'local' print('enclosing message', message) local() print('enclosing message', message) # Sample usage of nonlocal. def make_timer(): """ Create a function whose result is the elapsed time between the created function calls""" last_called = None def elapsed(): nonlocal last_called now = time.time() if last_called is None: last_called = now return None result = now - last_called last_called = now return result return elapsed if __name__ == '__main__': print('global message', message) enclosing() print('global message', message) print() timer = make_timer() print(timer()) # Returns nothing, since it's the first call print(timer()) # Returns the elapsed time between the first and second call print(timer()) # Returns the elapsed time between the second and third call
true
592d9fb68431336c8bc5d78b9cea48bc71777891
diego-guisosi/python-norsk
/02-beyond-the-basics/02-functions/forwarding_arguments.py
833
4.21875
4
# extended call sintax is commonly used to forward all arguments of a function to other functions def trace(f, *args, **kwargs): """ Traces arguments and return values of other functions """ print("args = {}".format(args)) print("kwargs = {}".format(kwargs)) r = f(*args, **kwargs) print("return = {}".format(r)) return r print(int("ff", base=16)) print(trace(int, "ff", base=16)) # with this combination of arguments (*args, **kwargs), the function can accept and forward any combination of # positional and key-value arguments. This way, the trace function works with any other function def upper_name(name): return name.upper() def lower_name(name, surname): return "{} {}".format(name, surname) if surname else name trace(upper_name, "Diego") trace(lower_name, "Diego", "Guimaraes")
true
23c7631d5202726ae08892d889356ca7691e0af7
diego-guisosi/python-norsk
/02-beyond-the-basics/06-numeric-and-scalar-types/04-time.py
719
4.28125
4
import datetime # representing time not caring about the date print(datetime.time(3)) print(datetime.time(3, 1)) print(datetime.time(3, 1, 2)) print(datetime.time(3, 1, 2, 232)) # the last parameter is microseconds t = datetime.time(hour=23, minute=59, second=59, microsecond=999999) print() print('hour={time.hour}, minute={time.minute}, second={time.second}, microsecond={time.microsecond}'.format(time=t)) print(t) print(t.isoformat()) print() # the formatting below depends on the OS print(t.strftime('%Hh%Mm%Ss')) # prefer this more pythonic approach instead print('{time.hour}h{time.minute}m{time.second}s'.format(time=t)) print() print(datetime.time.min) print(datetime.time.max) print(datetime.time.resolution)
true
052e066c93cc81ddff3593577d56d1b37d90ae3c
diego-guisosi/python-norsk
/02-beyond-the-basics/02-functions/extended_call.py
950
4.4375
4
# extended call sintax def print_numbers(number, *numbers): # passing *numbers to print function will extend the parameters, so each positional argument is passed to print() # this function first parameter is mandatory and, the others, are optional print(number, *numbers) print(1, 2, 3) t = (1, 2, 3) print_numbers(*t) # as we can see, it's possible to unpack a tuple into mandatory and *args at the same time def print_colors(red, green, blue, **kwargs): print('r = {}'.format(red)) print('g = {}'.format(green)) print('b = {}'.format(blue)) print(kwargs) # it is possible to do the same with **kwargs k1 = {'red': 21, 'green': 68, 'blue': 120, 'alpha': 52} print_colors(**k1) # observe that the order of the keys defined on dict does not matter # python unpacks each key into the function parameter that have the same name of the key k2 = {'green': 68, 'red': 21, 'blue': 120, 'alpha': 52} print_colors(**k2)
true
9c55733fde31fc325e112387be5ed2361e8e2edb
diego-guisosi/python-norsk
/01-fundamentals/chapter06/list_repetition.py
615
4.4375
4
# when used with strings or lists, * works as a repetition operator # it can be used to initialize lists with default values my_list = [0] * 3 print(my_list) print() # with the repetition operator, the previous list was initiated with three elements containing the value zero my_string = "Diego " * 4 print(my_string) print() # the same applies to strings # repetition is shallow other_list = [[-1, +1]] * 5 print(other_list) print(other_list[0] is other_list[1]) other_list[3].append(7) print(other_list) print() another_one = [[-1, +1] * 5] print(another_one) print(another_one[0][0] is another_one[0][3])
true
7558925608308d2ad8719927945b34161194b05f
diego-guisosi/python-norsk
/01-fundamentals/chapter06/shallow_copies.py
607
4.3125
4
# list copies are shallow. A new list containing the same object references of the source list is create. my_list = [1, 2] print(my_list) my_copy = my_list[:] print(my_copy) print(my_copy is my_list) print(my_copy == my_list) my_other_list = [[1, 2], [3, 4]] my_other_copy = my_other_list[:] print(my_other_copy) print(my_other_copy is my_other_list) print(my_other_copy[0] is my_other_list[0]) # since the elements of my_other_list are references to other lists, the copied list contains the same references # of my_other_list my_other_list[1].append(5) print(my_other_list[1]) print(my_other_copy[1])
true
469fdc4be725f8e3402c0ca9d80a68838f32fd43
shmuelch/python_project_1
/display_data.py
2,547
4.125
4
""" The Questions you should answer: What are the universities with more than one website Out of the last 1000 flights - Display the flights Landed from countries which are larger than 1,000,000 km² Out of the last 1000 flights - Show list of all flights coming from countries with more than 5 universities and that the number of flights for this country is less than 100 Hands out: Git repository with your code and SQL We will review your code together """ from sqlalchemy import create_engine import pandas as pd engine = create_engine('mysql+pymysql://root:@localhost/project_1') #What are the universities with more than one website sql= "SELECT name,country,web_pages from universities where web_pages > 1 " df = pd.read_sql(sql, con=engine) print("\n\n Universities with more than one website \n") print(df) #Out of the last 1000 flights - Display the flights Landed from countries which are larger than 1,000,000 km² #sql= " select flights.*,countries.AREA from flights join countries on (UPPER(flights.CHLOCCT)=UPPER(countries.NAME)) where CHRMINE='LANDED' and countries.AREA > 1000000 and CHFTLN in (select CHFTLN from flights order by UNIX_TIMESTAMP(CHSTOL) desc limit 1000 )" # This version of MariaDB doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery' sql="select * from flights order by UNIX_TIMESTAMP(CHSTOL) desc limit 1000" df = pd.read_sql(sql, con=engine) df.to_sql(name="flights_temp", con=engine, if_exists = 'replace', index=False) sql= " select flights_temp.*,`countries`.`Area in km²` from flights_temp join countries on (UPPER(flights_temp.CHLOCCT)=UPPER(countries.Country)) where CHRMINE='LANDED' and `countries`.`Area in km²` > 1000000 " df = pd.read_sql(sql, con=engine) print("\n\nLast 1000 flights - Landed from countries which are larger than 1,000,000 km² \n") print (df) #Out of the last 1000 flights - Show list of all flights coming from countries with more than 5 universities and that the number of flights for this country is less than 100 sql= " select * from flights_temp " sql+=" where UPPER(flights_temp.CHLOCCT) in (select UPPER(country) from universities GROUP by country HAVING COUNT(country) > 5 ) " sql+=" and flights_temp.CHLOCCT in (select CHLOCCT from flights_temp GROUP by CHLOCCT HAVING COUNT(_id) < 100) " df = pd.read_sql(sql, con=engine) print("\n\nLast 1000 flights - coming from countries with more than 5 universities and that the number of flights for this country is less than 100 \n") print (df)
true
5fb85d361a168c51e57aefe5e94cf6c2a96c7bde
soloasiedu/DataStructuresAndAlgorithms
/Stack/StackImplementation.py
1,133
4.34375
4
# A stack is an abstract data structure. It is just like a pile of plates. # You can add a new plate or remove a plate # If you want to get to the last last plate you have to remove all the plates on top # of it first # Adding a new item on the stack is called a push. To push you first have to check if the stack is not # full # Removing an item from the stack is called a pop. To pop you have to check if the stack is empty # Looking at the top item without removing it is called peeking def create_stack(): stack = [] return stack def check_empty(stack): return len(stack) == 0 def push(stack, item): stack.append(item) print("pushed item: " + item) def peek(stack): return stack[len(stack) - 1] def pop(stack): if (check_empty(stack)): return "stack is empty" return stack.pop() stack = create_stack() push(stack, str(5)) push(stack, str(59)) push(stack, str(12)) push(stack, str(88)) print("Popped item: " + pop(stack)) print("Stack after popping: " + str(stack)) print("Peeking top item: " + peek(stack)) print("Stack after peeking: " + str(stack)) print(stack)
true
5078fb1dc33e58d37ed81b8746e3dfac078b170b
LauraHoffmann-DataScience/DSC510
/LHoffmann_9.1.py
2,184
4.34375
4
# Course: DSC510 # Assignment: 8.1 # Date: 4/27/2020 # Name: Laura Hoffmann # Description: Program to write new text files # Generate a text file for the output of the dictionary from the gba_file # Add a function (process_file) similar to pretty_print # This function prompts user for name of new file and then commands to write the dictionary to the new file # instead of to the screen in addition to formatting the dictionary import string def process_line(line, word_count_dict): line = line.strip() word_list = line.split() for word in word_list: if word != '--': word = word.lower() word = word.strip() word = word.strip(string.punctuation) add_word(word, word_count_dict) def add_word(word, word_count_dict): if word in word_count_dict: word_count_dict[word] += 1 else: word_count_dict[word] = 1 def process_file(word_count_dict): # User input for the file name file = input('What would you like the new file to be called?: ') # Create a file to be written from scratch with the user input as the name with open(file, 'w') as file: wordcount = 'Your total word count is: ' + str(len(word_count_dict)) # Since file.write can only take one argument I made it into a variable file.write(wordcount) file.write('\n' * 2) # Formatting from pretty_print function value_key_list = [] for key, val in word_count_dict.items(): value_key_list.append((val, key)) value_key_list.sort(reverse=True) file.write('{:11s}{:11s}'.format("Word", "Count")) file.write('\n' * 2) for val, key in value_key_list: file.write('{:12s} {:<3d}'.format(key, val, )) file.write('\n') def main(): word_count_dict = {} try: with open('gettysburg.txt', 'r') as gba_file: for line in gba_file: process_line(line, word_count_dict) process_file(word_count_dict) except FileNotFoundError as e: print(e) if __name__ == "__main__": main()
true
ceea93eedb51382d13a7520c064709763c3ca2e6
LauraHoffmann-DataScience/DSC510
/Hoffmann_3.1.py
729
4.5625
5
# Course: DSC510 # Assignment: 3.1 # Date: 3/24/20 # Name: Laura Hoffmann # Description: Program to calculate cost at a bulk discount Welcome_Message = "Welcome to Fiber Optics R Us!" print(Welcome_Message) Company_Name = input("What is your company's name?\n") Feet = input("How many feet of fiber optic cable do you need to be installed?\n") if int(Feet) <= int(100): Total_Cost = (.87) * int(Feet) elif int(100) < int(Feet) <= int(250): Total_Cost = (.80) * int(Feet) elif int(250) < int(Feet) <= int(500): Total_Cost = (.70) * int(Feet) else: Total_Cost = (.50) * int(Feet) print("The total cost for", Company_Name, "will be $", Total_Cost, "for", Feet, "of fiber optic cable to be installed.")
true
6347d2e0417140d41e4e57756a87ec24dcfe9487
er-arcadio/Project1_2020_metis
/jupyter_notebooks/lonlatmap.py
1,725
4.15625
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: """ The following code was inspired by https://www.kaggle.com/muonneutrino/mapping-new-york-city-census-data/#The-Census-Data The convert_to_2d function is used to take geo information and return a grid area of lon and lats the make_plot function uses matplotlib to graph area by density of values """ import pandas as pd import numpy as np import matplotlib.pyplot as plt def convert_to_2d(lats, lons, values): """ this function converts geo information """ latmin = 40.48 lonmin = -74.28 latmax = 40.93 lonmax = -73.65 lon_vals = np.mgrid[lonmin:lonmax:200j] lat_vals = np.mgrid[latmin:latmax:200j] map_values = np.zeros([200, 200]) dlat = lat_vals[1] - lat_vals[0] dlon = lon_vals[1] - lon_vals[0] for lat, lon, value in zip(lats, lons, values): lat_idx = int(np.rint((lat - latmin) / dlat)) lon_idx = int(np.rint((lon - lonmin) / dlon)) if not np.isnan(value): map_values[lon_idx, lat_idx] = value return lat_vals, lon_vals, map_values def make_plot(blocks, data_values, title='', colors='White'): """ this function uses grid information to create a density map """ lat_vals, lon_vals, values = convert_to_2d(blocks.Latitude, blocks.Longitude, data_values) fig, ax = plt.subplots(figsize = [12, 12]) limits = np.min(lon_vals), np.max(lon_vals), np.min(lat_vals), np.max(lat_vals) im = ax.imshow(values.T, origin='lower', cmap=colors, extent=limits, zorder = 1) ax.autoscale(False) plt.xlabel('Longitude [degrees]') plt.ylabel('Latitude [degrees]') plt.title(title) plt.colorbar(im, fraction=0.035, pad=0.04) plt.show()
true
94ff608b2abd00e6c7f8f48baba309a1840cd04b
decodingjourney/BeginnerToExpertInPython
/IfProgramFlow/ifprogramflow.py
1,921
4.1875
4
# name = input("Please enter your name ") # age = int(input("How old are you {0} " .format(name))) # print("are you really {0} years old {1}?" .format(age, name)) # # if age >= 21: # print("You are eligible to cast your Vote") # print("Plese put an X in the box") # else: # print("Please come after {0} years to vote" .format(21 - age)) # print("Please enter the number between 1 to 10 ") # num = int(input()) # if num < 5: # print("Please guess the number higher ") # num = int(input()) # if num == 5: # print("Well Done ! you guessed it correctly") # else: # print("Sorry! You did not guessed it ") # elif num > 5: # print("Please guess lower number") # num = int(input()) # if num == 5: # print("Well Done ! you guessed it correctly") # else: # print("Sorry! you did not guessed it correctly") # else: # print("Congratulations! you have guessed it on very first time") # print("Please enter the number between 1 to 10 ") # num = int(input()) # if num != 5: # if num < 5: # print("Please guess higher") # else: # print("Please guess lower") # # num = int(input()) # if num == 5: # print("Well Done! you got it ") # else: # print("Sorry you did not guessed it ") # else: # print("You guessed it on first attempt") # age = int(input("How old are you? ")) # # if (age >= 16) and (age <= 65): # if 16 <= age <= 65: # print("Welcome to work and have a nice day at work") # Coding on 12-12-2018 # Write a small program to enter the name and age name = input("Please enter your name ") age = int(input(" how old are you {0} " .format(name))) if age > 18 and age < 31: print("welcome to the grand party") elif age <= 18: print("I am sorry! you are allowed after {0} years " .format(18 - age)) else: print("You are too old to attend this party")
true
25bfaa29252465e8dbf4ae5405fb78ee6dbb312a
ozkancondek/clarusway_python
/my_projects/username and pass real.py
798
4.125
4
user_name = input("User name: ") password = int(input("Password: ")) count=1 while user_name != "ozkan" or password != 3507: if user_name == "ozkan": print("your password is wrong. Enter your informations again") if password == 3507: print("Your username is wrong. Enter your informations again") if user_name != "ozkan" and password != 3507: print("both of your infos wrong") user_name = input("User name: ") password = int(input("Password")) count+=1 if count >2: print("your account is locked") break #if count == 3: # print("your account is locked") # break if user_name == "ozkan" and password == 3507: print("access confirmed in ",count,". attampt")
true
376ce60ac734df80afad0d02360fd8609cd3cf63
ozkancondek/clarusway_python
/my_projects/disarium_number.py
537
4.1875
4
# -*- coding: utf-8 -*- """ Created on Sun Jul 25 23:37:51 2021 @author: admin """ #A number is said to be Disarium if the sum of its digits # raised to their respective positions is the number itself. num = int(input("Enter the number: ")) order =str(num) def disarium(num): result = 0 for i in range(len(order)): result = result + int(order[i])**(i+1) if result == num: print(f"{num} is disarium number.") else: print(f"{num} is not disarium number") disarium(num)
true
9db37d14eb3536320a01293ed6851dbd4ad2621c
ozkancondek/clarusway_python
/my_projects/anagram.py
694
4.15625
4
# -*- coding: utf-8 -*- """ Created on Thu Jul 29 15:14:55 2021 @author: admin """ #anagram example #Take two inputs from the user word and word-list. #Than write code that will find all the anagrams of a word from a list. # You should return a list of all the anagrams or an empty list if there are none. word = input("Give me a word. ") ls = [] sl = [] for i in range(4): a = input(f"Give me {i+1}. word for list. ") ls.append(a) print(f"Your list is:\n {ls}\nYour word is: {word}") x = list(word) x.sort() for j in range(len(ls)): y= list(ls[j]) y.sort() if x == y: sl.append(ls[j]) print("Your anagram list is below:\n ",sl)
true
b40a42620ec4062eaf48a223103a020a20438a66
ozkancondek/clarusway_python
/clarusway/inclass_map.py
845
4.625
5
# -*- coding: utf-8 -*- """ Created on Thu Aug 12 20:15:13 2021 @author: admin """ #map object #map(function,*iterable) applies this function for every elements of iterable.You can also send an iterable more than one. iterable = [1,2,3,4,5,6] result = map(lambda x:x**2,iterable) print(result) print(list(result)) #---def and map def a(x): return x**2 iterable = [1,2,3,4,5,6] a = map(a,iterable) print(list(a)) #---------- #first of all x for iterable1 #than y for iterable #than z for iterable3 letter1 = ['o', 's', 't', 't'] letter2 = ['n', 'i', 'e', 'w'] letter3 = ['e', 'x', 'n', 'o'] numbers = map(lambda x, y, z: x+y+z, letter1, letter2, letter3) print(list(numbers)) #--------avarage of two list num1 = [1,2,3,4] num2 = [11,22,33,44] a = map(lambda x,y : (x+y)/2, num1,num2) print(list(a)) #--------
true
0a54a29afedc0fc9940d5243fa88d1c476dd3961
SiddheshKhedekar/Python-Foundations
/2.Turtle, messaging and Profanity checker/turtleSquare.py
762
4.65625
5
""" The program that allows user to make a turtle using the function and call to it. """ import turtle def draw_square(): # declare function to draw square playground=turtle.Screen() # provide a windows for turtle to draw playground.bgcolor("pink") # change background color meow=turtle.Turtle() # meow = new turtle meow.color("yellow") # set color of turtle meow.shape("turtle") # set arrow shape to turtle meow.speed(1) meow.forward(200) # move 100 distance meow.right(90) # turn 90 degree meow.forward(200) meow.right(90) meow.forward(200) meow.right(90) meow.forward(200) meow.right(90) playground.exitonclick() # click any where to exit draw_square() # run function draw_square
true
fc3e8d09361d9951c6e29d8a538071c4f00d6410
gregtampa/Wargames
/ProjectEuler/019.py
737
4.125
4
#!/usr/bin/env python # You are given the following information, but you may prefer to do some # research for yourself. # 1 Jan 1900 was a Monday. # Thirty days has September, # April, June and November. # All the rest have thirty-one, # Saving February alone, # Which has twenty-eight, rain or shine. # And on leap years, twenty-nine. # A leap year occurs on any year evenly divisible by 4, but not on a century # unless it is divisible by 400. # How many Sundays fell on the first of the month during the twentieth century # (1 Jan 1901 to 31 Dec 2000)? years = 2000 - 1901 days = 0 for i in range( 1900, 2001 ): days += 365 if i % 4 == 0 and ( i % 100 != 0 or i % 400 == 0 ): days += 1 print "Leap year" print i print days
false
c175cf4741c933841f30c9b902b7a38aeab4ad64
dawsboss/Math471
/ch1/1.3.1.py
1,557
4.15625
4
# Grant Dawson # Problem 1.3.1 a-d # # "In each problem below, A is the exact value, and Ah is an approximation to A. # Find the absolute error and the relative error" # #1a. A = pi | Ah = 22/7 #1b. A = e | Ah = 2.71828 #1c. A = 1/6 | Ah = .1667 #1d. A = 1/6 | Ah = .1666 import math #This will calculate the absolute error def Absolute_Error(real, experiement): return abs(real - experiement) #This will calculate the relative error def Relative_Error(real, experiement): return abs( (real - experiement) / real ) A = math.pi Ah = 22.0/7.0 print("A = {:2.6f} | Ah = 22/7".format(math.pi)) print("Absolute error = {:2.6f} | Relative Error = {:2.6f}".format(Absolute_Error(A,Ah), Relative_Error(A,Ah))) A = math.e Ah = 2.71828 print("A = {:2.6f} | Ah = 2.71828".format(math.e)) print("Absolute error = {:2.9f} | Relative Error = {:2.9f}".format(Absolute_Error(A,Ah), Relative_Error(A,Ah))) A = 1.0/6.0 Ah = .1667 print("A = 1/6 | Ah = .1667") print("Absolute error = {:2.6f} | Relative Error = {:2.6f}".format(Absolute_Error(A,Ah), Relative_Error(A,Ah))) A = 1.0/6.0 Ah = .1666 print("A = 1/6 | Ah = .1666") print("Absolute error = {:2.6f} | Relative Error = {:2.6f}".format(Absolute_Error(A,Ah), Relative_Error(A,Ah))) # Problem 1.3.6 # sum = 0.0 for i in range(0,200000): sum = sum + math.pow(math.e, -14 * (1 - math.pow( math.e, -.05*i ))) print(sum) sum = 0.0 for i in range(200000,0,-1): sum = sum + math.pow(math.e, -14 * (1 - math.pow( math.e, -.05*i ))) print(sum)
false
b3d4ea6bddd626146e56e4749be1719a683dd78e
derpwanda/Sorting
/project/searching.py
1,459
4.15625
4
# STRETCH: implement Linear Search # found https://www.geeksforgeeks.org/linear-search/ def linear_search(arr, target): # TO-DO: add missing code for i in range(0, len(arr)): if(arr[i] == target): return i return -1 # not found arr = [2, 3, 4, 10, 40] result = linear_search(arr, 10) if(result == -1): print("Not found") else: print("Element is at index", result) # STRETCH: write an iterative implementation of Binary Search # O(log(n)) def binary_search(arr, target): if len(arr) == 0: return -1 # array empty low = 0 high = len(arr)-1 # TO-DO: add missing code # while loop has runtime of O(log(n)): # we are searching through some not all while low < high: middle = (low + high)/2 if target < arr[middle]: high = middle - 1 elif target > arr[middle]: low = middle + 1 else: return middle return -1 # not found # STRETCH: write a recursive implementation of Binary Search # O(log(n)) def binary_search_recursive(arr, target, low, high): middle = (low+high)/2 if len(arr) == 0: return -1 # array empty # TO-DO: add missing if/else statements, recursive calls if len(arr) == 0: return -1 # array empty elif low > high: return -1 elif arr[middle] == target: return middle else: if target < arr[middle]: high = middle - 1 else: low = middle + 1 return binary_search_recursive(arr, target, low, high)
true
d8c5da6ccc3e01c3b05426eb8716ff338e9c34f1
pi2017/lessons
/lesson4/ex_06.py
370
4.21875
4
# coding=utf-8 # Example code # задачи для закрепления теории def bubble_sort(numbers): for i in range(len(numbers)): for j in range(len(numbers) - 1, i, -1): if numbers[j] < numbers[j-1]: numbers[j], numbers[j-1] = numbers[j-1], numbers[j] return numbers print(bubble_sort([4, 8, 3, 1, 5, 7, 2]))
false
0bebb7b24076811d936c90e60ba4f0293b1a042f
pi2017/lessons
/lesson5/ex_03.py
475
4.28125
4
# # Списки - изменяемые последовательности любого типа данных # Кортеж - не изменяемый список, ограниченный список from typing import Tuple my_list = [] my_list_0 = [1, 4, 5, 32, 88] for i in range(10): my_list.append(None) print(my_list) my_list.insert(0, 'ausweis') print(my_list) my_tuple_1 = (1, 2, 'ausweis') print(my_tuple_1) a, b, c = 13, 13, 13 print((a, b, c))
false
63c09ef876de1be0639f60d0cd4c46a45bd6165e
semosso/lpthw
/ex33.py
2,889
4.15625
4
i = 0 numbers = [] while i < 6: print(f'At the top i is {i}') numbers.append(i) i = i + 1 print('Numbers now: ', numbers) print(f'At the bottom i is {i}') # goes to top until i < 6, that's the whole point of the WHILE-loop print('The numbers: ') # only called when loop ends, i.e., when i = 6, and lists is 0 through 5 for num in numbers: print(num) # prints each number, one at a time, until reaches the last NUM (it'd be different if it was NUMBERS, because it'd print the list six times) # # # # # STUDY DRILLS # # # # 1, convert this while-loop to a FUNCTION that you can call, and replace 6 in the test with a variable # # # # 2, use this FUNCTION to rewrite the script to try different numbers def lister(fim): i = 0 lista = [] while i < fim: print(f'At the top i is {i}') lista.append(i) i = i + 1 print('Numbers now: ', lista) print(f'At the bottom i is {i}') return lista # important indent here (I got it right the first time by luck; this should be indented to the function level, not the while-loop) var = int(input('How long should the loop run for?\n> ')) # important, so that comparison in ln 24 works (otherwise input comes as string) lishta = lister(var) print('The numbers: ') for num in lishta: print(num) # # # 3, add another variable to the FUNCTION arguments that you can pass in that lets you change the + 1 on line 8 so you can change how much it increments by # # # 4, rewrite the script again to use this function to see what effect that has def lister2(fim, incremento): i = 0 lista = [] while i < fim: print(f'At the top i is {i}') lista.append(i) i = i + incremento print('Numbers now: ', lista) print(f'At the bottom i is {i}') return lista var2 = int(input('How long should the loop run for?\n> ')) incr = int(input('What should the increment be?\n> ')) lishta2 = lister2(var2, incr) print('The numbers: ') for num in lishta2: print(num) # 5, write it to use for-loops and range. Do you need the incrementor in the middle anymore? What happens if you do not get rid of it? numbers = [] for x in range (0, 6): # no need for incrementor, because FOR-LOOP "iterates over" each element within range in a sequence # note how 6 being the last number in RANGE is similar to having WHILE i < 6, because range doesn't iterate over last number print(f'At the top i is {x}') numbers.append(x) print('Numbers now: ', numbers) print('At the bottom i is', x + 1) # i = i + 1 # no need for it, but this is not really getting rid of the incrementor, just moving it around # could I have done something similar for the other ones? not really, because WHILE needs a defined variable to run, but FOR doesn't print('The numbers: ') for num in numbers: print(num)
true
40116b669029868538a277850148ffc39d69facd
semosso/lpthw
/5drill.py
1,442
4.28125
4
# first exercise # removing my from the beginning name = 'Zed A. Shaw' age = 35 # Not a lie height = 74 #inches weight = 180 #lb eyes = 'Blue' teeth = 'White' hair = 'Brown' print(f'Let\'s talk about {name}.') print(f'He\'s {height} inches tall.') print(f'He\'s {weight} pounds heavy.') print(f"He's got {eyes} eyes and {hair} hair.") # instead of relying on \ before ' to avoid closing the string prematurely print(f'His teeth are usually {teeth} depending on the coffee.') # this line is tricky, try to get it exactly right total = age + height + weight print(f'If I add {age}, {height}, and {weight} I get {total}.') # second exercise # calculating CM and KG inch = 2.54 lb = 0.45 height_cm = height * inch # alternatively, could have just put the 2.54 here, like I did wigh weight below weight_kg = weight * 0.45 print(f'In the metric system, he is {height_cm} centimeters tall, and weighs {weight_kg} kilograms.') # on my own # so what does the "f" do? f FORMATS the string, i.e., it tells Python to find the variable and put it INSIDE the string # i.e., without FORMAT, you have to keep breaking the strings to call the variables # using , inside the string without format is the same; but only works for now (while the true potential of format is not being used) # also it's way more trouble and not at all skillful, elegant etc. print('In the metric system, he is', height_cm, 'centimeters tall, and weights', weight_kg, 'kilograms.')
true
3c0b11bea284c8d88b7f0c073c2b29fbfdf2b7ad
ChrisRRadford/CodingChallenges
/immutableFunction.py
2,464
4.46875
4
# Write an immutable function that merges the following inputs into a single list. # (Feel free to use the space below or submit a link to your work.) # Inputs # - Original list of strings # - List of strings to be added # - List of strings to be removed # Return # - List shall only contain unique values # - List shall be ordered as follows # --- Most character count to least character count # --- In the event of a tie, reverse alphabetical # Other Notes # - You can use any programming language you like # - The function you submit shall be runnable # For example: # Original List = ['one', 'two', 'three',] # Add List = ['one', 'two', 'five', 'six] # Delete List = ['two', 'five'] # Result List = ['three', 'six', 'one']* def immutableFunction(): origList = ("one","two","three") addList = ("one","two","five","six") delList = ("two","five") print("Origional list",origList) #Add list to Origional modifiedList = origList + addList dupFreeList = ("temp",) print("With added List",modifiedList) # Remove duplicate elements for index in modifiedList: if index not in dupFreeList: #create temporary tuple containing valid entry tupleIndex = (index,) dupFreeList+= tupleIndex dupFreeList = dupFreeList[1:] print("Removed duplicates", dupFreeList) # Remove delete list elements finalList = ("temp",) for index in dupFreeList: if index not in delList: tupleIndex = (index,) finalList+= tupleIndex finalList= finalList[1:] print("Remove deletion list",finalList) # Sort the final list if len(finalList) <= 0: print("Final list is empty") return elif len(finalList) == 1: print("List equals one") return(finalList) # List must be sorted use bubble sort else: print("Sorting list") finalSortedList = bubbleSortRevAlphabetical(finalList) return finalSortedList def bubbleSortRevAlphabetical(sortList): for i in range (0, len(sortList) -1): for j in range (0, len(sortList) - 1 - i): #set temporary list to check if reverse alphabetical reverseAlphaTemp = (sortList[j],sortList[j+1]) sortedReverseAlphaTemp=(sorted(reverseAlphaTemp,reverse=True)) #bubble sort if len(sortList[j]) < len(sortList[j+1]) or (len(sortList[j]) == len(sortList[j+1]) and (tuple(sortedReverseAlphaTemp) != reverseAlphaTemp)): leftswap = (sortList[j+1],) rightswap = (sortList[j],) sortList = sortList[:j] + leftswap + rightswap + sortList[j+2:] return(sortList) print(immutableFunction())
true
4b2c390b9c459c29def8b86305814cd98d8093fa
amitmtm30/PythonCode
/Function/evenodd.py
249
4.28125
4
################################################################## def evenodd(n): if n % 2 == 0: print("The number ",n, "is Even") else: print("The number ",n, "is Odd") n = int(input("Enter Number to check for Even or odd : ")) evenodd(n)
false
c21aa30a09160d4ed552599fa7061b459d316a11
amol-a-kale/exersicepython
/medium/count_word.py
2,166
4.21875
4
# Write a program to count the number of words and letters in a sentence def count_word(): string_input = input('enter the string :') count1 = 0 for i in string_input: # we use if loop for calculate no of space if i == " ": count1 += 1 # word is greater than one by space for that we write following syntax no_word = count1 + 1 print(no_word) # count_word() # it is used to find number of characteristic def count_char(): string_input = input('enter the string :') count1 = 0 for i in string_input: # we use if loop for calculate no of space if i == " ": count1 += 1 # word is greater than one by space for that we write following syntax no_char =len(string_input)- count1 print(no_char) # count_char() def print_vowol(): string_input = input('enter the string :') string=string_input.lower() count1 = 0 vowel_list=['a', 'i', 'e', 'o','u'] for i in string: # we use if loop for calculate no of space if i in vowel_list: print(i) count1 += 1 # word is greater than one by space for that we write following syntax print(count1) # print_vowol() # print_ consonants def print_cons(): string_input = input('enter the string :') string=string_input.lower() count1 = 0 vowel_list=['a', 'i', 'e', 'o','u',' '] for i in string: # we create list in list we add vowels and space and compare with actual string if i not in vowel_list: print(i) count1 += 1 # word is greater than one by space for that we write following syntax print('the number of consonant is : ',count1) # print_cons() # find number of word by using splict function # # count=0 # string=' hi amol kale' # split_string=string.split() # for i in split_string: # print(i) # count=1+count # # print('the number of word :', count ) # count the number of charactertics count=0 string=' hi amol kale' for i in string: if i== " ": print(i) count=1+count print('the number of word :', len(string)-count )
true
26dbe0334526883e1d9feee8214f1dd0dbb8c7db
Kazzle619/Project_Euler
/project_euler_62.py
1,427
4.1875
4
# -*- coding: utf-8 -*- ''' Problem62 「Cubic permutations」 The cube, 41063625 (345^3), can be permuted to produce two other cubes: 56623104 (384^3) and 66430125 (405^3). In fact, 41063625 is the smallest cube which has exactly three permutations of its digits which are also cube. Find the smallest cube for which exactly five permutations of its digits are cube. (桁を並び替えると他に4つの立方数となる、最小の立方数を求めよ。) ''' import time def digits_tuple(num): digits = {} str_num = str(num) for digit_number in str_num: try: digits[digit_number] += 1 except KeyError: digits[digit_number] = 1 # タプルでないと辞書のキーに出来ないのでタプル化して返す。 return tuple(sorted(digits.items())) if __name__ == '__main__': start = time.time() digits_of_cubes = {} num = 1 while True: cube = num ** 3 try: digits_of_cubes[digits_tuple(cube)].append(cube) except KeyError: digits_of_cubes[digits_tuple(cube)] = [cube] if len(digits_of_cubes[digits_tuple(cube)]) == 5: print(min(digits_of_cubes[digits_tuple(cube)])) # answer 127035954683 break else: num += 1 elapsed_time = time.time() - start print("elapsed_time:{}".format(round(elapsed_time, 5)) + "[sec]") # 0.09943sec
true
54e7083309f1af87a7f7b5d96d7f252fbadd5aaa
abir-taheer/learnination-fruition
/hw26.py
1,073
4.125
4
# Abir Taheer # IntroCS pd1 # HW26 -- 000 000 111, v10 # 2019-03-18 def bondify(name: str) -> str: """ :param name: The name of the person :return: The name, bondified >>> bondify("Abir Taheer") 'Taheer, Abir Taheer' >>> bondify("banana man") 'man, banana man' >>> bondify("coolio") 'coolio, coolio' """ loc = name.find(" ") return name[loc + 1:] + ", " + name def replace(s: str, q: str, r: str) -> str: """ :param s: The original string :param q: The string to match in the original string :param r: The string to replace the match with :return: The new string with the replacement in place >>> replace("hello from the other side", "other", "banana") 'hello from the banana side' >>> replace("Winter is coming", "Winter", "Spring") 'Spring is coming' >>> replace("Dolphins run this planet", "dolphins", "mice") 'Dolphins run this planet' """ loc = s.find(q) if loc == -1: return s beginning = s[:loc] end = s[loc + len(q):] return beginning + r + end
false
c5a3aecc23dc9d2e9de950857b1fb0a52ac2a8cd
georgiosdoumas/ModularProgrammingInPython3-
/chap07/string_utils.py
422
4.125
4
import re def extract_numbers(s): pattern = r'[+-]?\d+(?:\.\d+)?' ## numbers = [] ## for match in re.finditer(pattern, s): ## number = s[match.start():match.end()] ## numbers.append(number) ## return numbers ## these lines are mentioned in the book ## but we can use list comprehension and do it in one line : return [s[match.start():match.end()] for match in re.finditer(pattern, s)]
true
4b912169235bdce6e4ff04208f7de50fa7716419
mursigkeit22/py_weekly_charm
/asynchronous/queues_sync_and_async/_3_concurrency_queue_sleep.py
1,369
4.15625
4
# The next version of the program is the same as the last, # except for the addition of a time.sleep(delay) # in the body of your task loop. # This adds a delay based on the value retrieved # from the work queue to every iteration of the task loop. # The delay simulates the effect of a blocking call # occurring in your task. # A blocking call is code that stops the CPU from # doing anything else for some period of time. import time import queue from codetiming import Timer def task(name, queue): timer = Timer(text=f"Task {name} elapsed time: {{:.1f}}") while not queue.empty(): delay = queue.get() print(f"Task {name} running, delay: {delay}") timer.start() time.sleep(delay) timer.stop() #stops the timer instance and outputs the elapsed time since timer.start() was called. yield def main(): work_queue = queue.Queue() for work in [15, 10, 5, 2]: work_queue.put(work) tasks = [task("One", work_queue), task("Two", work_queue)] done = False with Timer(text="\nTotal elapsed time: {:.1f}"): while not done: for t in tasks: try: next(t) except StopIteration: tasks.remove(t) if len(tasks) == 0: done = True if __name__ == "__main__": main()
true
2acb2ce9103a9343b4f971ff95905350da3cd18e
Tbones41/python_Mentorship_Tolulope
/Week_1/Challenge_1.py
377
4.15625
4
def first_reverse(sentence): split_sentence = sentence.split(" ") output_list = [] for item in split_sentence: output_list.append(item) output_list.reverse() output = "" for each_word in output_list: output += each_word + " " return output print(first_reverse(input("Type your sentence here to be reversed!! \n>> ")))
true
06867f0fa2d6735cc8a3ce15172c8166ab38d838
chelsea-shu/codingHW
/common_factors.py
1,425
4.1875
4
from math import sqrt def main(): number1 = int(input("Enter first integer: ")) number2 = int(input("Enter second integer: ")) num1list = [] num2list = [] common = [] for i in range(number1): if number1 % (i+1) == 0: num1list.append(i+1) for i in range(number2): if number2 % (i+1) == 0: num2list.append(i+1) for r in num1list: for r2 in num2list: if r == r2: common.append(r) print(common) """Insert code here print common factors of two numbers Similar to the previous homework, loop up to the square root of the two numbers, identify all the factors and store them in two lists, one for each number. Then compare the contents of the list to identify unique common factors (including 1) and print them in ascending order. One way to compare is to loop through the contents of the sets and find common factors. (A more efficient way is to convert the lists into sets and find the intersection, if you want to try that.) Check that the inputs are positive integers. If you are comfortable using functions, feel free to define one to identify factors. If not, it's okay to duplicate the code for this homework. We'll re-do this exercise later for an arbitrarily large number of integers, and then we'll use functions. """ main()
true
3ce30ae5b0f7078d4849136236656bc06b77f6fc
gabreuvcr/curso-em-video
/mundo1/ex025.py
344
4.21875
4
## EX025 ## nome = input('Digite seu nome completo: ') print('Com find: ') existe = nome.upper().find('SILVA') if existe == -1: print('O nome não possui SILVA!') else: print('O nome tem SILVA!') print('\nCom in: ') existe = 'SILVA' in nome.upper() if existe: #if true print('Existe SILVA!') else: print('Nao existe SILVA!')
false
86254ad54f648483c518d1ba46b8e49d34b9c615
DavidLewinski/CA117
/week08/circle_081.py
734
4.15625
4
#!/usr/bin/env python3 class Point(object): def __init__(self, x=0, y=0): self.x = x self.y = y def __str__(self): return f'({self.x}, {self.y})' def midpoint(self, other): x = ((other.x + self.x) / 2) y = ((other.y + self.y) / 2) return Point(x, y) class Circle(object): def __init__(self, c=None, r=0): if c is None: c = Point() self.centre = c self.radius = r def __add__(self, other): c = (self.centre.midpoint(other.centre)) r = (self.radius + other.radius) return (Circle(c, r)) def __str__(self): return f'Centre: {self.centre}\nRadius: {self.radius}'
false
07c8b8d592ddb33b2ed4b9e4a905cfb58c81ff60
DorotaPawlowska/programming-practice
/books/Z.A.Shaw/ex21-30/ex25.py
985
4.125
4
def break_words(stuff): """Ta funkcja rozbija zdanie na słowa.""" words = stuff.split(' ') return words def sort_words(words): """Sortuje słowa.""" return sorted(words) def print_first_word(words): """Drukuje pierwsze słowo i usuwa je ze zdania.""" word = words.pop(0) print(word) def print_last_word(words): """Drukuje ostatnie słowo i usuwa je ze zdania.""" word = words.pop(-1) print(word) # def sort_sentence(sentence): """Pobiera pełne zdanie i zwraca posortowane słowa.""" words = break_words(sentence) return sort_words(words) # def print_first_and_last(sentence): """Drukuje pierwsze i ostatnie słowo zdania.""" words = break_words(sentence) print_first_word(words) print_last_word(words) # def print_first_and_last_sorted(sentence): """Sortuje słowa, a następnie drukuje pierwsze i ostatnie.""" words = sort_sentence(sentence) print_first_word(words) print_last_word(words)
false
d0409ff97d5e808da8eccfcf87ec22cd62f01278
dom-0/python
/regex/subslash1.py
315
4.4375
4
import re # Lets try and reverse the order of the day and month in a date # string. Notice how the replacement string also contains metacharacters # (the back references to the captured groups) so we use a raw # string for that as well. name = input("Enter your name") print(re.sub(r'(\w+) (\w+)', r'\2 \1', name))
true
daa3a87f521c5acaba11eb4bd9d3a99d6acf69e3
ErenBtrk/PythonDictionaryExercises
/Exercise14.py
724
4.3125
4
''' 14. Write a Python program to sort a dictionary by key. ''' import operator d = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} print('Original dictionary : ',d) sorted_d = sorted(d.items(), key=operator.itemgetter(0)) print('Dictionary in ascending order by value : ',sorted_d) sorted_d = dict( sorted(d.items(), key=operator.itemgetter(0),reverse=True)) print('Dictionary in descending order by value : ',sorted_d) ######################################################################################################################## color_dict = {'red':'#FF0000', 'green':'#008000', 'black':'#000000', 'white':'#FFFFFF'} for key in sorted(color_dict): print("%s: %s" % (key, color_dict[key]))
false
e9dcd408991a5e050a37bd21ecfa4c1458c474c1
Priyanshu729/hacktoberfest-2020
/python/find-greater.py
225
4.21875
4
# Finf the greater number def find_greater(x, y): # Todo: Write a function to return greater number return x if x > y else y x = int(input()) y = int(input()) print('Greater Number: {}'.format(find_greater(x, y)))
true
f731cb3a94ec8f58d9f89d9257d4d701773aa382
SmasterZheng/leetcode
/力扣刷题/1389按既定顺序创建目标数组.py
1,821
4.375
4
""" 给你两个整数数组 nums 和 index。你需要按照以下规则创建目标数组: 目标数组 target 最初为空。 按从左到右的顺序依次读取 nums[i] 和 index[i],在 target 数组中的下标 index[i] 处插入值 nums[i] 。 重复上一步,直到在 nums 和 index 中都没有要读取的元素。 请你返回目标数组。 题目保证数字插入位置总是存在。 示例 1: 输入:nums = [0,1,2,3,4], index = [0,1,2,2,1] 输出:[0,4,1,3,2] 解释: nums index target 0 0 [0] 1 1 [0,1] 2 2 [0,1,2] 3 2 [0,1,3,2] 4 1 [0,4,1,3,2] 示例 2: 输入:nums = [1,2,3,4,0], index = [0,1,2,3,0] 输出:[0,1,2,3,4] 解释: nums index target 1 0 [1] 2 1 [1,2] 3 2 [1,2,3] 4 3 [1,2,3,4] 0 0 [0,1,2,3,4] 解释:index列表的数,对应是输出列表target插入位置的下标,然后数就从nums里对应的index位置的数取出来 """ class Solution: def createTargetArray(self, nums, index): ''' 思路:python插入指定位置,利用insert() :param nums: :param index: :return: ''' target=[] for i in range(len(nums)): # target.insert(index[i],nums[i]) # return target # 评论里看到的纯切片操作,以要插入的数为分隔点,进行左右两边的相加,确实是个不错的方法 target = target[0:index[i]] + [nums[i]] + target[index[i]:] return target if __name__ == '__main__': Solution=Solution() nums = [1,2,3,4,0] index = [0,1,2,3,0] result = Solution.createTargetArray(nums,index) print(result)
false
d2caccb8bf15e89b72182dd6aa25cfdb21363191
gagigante/Python-exercises
/List 05/13.py
798
4.28125
4
# Questão 13. Construa uma função que desenhe um retângulo usando os # caracteres ‘+’ , ‘−’ e ‘| ‘. Esta função deve receber dois parâmetros, # linhas e colunas, sendo que o valor por omissão é o valor mínimo # igual a 1 e o valor máximo é 20. Se valores fora da faixa forem informados, # eles devem ser modificados para valores dentro da faixa de forma elegante. def rectangle(width, height): if width > 20: width = 20 elif width <= 0: width = 1 if height > 20: height = 20 elif height <= 0: height = 1 print('-+-' * width) z = '|' for i in range(height): print('|', ' ' * (width * 3 - 4), '|') print('-+-' * width) width = int(input('Digite a largura: ')) height = int(input('Digite a altura: ')) rectangle(width, height)
false
40df4027040183e286726f022e3e400c2eef975a
stan-andrei/python_upskilling
/exercices/assessment1/part6/practice3.py
963
4.5625
5
""" Write a program that asks the user how many Fibonacci numbers to generate and then generates them. Take this opportunity to think about how you can use functions. Make sure to ask the user to enter the number of numbers in the sequence to generate. (Hint: The Fibonacci sequence is a sequence of numbers where the next number in the sequence is the sum of the previous two numbers in the sequence. The sequence looks like this: 1, 1, 2, 3, 5, 8, 13, …) """ if __name__ == "__main__": def fibonacci(): num = int(input("How many Fibonacci numbers to generate:")) i = 1 if num == 0: fib = [] elif num == 1: fib = [1] elif num == 2: fib = [1, 1] elif num > 2: fib = [1, 1] while i < (num - 1): fib.append(fib[i] + fib[i - 1]) i += 1 return fib print(fibonacci()) input("Press the enter key to exit.")
true
4e4865a5af869ba1d05a8c008cb55ee0bbd3ec96
yzw1102/study_python
/partone/test3.py
789
4.40625
4
# 1.创建元组 # tuple1 = (1,2,'a','b') # tuple2 = 1,2,'a','b' # tuple3 = () # tuple4 = (123,) # tuple5 = (123) # print(tuple1) # print(tuple2) # print(tuple3) # print(tuple4) # print(tuple5) # 2.访问元组 # tuple1 = (1,2,'a','b') # tuple2 = 1,2,'a','b' # print(tuple1) # print(tuple1[0]) # print(tuple2) # print(tuple2[1]) # 3. # list1 = [123,345] # tuple1 = (1,2,'a','b',list1) # print(tuple1) # list1[0] = 'd' # list1[1] = 'e' # print(tuple1) # 4. # tuple1 = (1,2,'a','b') # tuple2 = ('d','e','f') # print(tuple1) # print(len(tuple1)) # print(tuple1 + tuple2) # print(tuple1*2) # print(2 in tuple1) # for x in tuple1: # print(x) # 5. tuple1 = (1,2,3) tuple2 = (4,5,6) # print(cmp(tuple1,tuple2)) print(max(tuple1)) print(min(tuple1)) print(tuple([1,2,3,4]))
false
f47fa8860c1932f176a697ef30f8c084613ef384
christopher-hesse/tenet
/scripts/grad_example.py
1,744
4.15625
4
def square(x): return x ** 2 def cube(x): return x ** 3 def multiply(x, y): return x * y def f(x, y): a = square(x) b = cube(y) c = multiply(a, b) return c def backward_multiply(x, y, grad_out): grad_in_x = y * grad_out grad_in_y = x * grad_out return grad_in_x, grad_in_y def backward_square(x, grad_out): grad_in = 2 * x * grad_out return grad_in def backward_cube(x, grad_out): grad_in = 3 * x ** 2 * grad_out return grad_in def backward_f(x, y, grad_z): # we actually need the intermediate values to call the backward functions # so re-calculate them here (normally we would just store them when running f() the first time) a = square(x) b = cube(y) _c = multiply(a, b) grad_a, grad_b = backward_multiply(a, b, grad_z) grad_y = backward_cube(y, grad_b) grad_x = backward_square(x, grad_a) return grad_x, grad_y # run the function normally x = 1.0 y = 2.0 z = f(x, y) print(f"f(x,y): {z}") # run the backward function grad_z = 1.0 # the initial grad value is set to 1 grad_x, grad_y = backward_f(x, y, grad_z) print(f"backward_f(x, y, grad_z): grad_x = {grad_x}, grad_y = {grad_y}") # check the backward function using finite differences # by making small changes to each input to find how the output changes def finite_differences(x, y, f, epsilon=1e-6): grad_x = (f(x + epsilon, y) - f(x - epsilon, y)) / (2 * epsilon) grad_y = (f(x, y + epsilon) - f(x, y - epsilon)) / (2 * epsilon) return grad_x, grad_y grad_x_fd, grad_y_fd = finite_differences(x, y, f) print(f"finite differences approximation: grad_x = {grad_x_fd}, grad_y = {grad_y_fd}")
true
fab4171d9c82757c8b04d5941e4562cd2b41d541
SanLatkar/codewayy_python_series
/Python-Task2/Tuple.py
1,369
4.625
5
#Working with methods of Tuple: #Tuples are Immutable so we can't do updation methods on Tuple. numbers = (25, 36, 49, 64, 81, 100, 121) # Creating a numbers tuple print("The tuple of numbers : ",numbers) count = numbers.count(25) # count() count how many times mentioned element is occured in Tuple print("\nThe occurence of 25 in the numbers tuple is: ", count) index = numbers.index(36) # index() gives us index of mentioned element in Tuple print("\nThe index of 36 is: ",index) length = len(numbers) # len() is used to extract length of Tuple print("\nThe length of the numbers tuple is: ", length) Max_number = max(numbers) # max() gives result as Largest element from Tuple print("\nThe maximum number of the numbers tuple is: ", Max_number) Min_number = min(numbers) # min() gives result as smallest element from Tuple print("\nThe minimum number of the numbers tuple is: ", Min_number) Sum =sum (numbers) # sum() gives result as sum of elements in Tuple print("\nThe sum of all elements in the tuple numbers is: ", Sum) list = [1, 11, 111, 1111] Tuple = tuple(list) # We can apply casting like this to convert list into Tuple print("\nThe tuple obtained by converting a list into tuple is: ", Tuple)
true
fe5bc7ec01c7fdc9db061e2c7056c081ca87eb66
Ishank-Coder/Pyprog
/calculator.py
2,462
4.25
4
def script(): # Program make a simple calculator that can add, subtract, multiply and divide using functions import math # This function adds two numbers def add(x, y): return x + y # This function subtracts two numbers def subtract(x, y): return x - y # This function multiplies two numbers def multiply(x, y): return x * y # This function divides two numbers def divide(x, y): return x / y # This function represent number in exoponent def exponent(x,y): return x**y print("Select operation.") print("1.Add") print("2.Subtract") print("3.Multiply") print("4.Divide") print("5.Exponent") print("6.square root") print("7.square") print("8.sin") print("9.cos") print("10.tan") print("11.factorial") print("12.log") # Take input from the user choice = input("Enter choice(1/2/3/4/5/6/7/8/9/10/11/12):") num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number(*if you are finding square or square root of number then enter the number in first time and in second simply enter 1): ")) if choice == '1': print(num1,"+",num2,"=", add(num1,num2)) elif choice == '2': print(num1,"-",num2,"=", subtract(num1,num2)) elif choice == '3': print(num1,"*",num2,"=", multiply(num1,num2)) elif choice == '4': print(num1,"/",num2,"=", divide(num1,num2)) elif choice == '5': print(num1,"**",num2,"=", exponent(num1,num2)) elif choice == '6': print(num1,"under root","=",math.sqrt(num1)) elif choice == '7': print(num1,"**",2,"=",(num1**2)) elif choice == '8': print("sin",num1,"/",num2,"=",math.sin(num1/num2)) elif choice == '9': print("cos",num1,"/",num2,"=",math.cos(num1/num2)) elif choice == '10': print("tan",num1,"/",num2,"=",math.tan(num1/num2)) elif choice == '11': fact=1 kl=1 while(kl <= num1): fact=fact*kl kl=kl+1 print("The factorial of " ,num1, "=", fact) elif choice == '12': if (num2 == 1): print("log",num1,"=",math.log(num1)) else: print("log",num1,"*",num2,"=",math.log(num1*num2)) else: print("Invalid input") restart = input("Would you like to calculate more?") if restart == "yes" or restart == "y": script() if restart == "n" or restart == "no": print(" Goodbye.") script()
true
cdb552a05ab1c7bcbc32b6813336641eb35a16cb
C16398141/Algorithm-and-DS-Arena
/dijkstra.py
2,983
4.125
4
# initialise the graph graph = dict() # the whole graph is a dictionary # the graph contain the node 'start' graph['start'] = {} # the start has two children nodes 'a' and 'b' graph['start']['a'] = 6 # it takes 6 units to go from start to a graph['start']['b'] = 2 # it takes 2 units to go from start to b ''' OUTPUT of 'graph' >>> graph {'start': {'a': 6, 'b': 2}, 'a': {'end': 1}, 'b': {'a': 3, 'end': 5}, 'end': {}} ''' # the graph also contain the node 'a' graph['a'] = {} graph['a']['end'] = 1 # it takes one unit to go from node 'a' to the end # this graph also contains the node 'b' graph['b'] = {} graph['b']['a'] = 3 # it takes 3 units to go from 'b' to 'a' graph['b']['end'] = 5 # it takes 5 units to go to the end from when at b # the last node contained in the graph is the 'end' graph['end'] = {} # the end node points to nothing. i.e it doesn't have a neighbours. # next create a hastable to store the cost of each node # this is the how many units it takes to come to this node counted from first node used # e.g from start to 'a' it takes 6 units, and from start to 'b' it takes 2 units. # but as the transversal continues this will change. # e.g from start then b then 'a' the cost to get to 'a' will be 5, this is the '5' it # the 2 it takes from the start to b plus the 3 it takes from b to a # if the cost of a node is not known it is initialised to infinity cost = {} infinity = float('inf') cost['a'] = 6 cost['b'] = 2 cost['end'] = infinity # add the parents. This will add the parent of each node. usefull for bacjtracking parent = {} parent['a'] = 'start' parent['b'] = 'start' parent['end'] = None # ----- the algorithm ----- def dijkstra(cost, parent): # keep track of nodes I have already proceeded. seen = set() node = find_lowest_cost_node(cost,seen) while node is not None: node_cost = cost[node] # get the cost if the current node node_neighbours = graph[node] # get the neighbours of the current node for neighbour in neighbours.keys(): # go through all the current node's neighbours new_cost = node_cost + node_neighbours[neighbour] if cost[neighbour] > new_cost: # if this neigbour has a higher cost, then # update it to this newer low cost found cost[neighbour] = new_cost # e.g to get from start to 'a' was 6, now start-> b + b-> a is now 5 # update the parent to the parent of the new low cost parent[neighbour] = node # e.g the parent of 'a' was originally 'start' now change it to 'b' seen.add(node) # mark the node as seen # go through the cost dictionary to get the node with the updated lowest cost node = find_lowest_cost_node(cost,seen) def find_lowest_cost_node(cost, seen): lowest_cost = float('inf') lowest_cost_node = None for node in cost: # go through all the keys node_cost = cost[node] # the the cost value of the current node if not node in seen and node_cost < lowest_cost: lowest_cost = node_cost lowest_cost_node = node return lowest_cost_node
true