blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
34cd3453ff8de1f95b60e93bd24e575870bcc669
Thiksha/Pylab
/prog7.py
439
4.21875
4
# Python program using NumPy # for some basic mathematical # operations import numpy as np # Creating two arrays of rank 2 x = np.array([[1, 2], [3, 4]]) y = np.array([[5, 6], [7, 8]]) # Creating two arrays of rank 1 v = np.array([9, 10]) w = np.array([11, 12]) # Inner product of vectors print(np.dot(v, w), "\n") # Matrix and Vector product print(np.dot(x, v), "\n") # Matrix and matrix product print(np.dot(x, y))
true
1359d33adaa10e2ba9022cc703ef855ccf7c9355
distracted-coder/Exercism-Python
/yacht/yacht.py
2,602
4.125
4
""" This exercise stub and the test suite contain several enumerated constants. Since Python 2 does not have the enum module, the idiomatic way to write enumerated constants has traditionally been a NAME assigned to an arbitrary, but unique value. An integer is traditionally used because it’s memory efficient. It is a common practice to export both constants and functions that work with those constants (ex. the constants in the os, subprocess and re modules). You can learn more here: https://en.wikipedia.org/wiki/Enumerated_type """ # Score categories. # Change the values as you see fit. YACHT = "YACHT" ONES = "ONES" TWOS = "TWOS" THREES = "THREES" FOURS = "FOURS" FIVES = "FIVES" SIXES = "SIXES" FULL_HOUSE = "FULL_HOUSE" FOUR_OF_A_KIND = "FOUR_OF_A_KIND" LITTLE_STRAIGHT = "LITTLE_STRAIGHT" BIG_STRAIGHT = "BIG_STRAIGHT" CHOICE = "CHOICE" def score(dice, category): numbers = {"ONES": 1, "TWOS": 2, "THREES": 3, "FOURS": 4, "FIVES": 5, "SIXES": 6} score = 0 if category in numbers: for i in dice: if i == numbers[category]: score += i return score if category == "YACHT": score = 50 for i in range(1, len(dice)): if dice[i] != dice[i -1]: score = 0 return score if category == "FULL_HOUSE": temp_dict = {} triple = 0 double = 0 for i in dice: if i not in temp_dict: temp_dict[i] = 1 else: temp_dict[i] += 1 for i in temp_dict: if temp_dict[i] >= 3: triple = i temp_dict[i] = 0 for i in temp_dict: if temp_dict[i] >= 2: double = i if triple != 0 and double != 0: return 3 * triple + 2 * double else: return 0 if category == "CHOICE": return sum(dice) if category == "FOUR_OF_A_KIND": temp_dict = {} quadruple = 0 for i in dice: if i not in temp_dict: temp_dict[i] = 1 else: temp_dict[i] += 1 for i in temp_dict: if temp_dict[i] >= 4: quadruple = i if quadruple != 0: return 4 * quadruple else: return 0 if category == "LITTLE_STRAIGHT": if sorted(dice) == [1, 2, 3, 4, 5]: return 30 else: return 0 if category == "BIG_STRAIGHT": if sorted(dice) == [2, 3, 4, 5, 6]: return 30 else: return 0
true
2c28a743d2e170b3380b74bb4bec5d0867b6c373
rlawjdgus199/python
/python/chapter_03.py
1,136
4.40625
4
# Chapter03-1 # 숫자형 # 파이썬 지원 자료형 """ int : 정수 float : 실수 complex : 복소수 bool : 불린 str : 문자열(시퀀스) list : 리스트(시퀀스) tuple : 튜플(시퀀스) set : 집합 dict : 사전 """ # 데이터 타입 str1 = "Python" bool = True str2= 'Anaconda' float = 10.0 # 10 == 10.0 int = 7 list = [str1, str2] print(list) dict = { "name" : "Machine Learning", "version" : 2.0 } tuple = (7, 8, 9) tuple2 = 7 ,8, 9 set = {3, 5, 7} # 데이터 타입출력 print(type(str1)) print(type(bool)) print(type(str2)) print(type(float)) print(type(int)) print(type(list)) print(type(tuple)) print(type(set)) # 숫자형 연산자 """ + - * """ i1 = 39 i2 = 9939 big_int1 = 777777777888382323 big_int2 = 343434323423411111 f1 = 1.234 f2 = 3.134 # + print(">>>>>>>>+") print("i1 + i2 :", i1 + i2) print("f1 + f2 :", f1 + f2) print("big_int1 + big_int2 :", big_int1 + big_int2) #형이 다른것끼리 연산하면 형변환이 자동으로 이뤄진다 # * print(">>>>>>>>*") print("i1 * i2 :", i1 * i2) print("f1 * f2 :", f1 * f2) print("big_int1 * big_int2 :", big_int1 + big_int2)
false
669ed897002906ec966e9e6c7d06a97230402f0a
noalez/Assignment1
/Q3.py
1,371
4.21875
4
def compare_subjects_within_student(subj1_all_students, subj2_all_students): """ Compare the two subjects with their students and print out the "preferred" subject for each student. Single-subject students shouldn't be printed. Choice for the data structure of the function's arguments is up to you. """ best_subject = {} names = subj1_all_students.keys() for name in names: if name != 'Subject': if str(subj2_all_students.get(name)) != 'None': subj2_all_students[name] = max(subj2_all_students[name]) subj1_all_students[name] = max(subj1_all_students[name]) if subj1_all_students[name]>subj2_all_students[name]: best_subject[name] = subj1_all_students['Subject'] elif subj1_all_students[name]<subj2_all_students[name]: best_subject[name] = subj2_all_students['Subject'] else: best_subject[name] = str(subj1_all_students[name])+' in both' print(best_subject) dict1 = {'Subject': 'Math', 'Amy': [90,80], 'Ben': [70,80], 'John': [55,65], 'Jane': [80,70], 'Alex': [100,90]} dict2 = {'Subject': 'History', 'Amy': [95,80], 'Ben': [70,60], 'John': [60,95], 'Alex': [55,90]} compare_subjects_within_student(dict1,dict2)
true
48dba6ea3eab7303ec08688d1964730d12a64a51
affandhia/ifml-pwa
/main/utils/naming_management.py
1,875
4.125
4
import re def dasherize(word): """Replace underscores with dashes in the string. Example:: >>> dasherize("FooBar") "foo-bar" Args: word (str): input word Returns: input word with underscores replaced by dashes """ s1 = re.sub('(.)([A-Z][a-z]+)', r'\1-\2', word) s2 = re.sub('([a-z0-9])([A-Z])', r'\1-\2', s1) return s2.replace('_','-').lower().replace(' ','') def camel_classify(word): """Creating class name based on a word that have a dash or underscore. Example:: >>> classify("foo_bar") >>> classify("foo-bar") "FooBar" Args: word (str): input word Returns: Class name based on input word """ return word.replace('_', ' ').replace('-', ' ').title().replace(' ','') def camel_function_style(word): """Creating class name based on a word that have a dash or underscore. Example:: >>> classify("foo_bar") >>> classify("foo-bar") "fooBar" Args: word (str): input word Returns: Funcation or var name styling based on input word """ classy_name = camel_classify(word) first_lowercase_letter = classy_name[:1].lower() rest_of_word = classy_name[1:] return first_lowercase_letter + rest_of_word def creating_title_sentence_from_dasherize_word(word): return word.replace('-',' ').title() #Specially used for ABS Microservice Framework naming convention def change_slash_and_dot_into_dash(word): return word.replace('/','-').replace('.','-') def change_slash_and_dot(word, replaced_string): return word.replace('/', replaced_string).replace('.', replaced_string) def remove_slash_and_dot(word): return word.replace('/', '').replace('.', '')
true
da8d524c61d86ce53ee5015ab6d9d577bba38054
DamianArado/OneDayOneAlgo
/odd-even.py
248
4.15625
4
#the given program is for brick sort/odd even sort arr=[2,1,3] for i in range(0,len(arr)-1,2): if(arr[i+1]<arr[i]): arr[i+1],arr[i]=arr[i],arr[i+1] for i in range(1,len(arr)-1,2): if arr[i+1]<arr[i]: arr[i+1],arr[i]=arr[i],arr[i+1] print(arr)
false
0c781cdc145f18c892b5eb8a6cfc5548451f1b85
abhishekk3/Practice_python
/monotonic_array.py
758
4.25
4
#Problem Statement: Given an array of integers, we would like to determine whether the array is monotonic (non-decreasing/non-increasing) or not. #Examples: #1 2 5 5 8->true #9 4 4 2 2->true #1 4 6 3->false #1 1 1 1 1 1->true def monotonic_arr(arr): num = arr[1] if arr [0] < arr [1]: for i in range(2,len(arr)): if arr[i] < num: return False return True elif arr [0] > arr [1]: for i in range(2,len(arr)): if arr[i] > num: return False return True else: return True a= [10,10,10,9,14] res=monotonic_arr(a) print(res)
true
43a6ed3e8d2afe9b208f4d790d2c784593bb16ce
djangoearnhardt/Exercism
/acronym.py
254
4.15625
4
# Convert a long phrase to its acronym print("Enter your long phrase, and I'll convert it to an acronym.") str = input() # str = str.split() str_len = len(str) output = '' for i in str.upper().split(): output += i[0] print(f"Your acronym is", output)
true
c375d8474b784e3f52b30b6469c79ba237266ebb
acLevi/cursoemvideo-python
/Mundo 3 - Estruturas Compostas/Exercícios/EX088.py
950
4.15625
4
# Exercício Python 088: Faça um programa que ajude um jogador da MEGA SENA a criar palpites.O programa vai perguntar quantos jogos serão gerados e vai sortear 6 números entre 1 e 60 para cada jogo, cadastrando tudo em uma lista composta. from random import randint from time import sleep qnt = int(input('Quantidade de jogos a sortear: ')) print(f'-=-= SORTEANDO {qnt} JOGO =-=-' if qnt == 1 else f'-=-= SORTEANDO {qnt} JOGOS =-=-') jogo = [] nums = [] # enquanto 'jogo' não estiver com 'qnt' de jogos while len(jogo) < qnt: # enquanto 'nums' não estiver com 6 valores while len(nums) <= 6: # gerando um randint novo a cada repetição r = randint(1,60) # se r não estiver em nums if nums.count(r) < 1: # adiciona-se r a nums nums.append(r) nums.sort() jogo.append(nums[:]) nums.clear() for c in range(0, qnt): print(f'Jogo {c+1}: {jogo[c]}') sleep(1)
false
b3cb22cbf696e9f6f15007875200cee80562e244
acLevi/cursoemvideo-python
/Mundo 3 - Estruturas Compostas/Exercícios/EX075.py
920
4.3125
4
# Exercício Python 075: Desenvolva um programa que leia quatro valores pelo teclado e guarde-os em uma tupla. No final, mostre: # A) Quantas vezes apareceu o valor 9. # B) Em que posição foi digitado o primeiro valor 3. # C) Quais foram os números pares # Declarando a tupla nums = tuple() # Lendo os quatros números e adcionando na tupla for c in range(1, 5): n = int(input(f'Digite o {c}º número: ')) nums += (n,) # a) Quantidade de vezes em que o número 9 apareceu if 9 in nums: print(f'O número 9 aparece {nums.count(9)} vezes na tupla.') else: print('O número não está na tupla.') # b) Posição do valor 3 if 3 in nums: print(f'O número 3 aparece na {nums.index(3) + 1}ª posição da tupla.') else: print('O número 3 não está na tupla') # c) Números pares print('Números pares contidos na tupla: ', end='') for n in nums: if n % 2 == 0: print(n, end=' ')
false
b7805ef70e9bb17b571c33df2a615fb1148846f0
MarcoBertoglio/Sistemi-e-reti
/es_3_vacanze.py
486
4.21875
4
#Nella serie di Fibonacci, ciascun numero della serie è la somma dei due numeri nella serie che lo precedono, ad esempio: #1, 1, 2, 3, 5, 8, 13 (...) #Scrivi una funzione ricorsiva che restituisce in output i numeri della sequenza di Fibonacci, #entro una soglia specifica impostata dall'utente. def fibonacci(val): if val <= 0: return 0 elif val == 1: return 1 else: return fibonacci(val-1) + fibonacci(val-2) print(fibonacci(20))
false
b0df635bce8cec3906bce434e50bb3b2420bb360
MrsPsRobot/1-reposit-rio
/tulpas.py
753
4.4375
4
print ("Tuplas são como lista mas não pode adicionar e nem remover 1 objeto, apenas a tupla inteira") tuplas=("tiago", "Python","udemy") print(tuplas) print ("Quantidade de posições na tuplas") print (len (tuplas)) print("\nO que tem em qual posição tuplas[]") print("tuplas[0]",tuplas[0]) print ("tuplas[1]",tuplas[1]) print("tuplas[2]",tuplas[2]) print("tuplas[1:2]",tuplas[1:2]) print ("tuplas[0:2]",tuplas[0:2]) print ("\ntuplas*3") print (tuplas*3) print ("tuplas+tuplas",tuplas+tuplas) print ("Perguntado um conteudo na tupla"," "'udemy" in tuplas"') print ("udemy" in tuplas) print ("\n Transformando tuplas em lista","-->tuplas2=tuple(lista)") lista=[1,2,'tiago'] print (lista) tuplas2=tuple(lista) print (tuplas)
false
dd1f5d1c90422bbb32d0e1303b576e6b1ea25c38
RodrigoNeto/cursopythonyt
/aula3/aula3.py
633
4.40625
4
""" STR - String Linguagem de tipagem dinamica Tudo que estiver dentro de aspas simples ou duplas é consideravél uma string """ print('Essa é uma string') print("Essa é uma string") print("Essa é uma 'string' (str).") #Exemplo de string com aspas para exibição, serve para simples e dupla print('Essa é uma "string" (str).') #************ Preferivel utilizar essa forma ************ print("Essa é uma \"string\" (str).") print('Essa é uma \'string\' (str).') print('Essa é uma \n (str).') print(r'Essa é uma \n (str).') # O r faz com que nada que esta dentro do parametro seja executado
false
f3f454964a38f7dcada615b606faf856005691d5
shadumdum/basic-pyhthon-
/quiz.py
334
4.15625
4
nama = input("masukan nama:") umur = input("masukan umur:") alamat = input("masukan alamat anda:") print("nama saya adalah"+ " "+ nama) print("umur saya adalah"+ " "+ umur) print("alamat saya di"+ " "+ alamat) #problem di format print ("nama saya adalah {}, umur saya{},dan alamat saya di {}".format(nama,umur,alamat))
false
2ad6f815dbd3d0bdc29d9902486701b6790dbfa5
Emaasit/think-python
/card.py
1,757
4.5625
5
"""This is Chapter 18: Inheritance Learning Python programming using the book titled Think Python, 2nd Edition by Allen Downey http://thinkpython2.com Copyright 2017 Daniel Emaasit License: http://creativecommons.org/licenses/by/4.0/ """ from random import shuffle class Card: """Represents the cards in deck Attributes ---------- suits : int ranks : int """ suit_names = ['Clubs', 'Diamonds', 'Hearts', 'Spades'] rank_names = [None, 'Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King'] def __init__(self, suit = 0, rank = 2): """Initialize a Card object """ self.suit = suit self.rank = rank def __str__(self): return "%s of %s" % (Card.suit_names[self.suit], Card.rank_names[self.rank]) def __lt__(self, other): # using tuple comparison t1 = self.suit, self.rank t2 = other.suit, other.rank return t1 < t2 class Deck: """Represents a deck of 52 cards""" def __init__(self): self.cards = [] for suit in range(4): for rank in range(1, 14): card = Card(suit, rank) self.cards.append(card) def __str__(self): res = [] for card in self.cards: res.append(str(card)) return "\n".join(res) def remove_card(self): return self.cards.pop() def add_card(self, card): self.cards.append(card) def shuffle_deck(self): shuffle(self.cards) class Hand(Deck): """Represents a Hand which inherits from Deck class""" def __init__(self, label = ""): self.cards = [] self.label = label
true
71c6620a5721da6a501c998fe24e8809e5ba7961
tentao7/Python
/Learn+Python_Full+course+for+beginners-Copy1.py
952
4.15625
4
# coding: utf-8 # In[1]: print("hello world") # In[2]: print(" /l") print(" / l") print(" / l") print(" /___l") # In[3]: print("There once a man named George,") print("he was 70 years old.") print(" He reallly like the name George,") print("but did't like being 70.") # In[4]: character_name = "Tom" # string character_age = 50 #integer is_Male = False #boolean print("There once a man named "+ character_name+",") print("he was %i years old.", character_age) character_name = " Mike" print(" He reallly like the name"+ character_name+",") print("but did't like being %i", character_age) # In[5]: phrase = "Giraffe Academy" print("Giraffe\"Academy") # print " # In[6]: phrase = "Giraffe Academy" print(phrase + " is cool") # In[11]: print(phrase.lower()) #print(phrase.upper()) print(phrase.isupper()) print(phrase.upper().isupper()) # In[12]: print(len(phrase)) # In[14]: print(phrase[0])
false
166a849b4c82c1f0486cce56a0dcf17cf9e0ca9f
foureyes/csci-ua.0479-spring2021-001
/resources/code/class11/fraction.py
1,429
4.125
4
class Fraction: def __init__(self, n, d): self.n = n self.d = d # this means that this method can be called without instance # and consequently, no self is needed # instead, you call it on the actual class itself # Fraction.gcf() @staticmethod def gcf(a, b): # go through every possible factor # check if it divides evenly into both # return the largest one cur_gcf = 1 for factor in range(1, a + 1): if a % factor == 0 and b % factor == 0: cur_gcf = factor return cur_gcf def reduce(self): gcf = Fraction.gcf(self.n, self.d) return Fraction(self.n // gcf, self.d // gcf) def __str__(self): return "{}/{}".format(self.n, self.d) def __repr__(self): # we can call methods that already defined return self.__str__() def add(self, other): new_n = (self.n * other.d) + (other.n * self.d) new_d = self.d * other.d return Fraction(new_n, new_d) def __add__(self, other): return self.add(other) def __eq__(self, other): return self.n == other.n and self.d == other.d a = Fraction(1, 2) b = Fraction(6, 8) c = Fraction(1, 3) fractions = [a, b, c] print(fractions) print(a.add(c)) print(a + c) print(a == c) print(a == Fraction(1, 2)) print(Fraction.gcf(9, 12)) print(Fraction(4, 8).reduce())
true
5ce4d0d839d165438d3149d00e6ceea0bd48d2fa
foureyes/csci-ua.0479-spring2021-001
/assignments/hw03/counting.py
593
4.46875
4
""" counting.py ===== use *while* loops to do the following: * print out "while loops" * use a while loop to count from 2 up-to and including 10 by 2's. * use another while loop to count down from 5 down to 1 use *for* loops to do the following: * print out "for loops" * use a for loop to count from 2 up-to and including 10 by 2's. * use another for loop to count from 5 down to 1. * comment your code (name, date and section on top, along with appropriate comments in the body of your program) example output: while loops 2 4 6 8 10 5 4 3 2 1 for loops 2 4 6 8 10 5 4 3 2 1 """
true
c9f5850173477fdec74a2cf3eeaea216a5d221b7
foureyes/csci-ua.0479-spring2021-001
/_includes/classes/17/count.py
315
4.1875
4
def count_letters(letter, word): """returns the number of times a letter occurs in a word""" count = 0 for c in word: if c == letter: count += 1 return count assert 3 == count_letters("a", "aardvark"), "should count letters in word" assert 0 == count_letters("x", "aardvark"), "zero if no letters in word"
true
33827cee45fdaf7aa3210750392d51b51c4a58f9
foureyes/csci-ua.0479-spring2021-001
/resources/code/class04_return.py
766
4.375
4
""" return is a statement a value has to be on the right hand side that value can be an expression (that will be evaluated before the return) and it does 2 things: * immediately stops the function * gives back the value / expression to the right of it return statements have to be in a function they can be in a loop, as long as that loop is in a function """ """ def experiment(): print(1) return 'foo' print(2) experiment() """ """ def experiment(): for i in range(5): return i print(experiment()) # function ends on first iteration! """ """ def experiment(): for i in range(5): print(i) # after the for loop, i will still refer to its last value return i print('out of function', experiment()) """
true
2275341721c13fc2d71d67e2ffa1ea7d5cb81bcc
foureyes/csci-ua.0479-spring2021-001
/_includes/classes/18/caesar_encrypt_v3.py
738
4.25
4
def caesar_encrypt(s): """encrypts a string by rotating each letter 23 places to the right""" uppercase_start, lowercase_start = 65, 97 alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' shift = 23 translation = '' for c in s: letter_pos = alphabet.find(c.upper()) offset = (letter_pos + shift) % 26 if c.isupper(): translation += chr(uppercase_start + offset) elif c.islower(): translation += chr(lowercase_start + offset) else: translation += c return translation print(caesar_encrypt('Hello world! zzz')) print(caesar_encrypt('abc xyz')) expected = 'Qeb nrfzh yoltk clu grjmp lsbo qeb ixwv ald.' observed = caesar_encrypt('The quick brown fox jumps over the lazy dog.') assert expected == observed, 'test encryption'
false
3df9bf90f72f82039043e5db9b15d36424e2a5b6
foureyes/csci-ua.0479-spring2021-001
/_includes/classes/15/factorial_iterative_version_user_input.py
214
4.21875
4
def factorial(n): product = 1 for i in range(n, 0, -1): product = product * i return product user_input = input("Give me a number, I'll give you the factorial\n>") num = int(user_input) print(factorial(num))
true
244f4199d414d124c61646de18df4e6cfa1f30b8
foureyes/csci-ua.0479-spring2021-001
/resources/code/class05.py
2,109
4.46875
4
# go over some of the "old" slides # try a sample "quiz" question(s) ... practice for the upcoming # field some homework questions # go over strings # or go over more intermediate level stuff w/ lists """ >>> def foo(bar): ... """ """foo will print out the argument passed in""" """ ... print(bar) ... >>> help(foo) >>> # docstrings is_leap_year... """ # call the function # print out the result # does the result match my expectation # call the function twice # automatically test the observed result vs your expected result # assert statement # assert boolean expression, "description" # assert oberved == expected, "description of the test" """ def is_short_string(s): return len(s) < 3 #return True assert is_short_string('hello') == False, "this test determines if function returns false if we have a long string" assert is_short_string('') == True, "returns true if string is less than 3 chars" """ """ designing functions create a chart called input, output and processing input - what are the parameters? output - what's the return value (NOT WHAT IS PRINTED) processing - what goes in the body my_abs <-- input: * a number output: * a number, the absolute value of the input processing * whatever calculation you have to make """ """ in the doc string is_leap_year(y) y: int - the year used to determine if leap year our not return: bool - True or False depending on if year is leap year processing: describe the algo you might use """ """ the most common case for no params is a main """ """ def main(): name = input('what is your name?') print(name) main() """ """ def foo(): s = "bar" # no return result = foo() print(result) """ # if there's no return, then function gives back None # None is a special value that means NO VALUE result = print('hello') # print does not return anything!!!! <-- None print(result) """ def print() show something on screen but don't return anything """ # hello # None # it will def print out None
true
0497b83fab0d8c6f4eb21717c2ffdb9f4717f926
foureyes/csci-ua.0479-spring2021-001
/resources/code/class07_redact_dna.py
1,561
4.21875
4
""" redact(words, illegal_words) word is a list of strings illegal_words also a list of strings if one of the strings in words exists in illegal words then "replace" the first three letters with dashes otherwise, word stays the same if less than 3, then all chars returns an entirely new list composed of censored words """ """ def redact(words, illegal_words): new_words = [] for word in words: if word in illegal_words: if len(word) <= 3: redacted_word = len(word) * '-' else: redacted_word = '---' + word[3:] new_words.append(redacted_word) else: new_words.append(word) return new_words print(redact(['a', 'very', 'delicious', 'cake', 'for', 'me'], ['delicious', 'cake', 'me'])) """ """ codons 3 of ACTG | \/ AAG-CCA-ATG CAG-TCA """ """ import random def gen_dna(codons): dna = '' for i in range(codons): # if we are on the last index.... dna += gen_codon() if i < codons - 1: dna += '-'; return dna def gen_codon(): letters = 'ACTG' codon = '' for i in range(3): n = random.randint(0, 3) letter = letters[n] codon += letter return codon print(gen_dna(3)) print(gen_dna(7)) """ """ # split and join # split turn string into list # join turn list into string # both are called as methods on a string names = 'alice and bob and carol' names_as_list = names.split(' and ') print(names_as_list) print('---'.join(names_as_list)) """
true
58a7b172b7f719eca24e0f98780dc5056daa0a3e
foureyes/csci-ua.0479-spring2021-001
/assignments/hw03/grade.py
1,073
4.5
4
""" grade.py ===== Translate a numeric grade to a letter grade. 1. Ask the user for a numeric grade. 2. Use the table below to calculate the corresponding letter: 90-100 - A 80-89 - B 70-79 - C 60-69 - D 0-59 - F 3. Print out both the number and letter grade. 4. If the value is not numeric, allow the error to happen. 5. However, if the number is not within the ranges specified in the table, output: "Could not translate %s into a letter grade" where %s is the numeric grade" __COMMENT YOUR SOURCE CODE__ by * briefly describing parts of your program * including your name, the date, and your class section at the top of your file (above these instructions) Example Output (consider text after the ">" user input): Run 1: ----- What grade did you get? > 59 Number Grade: 59 Letter Grade: F Run 2: ----- What grade did you get? > 89 Number Grade: 89 Letter Grade: B Run 3: ----- What grade did you get? > 90 Number Grade: 90 Letter Grade: A Run 4: ----- What grade did you get? > -12 Couldn't translate -12 into a letter grade """
true
64153c77965ffd4fc5ecab9c382e17c496b9ed6b
foureyes/csci-ua.0479-spring2021-001
/assignments/hw06/translate_passage.py
2,885
4.25
4
""" translate_passage.py ===== Use your to_pig_latin function to translate an entire passage of text. Do this by importing your pig_latin module, and calling your to_pig_latin function. You can use any source text that you want! For example: Mary Shelley's Frankenstein from Project Gutenberg: http://www.gutenberg.org/cache/epub/84/pg84.txt Or... the Hacker Manifesto from phrack http://phrack.org/issues/7/3.html Here's an example of using Mary Shelley's Frankenstein. Taking The second paragraph in "Letter 1"... ----- I am already far north of London, and as I walk in the streets of Petersburgh, I feel a cold northern breeze play upon my cheeks, which braces my nerves and fills me with delight. ... Would be translated to... ----- i amway alreadyway arfay orthnay ofway ondonlay, andway asway i alkway inway ethay treetssay ofway etersburghpay, i eelfay a oldcay orthernnay reezebay laypay uponway ymay eekschay, hichway racesbay ymay ervesnay andway illsfay emay ithway elightday. This program can be implemented two ways: 1. (easy) using a built string method called split to break up the passage into individual words only using space as a word boundary 2. (medium) manually break apart the passage by looping and accumulating characters, using space non-letter characters as word boundaries Step-by-step instructions: 1. Bring in your pig_latin module using import 2. Copy a large paragraph as a triple quoted string and assign this string to a variable name. 3. Write a function that will: a. one parameter, a string, the entire passage to be translated. b. return a translated version of the string by using the pig latin function (that only translates single words) 4. To do this treat all consecutive letters as words. Note that numbers, punctuation and white space do not count as "letters". Translate each word and create a string that represents the translation of the full text. * ALTERNATIVELY, an easy way to deal with breaking up a string is by using the string method called split: * s = 'the hacker manifesto' * words = s.split(' ') # words is ['the', 'hacker', 'manifesto'] 7. Print out the result of calling your translate_passage function on a paragraph from Frankenstein HINT for the standard version (don't read this until you've tried writing the pseudocode for the above specifications on your own) 1. Accumulate two strings... your current word, and the actual translation. 2. Go through every character, collecting them into a word. 3. When you encounter a non letter character (use islpha), take what you currently have as a word, translate it, and add it to the translation 4. Add the non letter character to the translation 5. Reset your current word to empty string and go on with the loop (This is just one possible implementation; there are other ways to do this!) """
true
1fb70af92655eb5feeefcdb9b69a6eac5bab9db7
julienawilson/data-structures
/src/shortest_path.py
1,492
4.15625
4
"""Shortest path between two nodes in a graph.""" import math def dijkstra_path(graph, start, end): """Shortest path using Dijkstra's algorithm.""" path_table = {} node_dict = {} # try: # infinity = math.inf # except: infinity = float("inf") for node in graph.nodes(): path_table[node] = [None, infinity] node_dict[node] = infinity path_table[start][1] = 0 node_dict[start] = 0 while node_dict: shortest_dist_node = min(node_dict, key=node_dict.get) current_node_val = shortest_dist_node if current_node_val == end: break node_dict.pop(current_node_val) for child in graph.neighbors(current_node_val): current_node_distance = path_table[current_node_val][1] for edge in graph.node_dict[current_node_val]: if edge[0] == child: edge_length = edge[1] trial_distance = current_node_distance + edge_length if trial_distance < path_table[child][1]: path_table[child][1] = trial_distance node_dict[child] = trial_distance path_table[child][0] = current_node_val current = end total_length = path_table[end][1] path_list = [current] while current is not start: path_list.append(path_table[current][0]) current = path_table[current][0] return "Total length: {}, Path: {}""".format(total_length, path_list[::-1])
true
4713b6f84dd3413a20d71fe230fdcf2b499a2621
fermolanoc/sw-capstone
/lab2/student_dataclass.py
676
4.3125
4
from dataclasses import dataclass @dataclass # dataclass decorator to simplify class definition class Student: # define attributes with data types -> this usually goes on __init__ method along with self name: str college_id: int gpa: float # override how info will be printed def __str__(self): return f'Student: {self.name}\nCollege id: {self.college_id}\nGPA: {self.gpa}\n' def main(): # Create Students instances alice = Student('Alice Cooper', 12345, 4.0) meli = Student('Melissa Cobo', 12124, 3.99) ethan = Student('Ethan Ludovick', 99882, 2.001) # Print each student data print(alice) print(meli) print(ethan) main()
true
9697410fe37ce6a23ed05209a1f203ffd532cbc1
codingram/courses
/python-for-everybody/08_file_count.py
712
4.28125
4
# Exercise 5: # # Open the file mbox-short.txt and read it line by line. When you find a line # that starts with 'From ' like the following line: # # From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 # # You will parse the From line using split() and print out the second word in # the line (i.e. the entire address of the person who sent the message). Then # print out a count at the end. fname = input("Enter file name: ") fh = open(fname) count = 0 for line in fh: line = line.rstrip() if not line.startswith("From "): # Different solution in Ex.2 continue word = line.split() print(word[1]) count = count + 1 print("There were", count, "lines in the file with From as the first word")
true
ead7827cba391e26589a66717709406c0a27001b
codingram/courses
/python-for-everybody/08_list_max_min.py
586
4.46875
4
# Exercise 6: # # Rewrite the program that prompts the user for a list of numbers and prints out # the maximum and minimum of the numbers at the end when the user enters “done”. # Write the program to store the numbers the user enters in a list and use the # max() and min() functions to compute the maximum and minimum numbers after the # loop completes. mml = [] while True: mmdata = input("Enter a number: ") if mmdata == "done": break mmdata = float(mmdata) mml.append(mmdata) print("Maximum value is:", max(mml)) print("Minimum value is:", min(mml))
true
d847f9cc90b307d3f6aeb41d3841b26fe94fdf66
codingram/courses
/MITx6001x/edx/ps1/ps1_3.py
815
4.34375
4
""" Assume s is a string of lower case characters. Write a program that prints the longest substring of s in which the letters occur in alphabetical order. For example, if s = 'azcbobobegghakl', then your program should print: Longest substring in alphabetical order is: beggh In the case of ties, print the first substring. For example, if s = 'abcbcd', then your program should print: Longest substring in alphabetical order is: abc """ # s = 'abcbcd' s = "azcbobobegghakl" # s = 'aaaaaaaaaaaabaaaaaaaaaazaaaaaaaaaafaaaaaaaaayaaaaaaaa' strg = s[0] for let in s[1:]: strg = strg + let if strg[-1] <= let else strg + " " + let strList = strg.split() largest = "" for i in strList: if len(i) > len(largest): largest = i print("Longest substring in alphabetical order is:", largest)
true
db451f5ab9deb908f5bb811ec0ceb2b881c86305
stepik/SimplePyScripts
/is_even__is_odd.py
402
4.15625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'ipetrash' def is_even(num): return num % 2 == 0 def is_odd(num): return not is_even(num) def is_even_2(num): return num & 1 == 0 if __name__ == '__main__': for i in range(10): print('{} is even: {}, {}'.format(i, is_even(i), is_even_2(i))) print('{} is odd: {}'.format(i, is_odd(i))) print()
false
8f8c494b841104a69bea119b5a278f74479070a3
bestyoucanbe/joypython0826-b
/dictionaryOfWords.py
1,599
4.8125
5
# You are going to build a Python Dictionary to represent an actual dictionary. Each key/value pair within the Dictionary will contain a single word as the key, and a definition as the value. Below is some starter code. You need to add a few more words and definitions to the dictionary. # After you have added them, use square bracket notation to output the definition of two of the words to the console. # Lastly, use the for in loop to iterate over the KeyValuePairs and display the entire dictionary to the console. """ Create a dictionary with key value pairs to represent words (key) and its definition (value) """ word_definitions = dict() """ Add several more words and their definitions Example: word_definitions["Awesome"] = "The feeling of students when they are learning Python" """ # Define different keys in the dictionary. word_definitions["Exciting"] = "It is exciting to learn a new language" word_definitions["Challenging"] = "It is challenging to learn a new computer language" """ Use square bracket lookup to get the definition of two words and output them to the console with `print()` """ # Lookup the definition of each item in the dictionary. definition_of_exciting = word_definitions["Exciting"] definition_0f_challenging = word_definitions["Challenging"] """ Loop over the dictionary to get the following output: The definition of [WORD] is [DEFINITION] The definition of [WORD] is [DEFINITION] The definition of [WORD] is [DEFINITION] """ for eachword in word_definitions: print(f'The definition of {eachword} is {word_definitions[eachword]}')
true
b9ed663fdd97171b8ddeb8bb848b83645a93bf8e
frubilarz/datainfo
/python/main.py
795
4.1875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import random def quicksort(lista): if len(lista) > 1: pivote = lista[0] # Escogemos el pivote, por defecto será el primer elemento de la lista menores = [x for x in lista[1:] if x < pivote] # Una sublista con los elementos menores o iguales al pivote mayores = [x for x in lista[1:] if x >= pivote] # Una sublista con los elementos mayores o iguales al pivote return quicksort(menores) + [pivote] + quicksort(mayores) # Llamada recursiva al algoritmo sobre las sublistas else: return lista # Ya ordenada if __name__ == '__main__': l = random.sample(xrange(100), 10) # Toma 10 números aleatorios, desde el 0 al 100 print "Lista aleatoria:", l print "Lista ordenada :", quicksort(l)
false
752c3be3dfe48be63fee20b97a213c3b6c3a2afc
mrodolfo1981/python
/ordenandolistas.py
449
4.125
4
lista = [124,345,5,72,46,6,7,3,1,7,0] print("lista desordenada") print (lista) lista.sort()#esse metodo faz a ordenacao da lista print("Lista Ordenada") print(lista) lista1 = [40,39,33,20,11,5,8,2,1] print("lista1 desordenada") print(lista1) print("lista1 ordenada pelo metodo sorted") lista1 = sorted(lista1)#esse metodo faz a ordenaçao e o resultado vem como retorno print(lista1) lista.sort(reverse=True) print("lista revertida") print(lista)
false
0b7e61fb66ee63523dd111eec1e8b4184d373191
Ayush05m/coding-pattern
/Python Codes/longestSubString.py
682
4.125
4
def longest_unique_subString(str1): windowstart = 0 max_length = 0 index_map = {} for windowend in range(len(str1)): right = str1[windowend] if right in index_map: windowstart = max(windowstart, index_map[right] + 1) index_map[right] = windowend max_length = max(max_length, windowend - windowstart + 1) return max_length if __name__ == '__main__': print("Length of the longest substring: " + str(longest_unique_subString("aabccbb"))) print("Length of the longest substring: " + str(longest_unique_subString("abbbb"))) print("Length of the longest substring: " + str(longest_unique_subString("abccde")))
true
68f7c4431ce6d5e6ba0cff983ed6f23603434d22
zahraishah/zahraishah.github.io
/ErdosRenyi_graphs.py
1,217
4.3125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Jun 13 11:43:46 2020 @author: malaikakironde """ #This document goes over implementing a random graph using #the Erdos-Renyi Model import sys import matplotlib.pyplot as plt import networkx as nx import random def erdos_renyi(G,p): #finding all possible edges in G for i in G.nodes(): for j in G.nodes(): #the edges do not count if they start and end at the same node if i != j: r = random.random() #if the random number is less than the probabilty, then #an edge will be drawn if r <= p: G.add_edge(i,j) #if not, the edge will not be drawn else: continue def graph_G(): #G(n,p) n = int(input('Enter the number of nodes: ')) p = float(input('Enter a number between 0 and 1 for the probability: ')) #Creating an empty graph G = nx.Graph() #Adding nodes and edges to the graph G.add_nodes_from([i for i in range(n)]) erdos_renyi(G,p) #Drawing the graph nx.draw(G) plt.show() graph_G()
true
c085dc3d74bbb82b00b1de60f434a9a0dd53be3e
milenacudak96/python_fundamentals
/labs/04_conditionals_loops/04_07_search.py
365
4.15625
4
''' Receive a number between 0 and 1,000,000,000 from the user. Use while loop to find the number - when the number is found exit the loop and print the number to the console. ''' number = int(input('enter the number between 0 and 1000000000: ')) while number in range(1, 1000000000): print(number) break else: int(input('enter the other number: '))
true
ec8885cb263e5d23fc69f837f83882bab1d48d23
milenacudak96/python_fundamentals
/labs/04_conditionals_loops/04_01_divisible.py
333
4.40625
4
''' Write a program that takes a number between 1 and 1,000,000,000 from the user and determines whether it is divisible by 3 using an if statement. Print the result. ''' number = int(input('enter the number between 1 and 1000000000: ')) if number % 3 == 0: print('its divisible by 3') else: print('its not divisible by 3')
true
d12615c7de5b1a340a8469fb265b15aa3c5fc7b3
milenacudak96/python_fundamentals
/labs/07_classes_objects_methods/07_02_shapes.py
797
4.5
4
''' Create two classes that model a rectangle and a circle. The rectangle class should be constructed by length and width while the circle class should be constructed by radius. Write methods in the appropriate class so that you can calculate the area (of the rectangle and circle), perimeter (of the rectangle) and circumference of the circle. ''' class Rectangle: def __init__(self, length, width): self.length = length self.width = width def perimeter(self): return (2 * self.length) + (2 * self.width) class Circle: def __init__(self, radius): self.radius = radius def circumference(self): return 2 * 3.14 * self.radius Circle = Circle(5) print(Circle.circumference()) Rectangle = Rectangle(6, 5) print(Rectangle.perimeter())
true
35968dce2d4f437986f46c8762d798a869a32eec
ashutoshnarayan/Coursera
/guess_the_number.py
2,461
4.34375
4
# "Guess the number" mini-project # input will come from buttons and an input field # all output for the game will be printed in the console import simplegui import math import random # initialize global variables used in your code count_of_guesses = 7 game_range = 100 secret_number = random.randrange(0, 100) startgame = 0 # By default game in the range 0-100 starts. print "New Game. Range in between 0 to 100" print "Number of remaining guesses is ", count_of_guesses # define event handlers for control panel def range100(): # button that changes range to range [0,100] and restarts global count_of_guesses, game_range secret_number = random.randrange(0,100) count_of_guesses = 7 game_range = 100 print "New Game. Range in between 0 to 100" print "Number of remaining guesses is ", count_of_guesses def range1000(): # button that changes range to range [0,1000] and restarts global count_of_guesses, game_range count_of_guesses = 10 game_range = 1000 secret_number = random.randrange(0,1000) print "New Game. Range is between 0 to 1000" print "Number of remaining guesses is ", count_of_guesses def get_input(guess): # main game logic goes here global count_of_guesses, secret_number, startgame guess = int(guess) print "Guess was:" ,guess count_of_guesses -= 1 if guess == secret_number: print "Number of remaining guesses is ", count_of_guesses print "Correct.." startgame = 1 if guess < secret_number: print "Number of remaining guesses is ", count_of_guesses print "Lower.." if guess > secret_number: print "Number of remaining guesses is ", count_of_guesses print "Higher.." if count_of_guesses == 0: startgame = 1 if guess != secret_number: print "You ran out of guesses. Correct number was", secret_number if(startgame == 1): if(game_range == 100): range100() else: range1000() startgame = 0 # create frame f = simplegui.create_frame("Guess the number", 200, 200) # register event handlers for control elements f.add_button("Range is [0,100]", range100, 200) f.add_button("Range is [0,1000]", range1000, 200) f.add_input("Enter the number", get_input, 200) # start frame f.start()
true
654adb4d0cfffff4f410b5408e631eeeb9d4856e
mannhuynh/Python-Codes
/OOP/APP_1/water.py
1,271
4.5625
5
class Water: """ How do you access a class variable (e.g., boiling_temperature ) from within a method (e.g., from state)? The answer is: You can access class variables by using self. So, in our example, you would write self.boiling_temperature. See the state method below for an illustration. The key takeaway here is that even though boiling_temperature is a class variable (i.e., it belongs to the class and not to the instance of the class), such a variable can still be accessed through the instance (i.e., through self). So, class variables belong to the class, but they also belong to the instance created by that class. """ boiling_temperature = 100 freezing_temperature = 0 def __init__(self, temperature): self.temperature = temperature def state(self): # Return 'solid' if water temp is less or equal than 0 if self.temperature <= self.freezing_temperature: return 'solid' # Return 'liquid' if water temp is between 0 and 100 elif self.freezing_temperature < self.temperature < self.boiling_temperature: return 'liquid' # Return 'gas' in other scenarios (water temp higher than 100) else: return 'gas'
true
f78b8aa5f0118d4dc47e1e667a1c97dfe2c12f3b
lionel-antony/pycode
/py01/string_use_02.py
718
4.34375
4
#first_name = 'Lionel' #last_name = 'Antony' #print(first_name + last_name) #print('Hello ' + first_name + ' ' + last_name) first_name = input('What is your first name? ') last_name = input('What is your last name? ') #print('Hello ' + first_name + ' ' + last_name) #print('Hello ' + first_name.capitalize() + ' ' + last_name.capitalize()) #print('Hello, ' + first_name + ' ' + last_name) #print('Hello, {} {}'.format(first_name, last_name)) #print('Hello, {0} {1}'.format(first_name, last_name)) #print('Hello, {1} {0}'.format(first_name, last_name)) #print(f'Hello, {first_name} {last_name}') #output = 'Hello, {1} , {0}'.format(first_name, last_name) output = f'Hello, {first_name} , {last_name}' print(output)
false
051dc584bef186573140404b6de74f8ba9fc1fdf
Mariobouzakhm/Hangman
/hangman.py
2,574
4.1875
4
import filemanager, random def createWordList(word): lst = list() for i in range(len(word)): lst.append('-') return lst def modifyWordList(lst, word, letter): for i in range(len(word)): if word[i] == letter: lst[i] = letter return lst #Open a File Handle with the file containing all the words file = open('wordlist.txt', 'r') #list of all the words contained in the hangman dictionnary lst = filemanager.readLines(file) #Number of wrong choices the user can make while guessing a word chances = 8 while True: choice = input('Enter \'new\' to start a new game or \'done\' to exit the game - ').lower() if choice == 'new': print('Starting a new game....') #Word the user need to guess word = lst[random.randint(0, len(lst) -1)].lower() print(word) #Choices that are still available for the user choices = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] #Holds the correct letters a user has guessed with the remaining ones as well wordchoices = createWordList(word) ##Holds the wrong guesses a user has made wrong = list() while True: letter = input('Enter a new letter - ').lower() while letter not in choices: print('Invalid Choice') print('Choices: ', choices) letter = input('Enter a new letter - ').lower() index = word.find(letter) if index != -1: choices.remove(letter) print('Correct Letter: ', letter) wordchoices = modifyWordList(wordchoices, word, letter) print(wordchoices) if '-' not in wordchoices: print('Successfully Completed the Game !') break else: print('You are still missing some letters.') continue else: choices.remove(letter) print('Wrong Letter: ', letter) wrong.append(letter) print(wrong) if len(wrong) > chances: print('Game Lost. You have ran out of chances') break; else: print('You still have %d chances.' % (chances - len(wrong))) continue elif choice == 'done': print('Exiting the system...') break else: print('Wrong Argument')
true
7ccc450c398e40e9e8c97b927d20dbf0d4f83b7b
sergiosanchezbarradas/Udemy_Masterclass_Python
/sequences/automate boring.py
551
4.1875
4
# This program says hello and asks for my name. print('Hello, world!') print('Whats your name') your_name = input() print('nice to meet you ' + your_name) length_name = (len(your_name)) print('your name is {} characters long'.format(length_name)) print("What's your age") age = input() print("You will be " + str(int(age)+1) + " next year.....old fella") #Casting #If you want to specify the data type of a variable, this can be done with casting. #Example #x = str(3) # x will be '3' #y = int(3) # y will be 3 #z = float(3) # z will be 3.0
true
c17dcbc7c35639c2aef6d0a4d7fc8371b05b7620
ParkHanBin0820/Python
/reversed.py
280
4.1875
4
list_a = [1, 2, 3, 4 ,5] list_reversed = reversed(list_a) print("# reversed() 함수") print("reversed([1, 2, 3, 4, 5]):", list_reversed) print("list_reversed([1, 2, 3, 4, 5])):", list(list_reversed)) print() print("# reversed() 함수와 반복문") print("for i in reversed")
false
2ed3de8d74a1df5c2a32776675614f670af9b7bc
eraldomuha/software_development_projects
/rock_paper_scissors.py
2,995
4.21875
4
#!/usr/bin/env python3 from random import choice """This program plays a game of Rock, Paper, Scissors between two Players, and reports both Player's scores each round.""" moves = ['rock', 'paper', 'scissors'] """The Player class is the parent class for all of the Players in this game""" class Player: def move(self): return "rock" def learn(self, last_move): pass class HumanPlayer(Player): def move(self): myChoice = input("choose a move (paper, scissors, rock): ").lower() while myChoice not in moves: print("Not a valid move!") return self.move() return myChoice class RandomPlayer(Player): def move(self): return choice(moves) class ReflectPlayer(Player): def __init__(self): Player.__init__(self) self.last_move = None def learn(self, last_move): self.last_move = last_move def move(self): if (self.last_move is None): return Player.move(self) return self.last_move class CyclePlayer(Player): def __init__(self): Player.__init__(self) self.last_move = None def move(self): if (self.last_move is None): move = Player.move(self) else: index = moves.index(self.last_move) + 1 if index >= len(moves): index = 0 move = moves[index] self.last_move = move return move def beats(one, two): return ((one == 'rock' and two == 'scissors') or (one == 'scissors' and two == 'paper') or (one == 'paper' and two == 'rock')) class Game: def __init__(self, p1, p2): self.p1 = p1 self.p2 = p2 self.score1 = 0 self.score2 = 0 def play_round(self): move1 = self.p1.move() move2 = self.p2.move() if (beats(move1, move2) is True): print("PLAYER WINS :)") self.score1 += 1 elif (move1 == move2): print("It's a DRAW") pass else: print("COMPUTER WINS") self.score2 += 1 print(f"Player Move: {move1}, Computer Move: {move2}") print(f"Player Score: {self.score1}, Computer Score: {self.score2}") self.p1.learn(move1) self.p2.learn(move1) def play_game(self): print("Game start!") for round in range(3): print(f"Round {round+1}:") self.play_round() if (self.score1 > self.score2): print("PLAYER is the WINNER :)") elif (self.score1 == self.score2): print("No one is the Winner") else: print("COMPUTER is the WINNER") print("Game over!") if __name__ == '__main__': Player1 = HumanPlayer() Player2 = ReflectPlayer() game = Game(Player1, Player2) game.play_game()
true
2a53202790f416952f3e0eeaf46eeffda1b2440f
lachilles/oo-melons
/melons2.py
2,009
4.25
4
"""This file should have our order classes in it.""" class AbstractMelonOrder(object): """Default melon order """ def __init__(self, species, qty): self.species = species self.qty = qty self.shipped = False self.flat_rate = 0 def get_total(self): """Calculate price.""" if self.species == "Christmas": base_price = (5 * 1.5) else: base_price = 5 total = (1 + self.tax) * self.qty * base_price if self.order_type == "international" and self.qty < 10: total += 3 return total def mark_shipped(self): """Set shipped to true.""" self.shipped = True class DomesticMelonOrder(AbstractMelonOrder): """A domestic (in the US) melon order.""" order_type = "domestic" tax = 0.08 #order_type and tax are the class attributes class InternationalMelonOrder(AbstractMelonOrder): #InternationalMelonOrder subclasses AbstractMelonOrder """An international (non-US) melon order.""" def __init__(self, species, qty, country_code): #Defined the initialization method with attributes species, qty, country_code super(InternationalMelonOrder, self).__init__(species, qty) #Calling the initialization method of the super self.country_code = country_code #country_code is the instance attribute order_type = "international" tax = 0.17 #order_type and tax are the class attributes def get_country_code(self): """Return the country code.""" return self.country_code class GovernmentMelonOrder(AbstractMelonOrder): def __init__(self, species, qty, passed_inspection): super(GovernmentMelonOrder, self).__init__(species, qty) self.passed_inspection = False order_type = "government" tax = 0 def mark_inspections(self, passed): self.passed_inspection = passed
true
56fe479ffd914e40a60ecdd381d7dbfe37163c32
Tonyynot14/Textbook
/chapter5.10.py
339
4.15625
4
students = int(input("How many students do you have?")) highest = 0 secondhighest = 0 for i in range(students): score = int(input("What are the scores for the test?")) if score > highest: secondhighest=highest highest = score print("The highest test score was", highest, "\nThe second highest was",secondhighest )
true
7eb418fe5e33623b74ee446a4d515e32afa5c82c
Tonyynot14/Textbook
/nsidepolygonclass.py
1,229
4.1875
4
#Tony Wade # Class for regular polygons # Class that defines a polygon based on n(number of sides), side(length of side) # x(x coordinate) y(y coordinate) import math class RegularPolygon: # initalizer and default constructor of regular polygon def __init__(self, n=3, side = 1, x = 0, y = 0 ): self.__n= n self.__side = side self.__x = x self.__y = y # accessor function followed by mutator function of each piece of data def getN(self): return self.__n def setN(self,n): self.__n = n def getSide(self): return self.__side def setSide(self, side): self.__side = side def getX(self): return self.__x def setX(self, x): self.__x = x def getY(self): return self.__Y def setY(self, y): self.__y = y # Function for finding perimeter of regular sided polygon def getPerimeter(self): perimeter = self.__side*self.__n return perimeter # Function for finding the area of a regular sided polygon. Need math module for pi and tan functions. def getArea(self): area = (self.__n*(self.__side**2))/(4*math.tan(math.pi/self.__n)) return area
true
c5634614d01183874ccc6c7e0a0f651e9cd345ca
coldmanck/leetcode-python
/0426_Convert_Binary_Search_Tree_to_Sorted_Doubly_Linked_List.py
1,445
4.28125
4
# Runtime: 36 ms, faster than 55.87% of Python3 online submissions for Convert Binary Search Tree to Sorted Doubly Linked List. # Memory Usage: 14.8 MB, less than 100.00% of Python3 online submissions for Convert Binary Search Tree to Sorted Doubly Linked List. # Definition for a Node. class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right class Solution: '''Time O(n) Space O(h)''' def treeToDoublyList(self, root: 'Node') -> 'Node': def tree_to_doubly_list(root): if not root: return None, None left_tail, left_head = tree_to_doubly_list(root.left) # left_tail is used to connect with lower elements if left_tail: left_tail.right = root root.left = left_tail right_tail, right_head = tree_to_doubly_list(root.right) # right_head is used to connect with upper elements if right_head: right_head.left = root root.right = right_head # left_head and right_tail are kept as the final head and tail return (right_tail or root, left_head or root) if not root: return None tail, head = tree_to_doubly_list(root) tail.right = head head.left = tail return head
true
e0453bfe71a01326909b1105ad8333463af4d7a4
coldmanck/leetcode-python
/0077_Combinations.py
1,190
4.15625
4
class Solution: '''Backtrack. Time: O(k*C^n_k) Space (C^n_k)''' def combine(self, n: int, k: int) -> List[List[int]]: def backtrack(i, cur_arr, ans, arr): if len(cur_arr) == k: ans.append(cur_arr) return for j in range(i, n): backtrack(j + 1, cur_arr + [arr[j]], ans, arr) ans = [] arr = [i for i in range(1, n + 1)] backtrack(0, [], ans, arr) return ans ''' Algorithm Backtracking is an algorithm for finding all solutions by exploring all potential candidates. If the solution candidate turns to be not a solution (or at least not the last one), backtracking algorithm discards it by making some changes on the previous step, i.e. backtracks and then try again. Here is a backtrack function which takes a first integer to add and a current combination as arguments backtrack(first, curr). If the current combination is done - add it to output. Iterate over the integers from first to n. Add integer i into the current combination curr. Proceed to add more integers into the combination : backtrack(i + 1, curr). Backtrack by removing i from curr. '''
true
4bdb539d304920611d832ccf249baa155666b01b
JelenaKiblik/School-python
/kt1/exam.py
1,672
4.125
4
"""Kontrolltoo.""" def capitalize_string(s: str) -> str: """ Return capitalized string. The first char is capitalized, the rest remain as they are. capitalize_string("abc") => "Abc" capitalize_string("ABc") => "ABc" capitalize_string("") => "" """ if len(s) >= 1: return s[0].upper() + s[1:] else: return "" def sum_half_evens(nums: list) -> int: """ Return the sum of first half of even ints in the given array. If there are odd number of even numbers, then include the middle number. sum_half_evens([2, 1, 2, 3, 4]) => 4 sum_half_evens([2, 2, 0, 4]) => 4 sum_half_evens([1, 3, 5, 8]) => 8 sum_half_evens([2, 3, 5, 7, 8, 9, 10, 11]) => 10 """ new_list = [] list = [] for i in nums: if i % 2 == 0: new_list.append(i) if len(new_list) % 2 == 0: a = len(new_list) // 2 for i in range(a): list.append(new_list[i]) else: a = len(new_list) // 2 for i in range(a + 1): list.append(new_list[i]) return sum(list) def max_block(s: str) -> int: """ Given a string, return the length of the largest "block" in the string. A block is a run of adjacent chars that are the same. max_block("hoopla") => 2 max_block("abbCCCddBBBxx") => 3 max_block("") => 0 """ count = 1 string = s.lower() if len(string) == 0: return 0 else: for i in range(0, len(string) - 1): if string[i] == string[i + 1]: count += 1 return count print(max_block("hoopla")) print(max_block("")) print(max_block("abbCCCddBBBxx"))
true
6c0e0a844f7b4a863884ece04c4560c09167bb17
lkrauss15/Old-School-Stuff
/CarCalc.py
660
4.1875
4
# Programmer: Luke Krauss # Date: 9/15/14 # File: Wordproblems.py # This program allows a user to input specific numbers for a word problem. In this case, the user is saing up to purchase a car. def main(): print ("So you're saving up to buy a car?") carCost = input("How much is the car? ") currentCash = input("How much money do you have now? ") jobWage = input("How much money do you make per hour? ") hours = (carCost - currentCash)/jobWage days = (hours/24.0) weeks = (days/7.0) print ("You will need to work " + str(hours) + " hours,"+ str(days) + " days, or " + str(weeks) + " weeks in order to afford this car.") main()
true
5a95e84b87d787067f4acd7eb422549a772e1bf0
goodseeyou/python_small_function
/src/listTool/listTool.py
2,235
4.125
4
''' Select kth value number from list in order of (n) time complexity. However, comparing to sorted list and select kth value (order of nlogn), sorting by build-in function is faster. ''' import sys NUMBER_OF_ELEMENT_IN_COLUMN = 7 def select_the_kth_small_element(_list, k): len_list = len(_list) if k > len_list: raise ValueError("parameter k %s have greater then size of list %s", k, len_list) if len_list <= NUMBER_OF_ELEMENT_IN_COLUMN: return sorted(_list)[k-1] l = _list[:] number_of_padding = len(l) % NUMBER_OF_ELEMENT_IN_COLUMN l += [sys.maxint] * number_of_padding median_list = [] for i in [ii*NUMBER_OF_ELEMENT_IN_COLUMN for ii in range(len(l)/NUMBER_OF_ELEMENT_IN_COLUMN)]: column = l[i:i+NUMBER_OF_ELEMENT_IN_COLUMN] column.sort() i += NUMBER_OF_ELEMENT_IN_COLUMN median = column[NUMBER_OF_ELEMENT_IN_COLUMN / 2] median_list.append(median) median_of_median = select_the_kth_small_element(median_list, len(median_list) / 2) smaller, equal, bigger = [], [], [] for element in l: if element < median_of_median: smaller.append(element) elif element == median_of_median: equal.append(element) elif element > median_of_median: bigger.append(element) else: raise ValueError("Impossible %s ? %s", element, median_of_median) len_smaller, len_equal, len_bigger = len(smaller), len(equal), len(bigger) if k <= len_smaller: return select_the_kth_small_element(smaller, k) elif k <= len_smaller + len_equal: return select_the_kth_small_element(equal, k - len_smaller) else: return select_the_kth_small_element(bigger, k - len_smaller - len_equal) if __name__ == '__main__': import json import time import random k = int(sys.argv[1]) l = [random.randint(0,100000) for i in range(int(sys.argv[2]))][::-1] ''' l = json.loads(sys.argv[2]) print l #''' b = time.time() print select_the_kth_small_element(l, k) e = time.time() print '%.3lf' % (e - b) b = time.time() l.sort() print l[k-1] e = time.time() print '%.3lf' % (e - b)
false
3d9b540022732b42d3cb58317f9ac9c0fd2193cb
lcarbonaro/python
/session20161129/guess.v1.py
336
4.15625
4
from random import randint rand = randint(1,20) print('I have picked a random integer between 1 and 20.') guess = input('Enter your guess: ') if guess<rand: print('That is too low.') if guess>rand: print('That is too high.') if guess==rand: print('That is correct.') print('The random integer was: ' + str(rand))
true
71f1ded188070d203f547339a60416e50744e880
allen-studio/learn-python3-records
/ex34.py
951
4.4375
4
animals = ['bear', 'python3.6', 'peacock', 'kangaroo', 'whale', 'platypus'] print(animals[0]) #列表第一个元素位置是[0] print(animals[-1]) #列表第一个元素位置是[-1] print(animals[-2]) # 倒数第二个元素就是[-2] print(animals[5]) # 当然也可以从[0]开始数到第六个[5] print(animals[0:]) # 获取列表中从 [0] 到结尾的元素 print(animals[:-1]) # 获取列表中从开头 到 [-1]的元素 print(animals[:]) # 获取整个列表的元素 for animal in animals: # 通过for····in····· 遍历列表 print(animal) # 打印遍历出来的每一个元素 test = "python is a new programming language with computer, it's written by guido, it's a very simple programming language, i always use it to craiming some infomation in internet."# 这句子乱写的 print(test.split(' ')) # 通过split把句子分词拆成一个列表 print(len(test.split(' '))) # 通过len统计列表里有多少个元素
false
5f241775792987d41cda409b63a38a36cf5981b7
KevinMFinch/Python-Samples
/productCommercial.py
591
4.125
4
print("Hello! I am going to ask you questions about your device to create a commercial.") yourObject = input("What is your object? ") yourData = input("What data does it take? ") how = input("How will you record the "+yourData+" from your "+yourObject+"?") where = input("Where will the "+how+" be located? ") cost = input("How expensive will your "+yourObject+" be in dollars? ") print("Coming soon! For the low price of "+cost+" dollars, ",end="") print("this new "+yourObject+" will easily record "+yourData+". It is easy to control from "+how+" located ",end="") print("on "+where+".")
true
1782393b95763d826526de9d77d77df2ae89d038
brunoleonpuca/PYTHON
/learning-python/CONTROL DE FLUJOS.py
561
4.15625
4
"""CONTROL DE FLUJO""" """IF""" #IF condicion: # true #IF condicion1 and condicion2: # ambas devuelven true (si hay una falsa, no se va a mostrar) #IF condicion1 or condicion2: # una de ambas devuelve true """"IF - OPERADOR TERNARIO""" #print("cuando devuelve true") if 5 > 2 else print:("cuando devuelve false") #ELIF(condicion): (si condicion es true) -> solo ingresa un elif por ciclo #ELSE: (si condicion es false) #WHILE(condicion) #break -> finaliza el ciclo por completo #continue -> finaliza el ciclo y vuelve al principio del mismo #FOR LOOP
false
a69bfc55246f403b8b5711818e6591e150739c09
jaysonmassey/CMIS102
/Assignment_2_CMIS_102_Jayson_Massey.py
2,585
4.53125
5
# Assignment 2 CMIS 102 Jayson Massey # The second assignment involves writing a Python program to compute the price of a theater ticket. # Your program should prompt the user for the patron's age and whether the movie is 3D. # Children and seniors should receive a discounted price. x # There should be a surcharge for movies that are 3D. x # You should decide on the age cutoffs for children and seniors and the prices for the three different age groups. x # You should also decide on the amount of the surcharge for 3D movies. # Your program should output the ticket price for the movie ticket based on the age entered # and whether the movie is in 3D. # Your program should include the pseudocode used for your design in the comments. # Document the values you chose for the age cutoffs for children and seniors, # the prices for the three different age groups and the surcharge for 3D movies in your comments as well. # Predefined variables child_age = 12 # upper age limit senior_age = 60 # lower age limit child_discount = 5 senior_discount = 3 ticket_price = 15 # for ages 13 - 59 three_d_surcharge = 5 # Get user input - "should prompt the user for the patron's age and whether the movie is 3D" print("Welcome to Movie Calculator! If you give me a little info, I'll tell you the price for your movie.") patron_name = input("What is your name?") print(patron_name, "what is your age?") patron_age = eval(input()) print("Thanks", patron_name, "you're", patron_age, ". Is the movie you want to see in 3D? Yes or No?") is_three_d = input() # added logic to ensure that the user says yes or no to the 3D question if is_three_d.lower() == "yes": #used lower() here to allow answers like YES and Yes print("Your movie is in 3D") ticket_price = ticket_price + three_d_surcharge # adds 3D surcharge elif is_three_d.lower() == "no": print("Your movie is not in 3D") else: print("I missed that", patron_name, ". Is the movie you want to see in 3D? Yes or No?") is_three_d = input() # logic for age-based discounts if patron_age <= child_age: ticket_price = ticket_price - child_discount print("Child price") elif patron_age >= senior_age: ticket_price = ticket_price - senior_discount print("Senior price") else: print("Calculations done!") # "output the ticket price for the movie ticket based on the age entered and whether the movie is in 3D." print(patron_name, "I've calculated your movie price, and it's $",ticket_price,". Thanks for using Movie Calculator!")
true
9fa7ba142e1959040911fd07092dabf96e018ecf
gasgit-cs/pforcs-problem-sheet
/es.py
2,040
4.3125
4
# program to read in a file and count ocurrence of a char # author glen gardiner # run program calling es.py and passing the name of a file to read # example: python es.py Lorem-ipsum.txt # for this task its es.py md.txt import sys # fn - filename # i - input from user # uc - uppercase i # lc - lowercase i fn = sys.argv[1] # get letter from user i = input("Enter the letter you require counted: ") # convert input to upper and lower uc = i.upper() lc = i.lower() # f - file # t - text # l - line # c - charachter def read_file(fn, lc, uc): # count all non space char count_all = 0 # count lower count_lower = 0 # count upper count_upper = 0 try: # open file in read mode with open(fn, "r") as f: # iterate for each line in f for line in f: # iterate for each char in each line for c in line: # check if c is a space if not c.isspace(): # if not increment count_all counter count_all +=1 # check if c is lowercase if c == lc: # increment count_lower count_lower += 1 # check if c is uppercase elif c == uc: # increment count_upper count_upper +=1 count_total = count_lower + count_upper # display count result print("Total Chars count: {} \t Total Lower input: {} \t Total Upper input: {} \t Total input: {}".format(count_all,count_lower, count_upper, count_total)) # close the file #f.close() # catch teh exception and display my message and built in python message (e) except Exception as e: # my message print("File not found, check name and path:(") # python exception message print(e) read_file(fn, lc, uc)
true
c180f15dab31da69c0dc146ff04827f7d36289dc
leandroradusky/embnet-argentina
/embnet/Upload/module1.py
872
4.25
4
# REPASO # Defino la funcion x que devuelve el entero 3 x = 3 # Defino una funcion "inline" pordos = lambda y: y*2 # Defino una funcion comun def portres(y): return y*3 # Aplicar tenia la caracteristica de recibir # funciones como parametros, aca todo es una funcion!! aplicar = lambda y,z: y(z) aplicarr = lambda y,z,w: y(z(w)) # imprimo #print (aplicar(pordos,x)) #print (aplicarr(pordos,portres,x)) # LISTAS POR COMPRENSION # Lista comun l1 = [1,2,3] print l1 # Lista un poco más inteligente # range me devuelve del 0 al 29 # hago for para todos los e en ese rango l2 = [e for e in range(30)] print l2 # Puedo anidar incluso l3 = [[e,i] for e in range(10) for i in range(10)] print l3 # MAP # aplico res = map(portres, l2) print res # no es lo mismo que multiplicar la lista resdos = portres(l2) print resdos
false
3a676e0797232de364f8e1db7b5bdf858c8035a5
MandragoraQA/Python
/DZ_13.py
1,847
4.15625
4
#Пользователь вводит с клавиатуры строку, слово для поиска, слово для замены. Произведите в строке замену одного слова на другое. stroka = input("Введите строку: ") slovo = input("Введите слово для поиска: ") zamena = input("Введите слово для замены: ") #ищем слово и заменяем его сразу в цикле for a in range (len(stroka) - len(slovo)+1): if slovo == stroka[a:a + len(slovo)]: stroka = stroka.replace(slovo,zamena) print(stroka) #Пользователь вводит с клавиатуры арифметическое выражение. Необходимо вывести на экран результат выражения. stroka = input("Введите арифмитическое выражение, состоящее из число,оператор,число: ") #если сложение if "+" in stroka: chislo1=int(stroka[:stroka.index("+")]) chislo2=int(stroka[stroka.index("+")+1:]) print("Значение выражения: ",chislo1+chislo2) #если вычитание elif "-" in stroka: chislo1=int(stroka[:stroka.index("-")]) chislo2=int(stroka[stroka.index("-")+1:]) print("Значение выражения: ",chislo1-chislo2) #если умножение elif "*" in stroka: chislo1=int(stroka[:stroka.index("*")]) chislo2=int(stroka[stroka.index("*")+1:]) print("Значение выражения: ",chislo1*chislo2) #если деление elif "/" in stroka: chislo1=int(stroka[:stroka.index("/")]) chislo2=int(stroka[stroka.index("/")+1:]) print("Значение выражения: ",int(chislo1/chislo2))
false
df03082be153b1535a15ba6a35f9fbfd8c6480e5
robertggovias/robertgovia.github.io
/python/cs241/w04/assignment04/customer.py
2,220
4.1875
4
from order import Order from product import Product class Customer: '''id=0 price quantity''' def __init__(self): ''' Construction of an empty object to receive the id from the customer, and his name. Then will receive the list of orders ''' self.id = "" self.name= "" #this empty list will receive all new order self.orders = [] def add_order(self,add_new): ''' Each time a new object of th class order is created will be appended on this line. ''' self.orders.append(add_new) def get_total(self): ''' The last code create a list, but we need to iterate on each element to get from each one de return of the funciton get_total from the class order. ''' sum_of_orders = 0 for final_totals in self.orders: sum_of_orders += final_totals.get_total() return sum_of_orders def get_order_count(self): ''' as easy as qwe have a list, to know the quantity of member of taat list we will use -len - which will evaluate how long is the list ''' amount = len(self.orders) return amount def print_orders(self): ''' To print each order, we iterate on each element and print each one with its display code. ''' for order in self.orders: if self.get_order_count() > 1: print() order.display_receipt() def display_summary(self): ''' Print each customer, and its orders (with products) ''' print("Summary for customer '{}':\nName: {}".format(self.id,self.name)) print("Orders:",self.get_order_count()) print("Total: ${:.2f}".format(self.get_total())) def display_receipts(self): ''' getting advance from all the other display functions, this one will print in detail all the details of the sale ''' print("Detailed receipts for customer '{}':\nName: {}".format(self.id,self.name)) if self.get_order_count() < 2: print() self.print_orders()
true
b403438ea29fd5b24d4379fec9d6fc503c686ebc
robertggovias/robertgovia.github.io
/python/cs241/w07/fibonnacy.py
459
4.125
4
def fib(n): fib_list = [0,1,1] if n < 0: return if n >= 0 and n < 3: return fib_list[n] for i in range (3, n+1): g = fib_list[i - 1] + fib_list[i - 2] fib_list.append(g) return fib_list[n] def main(): f = int(input("Enter a Fibonacci index:")) print("The Fibonacci number is: {}".format(fib(f))) if __name__ == "__main__": main()
false
b0972ddcba708ccaf388c5f53d596f2bccebfb99
NishantGhanate/PythonScripts
/Scripts/alien.py
927
4.21875
4
# -*- coding: utf-8 -*- """ Created on Fri Jan 11 13:39:32 2019 @author: Nishant Ghanate """ # your code goes here import pandas as pd #Take User input for alphabetical order and string #a= input('Enter the order of alphabet : \n') #b= input('Enter the string you want to sort according to the Alphabet provided : \n') a = "abcdefghijklmnopqrstuvwxyz" b = "cyxbza" df = [] #Combining both list to a new list for i,j in zip(list(a),list(a.upper())): df.append(j) df.append(i) #print(df) a=df #Converting list to the dataframe alphabet = pd.DataFrame(index=range(0,len(a)),columns=['letter']) spell = pd.DataFrame(index=range(0,len(b)),columns=['letter']) alphabet['letter'] = list(a) spell['letter'] = list(b) #Sorting of String according to alphabet as per condition provided alphabet=pd.merge(alphabet,spell,how='inner') ##Printing the final result #output = ''.join(alphabet['letter'].values.tolist()) #print(output)
true
d8de5b3a6c0ba9c21d6f8287fe338f588175efa5
NishantGhanate/PythonScripts
/ObjectOriented/Sorting/MergeSort.py
2,569
4.28125
4
class MergeSort: def __init__(self,array): self.merge_sort(array) def merge_sort(self,array): print("\nGiven List = {} ".format(array)) if len(array)>1: mid = len(array)//2 print("Mid index = {} ".format(mid)) # From 0 till mid index left_half = array[:mid] print("Left half = {} ".format(left_half)) # From mid till end index right_half = array[mid:] print("Right half = {} ".format(right_half)) self.merge_sort(left_half) self.merge_sort(right_half) i = 0 j = 0 k = 0 while i < len(left_half) and j < len (right_half): if left_half[i] < right_half[j]: array[k] = left_half[i] i = i + 1 else: array[k] = right_half[j] j = j + 1 k = k +1 while i < len (left_half): array[k] = left_half[i] i = i + 1 k = k + 1 while j < len (right_half): array[k] = right_half[j] j = j +1 k = k + 1 print("Merging ",array) if __name__ =="__main__": array = [9,5,4,8,6,7,3,1,2] MergeSort(array) # Given List = [9, 5, 4, 8, 6, 7, 3, 1, 2] # Mid index = 4 # Left half = [9, 5, 4, 8] # Right half = [6, 7, 3, 1, 2] # Given List = [9, 5, 4, 8] # Mid index = 2 # Left half = [9, 5] # Right half = [4, 8] # Given List = [9, 5] # Mid index = 1 # Left half = [9] # Right half = [5] # Given List = [9] # Merging [9] # Given List = [5] # Merging [5] # Merging [5, 9] # Given List = [4, 8] # Mid index = 1 # Left half = [4] # Right half = [8] # Given List = [4] # Merging [4] # Given List = [8] # Merging [8] # Merging [4, 8] # Merging [4, 5, 8, 9] # Given List = [6, 7, 3, 1, 2] # Mid index = 2 # Left half = [6, 7] # Right half = [3, 1, 2] # Given List = [6, 7] # Mid index = 1 # Left half = [6] # Right half = [7] # Given List = [6] # Merging [6] # Given List = [7] # Merging [7] # Merging [6, 7] # Given List = [3, 1, 2] # Mid index = 1 # Left half = [3] # Right half = [1, 2] # Given List = [3] # Merging [3] # Given List = [1, 2] # Mid index = 1 # Left half = [1] # Right half = [2] # Given List = [1] # Merging [1] # Given List = [2] # Merging [2] # Merging [1, 2] # Merging [1, 2, 3] # Merging [1, 2, 3, 6, 7] # Merging [1, 2, 3, 4, 5, 6, 7, 8, 9]
false
bd446e6a1cd0e8bcb5fe6745d2ebe9b78c40639e
pavanpandya/Python
/Python Basic/27_Sets.py
589
4.5
4
# Set-Unordered Collection of unique objects my_set = {1, 2, 3, 4, 5, 6} print(my_set) # Now let say we have an another set name my_set2 my_set2 = {1, 2, 3, 4, 5, 5} print(my_set2) # Here this will only print the unique objects. my_set.add(100) my_set.add(2) # Here 2 is not added in the set because it is already present in the set. print(my_set) # print(my_set[0]) #This will throw an error as we can't access the elements like this. print(len(my_set)) print(2 in my_set) # Trick my_list = [1, 2, 3, 4, 5, 6, 5] print(set(my_list)) new = my_set2.copy() print(new) print(list(new))
true
0a64d5d93b55aca7e3b854c9cd246ba3269010f7
pavanpandya/Python
/OOP by Telusko/13_Operator_Overloading.py
2,145
4.15625
4
# eg: 5 + 6 # Here 5 and 6 are operands and + is operator. a = 5 b = 6 print(a+b) # When you say a + b behind the scene int.__add__(a, b) is called. print(int.__add__(a, b)) c = '5' d = '6' print(c+d) # When you say c + d behind the scene str.__add__(c, d) is called. print(str.__add__(c, d)) # The moment you say a - b then .__sub__(a, b) is called # The moment you say a * b then .__mul__(a, b) is called # The moment you say a / b then .__div__(a, b) is called # The moment you say a > b then .__gt__(a, b) is called # The moment you say a < b then .__lt__(a, b) is called # The moment you say a >= b then .__ge__(a, b) is called # The moment you say a <= b then .__le__(a, b) is called # These Methods are called as Magic Methods. class Student: def __init__(self, m1, m2): self.m1 = m1 self.m2 = m2 def __add__(self, other): # Adding m1 of student 1 and student 2 m1 = self.m1 + other.m1 # Adding m2 of student 1 and student 2 m2 = self.m2 + other.m2 s3 = Student(m1, m2) return s3 def __gt__(self, other): r1 = self.m1 + self.m2 r2 = other.m1 + other.m2 # Here r1 and r2 are not objects they are simple integer variables. if(r1 > r2): return True def __str__(self): # return self.m1, self.m2 # The above line will generate an error: # TypeError: __str__ returned non-string (type tuple) # So we have convert it into string. return '{} {}'.format(self.m1, self.m2) s1 = Student(58, 69) s2 = Student(68, 79) # This will throw an error because we have not defined add method. # print(s1 + s2) # This 's1 + s2' gets converted into 'Student.__add__(s1, s2)'. s3 = s1 + s2 print(s3.m1) print(s3.m2) if s1 > s2: print("S1 Wins") else: print("S2 Wins") f = 5 print(f) # when we type print(f), behind the scene print(f.__str__()) is called. # when we type print(s3), behind the scene print(s3.__str__()) is called. # But here it will print the address of s3. # As we want values we have to overwrite this method. print(s3) # Now it will print the values.
false
adff70a67790e99f15a4effcddf6d69269395bf9
pavanpandya/Python
/Python Basic/38_Range().py
965
4.46875
4
# Range - It returns an object that produces a sequence of integers from start(inclusive) to stop(exclusive) by step. # Syntax: # range(stop) # range(start, stop[, step]) print(range(100)) # will give output: # range(0, 100) print(range(0, 100)) # will give output: # range(0, 100) for number in range(0, 100): print(number) # Will print the no. starting from 0 till 99 for _ in range(0, 10): print(_) # If you want don't need the variable then you can use underscore(_). # It indicates that hey i dont really care what's the variable name, I am just using range to get my desired output. for _ in range(0, 10, 2): print(_) # Will print the no. starting from 0 till 9 and will step over the number by 2 (Be Default it is 1) for _ in range(0, 10, -1): print(_) # Will not print anything for _ in range(10, 0, -1): print(_) # Will print it in reverse order i.e 10 to 1 for _ in range(2): print(list(range(10)))
true
4bf1675599ba2c0097469ead8eccccc889334057
pavanpandya/Python
/Other Python Section/06_Error_Handling.py
718
4.21875
4
# Error Handling: while True: try: age = int(input('What is your age: ')) print(age) except: print('Please enter a number') # The above code means try the code and if there is any error run except. else: print('Thank You') break # If there is any error then instead of some pre_written error, msg(print in above case) written in except will get printed. # If there are multiple diff error: while True: try: age = int(input('What is your age: ')) print(age) except ValueError: print('Please Enter a number') except ZeroDivisionError: print("You can't Enter Zero") else: print('Thank You') break
true
59ca9c162a99aabaa5affebfe41f32241e655379
pavanpandya/Python
/Python Basic/11_Formatted_Strings.py
768
4.34375
4
# Formatted Strings name = 'Pavan' age = 19 # print('Hi' + name + '. You are ' + age + ' year old.') --> This will throw an error as age is int # and string Concatenation only works with strings print('Hi ' + name + '. You are ' + str(age) + ' year old.') # Better Way of doing This print(f'Hi {name}. You are {age} year old.') # Formatted Strings # print('Hi {}. You are {} year old.').format('Pavan', '19') --> This will throw an error as it # will run for print and not for the elements in print. print('Hi {}. You are {} year old.'.format('Pavan', '19')) # This also works the same as above print('Hi {}. You are {} year old.'.format(name, age)) # printing other variable print('Hi {new_name}. You are {age} year old.'.format( new_name='John', age='20'))
true
be072451108e2ad01b0c6f2638d13f3352104d16
pavanpandya/Python
/OOP by Telusko/10_Constructor_in_Inheritance.py
1,292
4.59375
5
# SUB CLASS CAN ACCESS ALL THE FEATURES OF SUPER CLASS # BUT # SUPER CLASS CANNOT ACCESS ANY FEATURES OF SUB CLASS ''' IMPORTANT RULE: When you create object of sub class it will call init of sub class first. If you have call super then it will first call init of super class and then call the init of sub class. ''' # Rules : If you create object of sub class it will first try to find init of sub class, # if it is not found then it will call init of super class. class A: def __init__(self): print('INIt in A') def feature1(self): print("Feature-1 is Working") def feature2(self): print("Feature-2 is Working") class B(A): def __init__(self): # If you also want to call the init method of class A then use 'super' keyword or you can say method. # By writing super we are representing super class A. super().__init__() print('INIt in B') def feature3(self): print("Feature-3 is Working") def feature4(self): print("Feature-4 is Working") a1 = A() # Here though it is the object of Class B, it is will call init method(Constructor of Class A) # Because Class B was not having it's own init method. But after adding the init method, it will call it's own init method. a2 = B()
true
266c658edeabb5217f3cd1b8cf61a2ad2de4fea2
pavanpandya/Python
/Python Basic/07_Augmented_Assignment_Operator.py
471
4.71875
5
# Augmented Assignment Operator Some_value = 5 # Some_value = Some_value + 5 # instead of doing this we will use Augmented Assignment Operator, Some_value += 5 # --> which is equal to Some_value = Some_value + 5 # NOTE : In order to work this "Some_value += 5", the variable "Some_value" should be defined before or in other words, # It should have some value defined to it. print(Some_value) # We can also do # Some_value -= 5 # Some_value *= 5 # Some_value /= 5
true
3f1dce9f42dbd335fa08610df5732a308fb7f744
pavanpandya/Python
/Python Basic/56_Exercise_Functions.py
332
4.125
4
def Highest_Even_Number(li): evens = [] for item in li: if(item % 2 == 0): evens.append(item) max = 0 for i in evens: if(i > max): max = i return max # By using Max Function. # return max(evens) my_List = [10, 2, 3, 4, 8, 11] print(Highest_Even_Number(my_List))
true
14039762193d12d2ab24057aa383a327bc254eb5
pavanpandya/Python
/Other Python Section/08_Exercise_error_handling.py
551
4.15625
4
while True: try: age = int(input('What is your age: ')) print(age) except ValueError: print('Please Enter a number') except ZeroDivisionError: print("You can't Enter Zero") else: print('Thank You') break finally: print("Okay, I'am Finally Done") print("Can you hear me?") # Finally runs regardless at the end of everything. # Though we use break to get out of the loop, Finally will still get executed. # Print statement will not get executed as we have break the loop.
true
61021fe5756f17e209dd666326304557af17b1d2
pavanpandya/Python
/Python Basic/33_Logical_Operators.py
470
4.1875
4
# Logical Operators: # >, <, >=, <=, ==, != # and, or, not print(4 > 5) print(4 >= 5) print(4 < 5) print(4 <= 5) print(4 == 5) print(4 != 5) print('a' > 'b') print('a' > 'A') print(1 < 2 < 3 < 4) print(not(True)) # Exercise is_magician = False is_expert = True if is_magician and is_expert: print("You are a master magician") elif is_magician and not is_expert: print("You are an Average magician") elif not is_magician: print("You are not magician")
false
ff82750488e0dd6ee02cdda39ebad5fc36df5fe4
cameron-teed/ICS3U-5-04-PY
/cyliinder.py
922
4.3125
4
#!/usr/bin/env python3 # Created by: Cameron Teed # Created on: Nov 2019 # This program calculates volume of a cylinder import math def volume_calculator(radius, height): # calculates the volume # process volume = math.pi * radius * radius * height return round(volume, 2) def main(): # This is asks for the user input # Welcomes user print("This program calculates the volume of a cylinder. ") while True: try: # input radius = float(input("What is the radius: ")) height = float(input("What is the height: ")) # runs volume_calculator() volume = volume_calculator(height=height, radius=radius) # output print("\nThe volume is " + str(volume) + " units cubed.") break except ValueError: print("Please put in integer.\n") if __name__ == "__main__": main()
true
0fd7593dc7b0faafc04fa0664278eb7ed1859e80
Zgonz19/Towers-of-Hanoi
/TowersofHanoi.py
2,875
4.125
4
# COSC 3320, Towers of Hanoi, Assignment 1 # Gonzalo Zepeda, ID: 1561524 # when called, printMove function prints the current move as long as the parameters # entered correspond to the solution. # notable parameters: which disk is moving, disk location, disk destination, number of moves so far def printMove(disk, source, dest, currentStep): print("Move number " + str(currentStep) + ": Move disk " + str(disk) + " from " + str(source) + " to " + str(dest)) # the hanoi function is the main recursive function of the program # notable parameters: how many disks there are, the 5 pegs, the current move # once called, this function will call itself until all disks are in the destination peg def hanoi(numOfDisks, Start, source, dest, aux, last, current,r): numOfDisks = int(numOfDisks) if numOfDisks == 1: printMove(numOfDisks, source, aux, current) current+=1 printMove(numOfDisks, aux, dest, current) current+=1 elif numOfDisks == 2: printMove(numOfDisks-1, source, aux, current) current+=1 printMove(numOfDisks-1, aux, dest, current) current+=1 if current == 4: printMove(numOfDisks, Start, source, current) current+=1 printMove(numOfDisks, source, aux, current) current+=1 printMove(numOfDisks-1, dest, aux, current) current+=1 printMove(numOfDisks-1, aux, source, current) current+=1 printMove(numOfDisks, aux, dest, current) current+=1 if r == 2: printMove(2, dest, last, current) current+=1; printMove(numOfDisks-1, source, aux, current) current+=1 printMove(numOfDisks-1, aux, dest, current) current+=1; elif numOfDisks > 2: current = hanoi(numOfDisks-1, Start, source, dest, aux, last, current, r) if(hasItMoved[numOfDisks]!=1): printMove(numOfDisks, Start, source, current) current+=1 hasItMoved[numOfDisks]=1 printMove(numOfDisks, source, aux, current) current+=1 current = hanoi(numOfDisks-1,Start, dest, source, aux,last, current, r) printMove(numOfDisks, aux, dest, current) current+=1 if(toDest[numOfDisks+1]!=0): printMove(numOfDisks, dest, last, current) current+=1 toDest[numOfDisks]=1 if(numOfDisks == r): r-=1 current = hanoi(numOfDisks-1, Start,source, dest, aux,last, current, r) return current; # the hanoiInit function is only called once to initiate our program. # within hanoiInit is the first call to our recursive hanoi function. def hanoiInit(numOfDisks, start, source, dest, aux, last, current, r): printMove(1, start, source, current) current+=1 current = hanoi(n,"Start","Aux1","Aux3","Aux2","Dest",current,r) printMove(1, dest, last, current) current+=1 current=1 hasItMoved = [None]*12 toDest = [None]*12 n = input("How many disks are we solving for? ") r = int(n) hanoiInit(n,"Start","Aux1","Aux3","Aux2","Dest",current,r)
true
985035622d0ea945f08a311f4b075820771d1652
mswift42/project-euler
/euler38.py
954
4.28125
4
#!/usr/bin/env # -*- coding: utf-8 -*- """Pandigital mutiples Problem 38 28 February 2003 Take the number 192 and multiply it by each of 1, 2, and 3: 192 1 = 192 192 2 = 384 192 3 = 576 By concatenating each product we get the 1 to 9 pandigital, 192384576. We will call 192384576 the concatenated product of 192 and (1,2,3) The same can be achieved by starting with 9 and multiplying by 1, 2, 3, 4, and 5, giving the pandigital, 918273645, which is the concatenated product of 9 and (1,2,3,4,5). What is the largest 1 to 9 pandigital 9-digit number that can be formed as the concatenated product of an integer with (1,2, ... , n) where n 1?""" def is_pandigital(number): if len(number) != 9: return False return sorted([int(i) for i in number]) == range(1,10) for i in range(20000, 5000, -1): number = str(i*1) + str(i*2) if is_pandigital(number): print number break # with Help From Dreamshire Blog.
true
951621c35b6c9109a5444a51e173d9d36a1a1920
jwong6100/CompSciHW
/HW3.py
2,641
4.125
4
#Author - Jonathan Wong, jfw5328@psu.edu #populating dictionaries and lists property_groups_size = {'purple':2, 'light blue':3, 'maroon':3, 'orange':3, 'red':3, 'yellow':3, 'green':3, 'dark blue':2} property_groups_size_words = {'purple':'two', 'light blue':'three', 'maroon':'three', 'orange':'three', 'red':'three', 'yellow':'three', 'green':'three', 'dark blue':'two'} property_groups_cost = {'purple':50, 'light blue':50, 'maroon':100, 'orange':100, 'red':150, 'yellow':150, 'green':200, 'dark blue':200} number_of_houses = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve'] size_of_property_group = ['none', 'one', 'two'] x = 0 #user inputs while x == 0: color = input('Which color block will you be building on? ') if color in property_groups_size: print('There are ' + property_groups_size_words[color] + ' properties and each house costs ' + str(property_groups_cost[color])) money = int(input('How much money do you have to spend? ')) x = 1 else: print('Sorry, that is not a color on the list') #converting values to integers int_size = int(property_groups_size[color]) int_cost = int(property_groups_cost[color]) #calculations for total houses and the divisions between the size of the property group total_houses = money // int_cost divided_total_houses = total_houses // int_size more_total_houses = divided_total_houses + 1 #calculating which properties will get x number of houses equal_houses = total_houses % int_size remaining_props = equal_houses other_props = int_size - equal_houses #outputs if money < int_cost: print('You cannot afford even one house.') elif divided_total_houses > 5: print('You can build ' + str(total_houses) + ' house(s) -- ' + str(other_props) + ' will have a hotel.') elif more_total_houses == 5: print('You can build ' + str(total_houses) + ' house(s) -- ' + str(other_props) + ' will have ' + str(divided_total_houses) + ' and ' + str(remaining_props) + ' will have a hotel') elif remaining_props > 0: print('You can build ' + str(total_houses) + ' house(s) -- ' + str(other_props) + ' will have ' + str(divided_total_houses) + ' and ' + str(remaining_props) + ' will have ' + str(more_total_houses)) elif remaining_props == 0: print('You can build ' + str(total_houses) + ' house(s) -- ' + str(other_props) + ' will have ' + str(divided_total_houses)) ###test ##print(divided_total_houses) ##print(equal_houses) ##print(other_int_size)
false
72833495fc0d5ab5180bbbd3cc98462bbb005ee5
ysjin0715/python-practice
/chapter6/study.py
1,268
4.15625
4
#2. print('방문을 환영합니다!') print('방문을 환영합니다!') print('방문을 환영합니다!') print('방문을 환영합니다!') print('방문을 환영합니다!') # for i in range(1000): # print('방문을 환영합니다!') #4. for i in [1, 2, 3, 4, 5]: print('방문을 환영합니다') #5. for i in [1, 2, 3, 4, 5]: print("i=",i) for a in [1, 2, 3, 4, 5]: print("9*",a,"=",9*a) #6. for b in range(5): print('방문을 환영합니다') print(list(range(10))) #7. for i in range(1,6,1): print(i,end="") for i in range(10,0,-1): print(i,end="") #8. import turtle t=turtle.Turtle() t.shape('turtle') for count in range(6): t.circle(100) t.left(360/6) #9. response='아니' while response=='아니': response=input('업마, 다됬어?'); print('먹자') #10. password="" while password!='pythonisfun': password=input('암호를 입력하시오: ') print('로그인 성공') #11. count=1 sum=0 while count<=10: sum=sum+count count=count+1 print('합계는',sum)\ #12. t.up() t.goto(0,0) t.down() i=0 while i<4: t.forward(100) t.right(90) i=i+1 #13. while True: light=input('신호등 색상을 입력하시오: ') if light=='blue': break print('전진!')
false
46811fc30524954812699c4ecc59ea0ce77735fb
Igor-Zhelezniak-1/ICS3U-Unit4-02-Python-Math_Program
/math_program.py
766
4.21875
4
#!/usr/bin/env python3 # Created by: Igor # Created on: Sept 2021 # This is math_program def main(): loop_counter = 1 answer = 1 # input integer = input("Enter any positive number: ") print("") # process & output try: number = int(integer) if number < 0: print("Please follow the instructions! Enter any POSITIVE number") else: while loop_counter <= number: answer = answer * loop_counter loop_counter = loop_counter + 1 print("{0}! = {1}".format(number, answer)) except Exception: print("Please follow the instructions! Use numbers") finally: print("") print("Done") if __name__ == "__main__": main()
true
aedda9665a6e79cc9c6fb033d1b04aa9c4ba3565
ecornelldev/ctech400s
/ctech402/module_6/M6_Codio_PROJECT/exercise_files/startercode3.py
498
4.34375
4
#### # Player and Computer each have 3 dice # They each roll all 3 dice until one player rolls 3 matching dice. ####### # import random package import random # player and computers total score player_score = 0 computer_score = 0 # define a function that is checks for three matching dice # function returns True or False # Computer and user roll until one rolls 3 matching dice # Display the 3 dice with each roll # Print both the player and computer's final score and report who wins
true
c829c9dab8968ee28dbcf12c7ed8a6f03167a632
ecornelldev/ctech400s
/ctech402/module_2/M2_Codio_PROJECT-Remove-Append/exercise_files/SolutionCode.py
515
4.125
4
Part 1: integer_list = [10,2,5,7,4,3,6,9,8,1] list_even = [] list_odd = [] for i in integer_list: if i%2 == 0: list_even.append(i) else: list_odd.append(i) print("Even numbers: " + str(sorted(list_even))) print("Odd numbers: " + str(sorted(list_odd))) Part 2: integer_list = [10, 2, 5, 7, 4, 3, 6, 9, 8, 1] integer_list.sort() list_a = list(reversed(integer_list)) integer_list.extend(list_a) index_of_max = integer_list.index(max(integer_list)) integer_list.pop(index_of_max) print(integer_list)
false
688528928849a3a923618670d60ad349799e16a2
satvikag2001/codechef
/func_game_south.py
1,541
4.1875
4
from sys import exit import func_extra prompt = ">>>>" def south(): print("You have entered the castle of DOOM ,from its rear end") print("It is dark and faint sounds of screaming can be heard.") print("you are absoulutely defenceless so like every sane peron you walk down the dusty corridor taking in") print("all that you can see.you make out 3 doors .What do you do") print("#hint:try typing 'open door 1' or 'go back'") S_dr_1_list = ['open door 1', 'open door 2', 'open door 3', 'go out'] S_dr_1 = input(prompt) while S_dr_1 not in S_dr_1_list: print("You cannot do that ") S_dr_1 = input(prompt) if S_dr_1 =="open door 1": S_dr_1_1() elif S_dr_1 =="open door 2": S_dr_1_2() elif S_dr_1 =="open door 3": S_dr_2_3() else : func_extra.dead("the grim reaper was waiting for u outside.he drank your soul\n") def S_dr_1_1() : print(" There is a giant cat here eating a cheese cake. What do you do?") print("1. Take the cake .") print("2' Scream at the bear.") cat = input(prompt) if cat == "take the cake" or cat == "1": func_extra.dead("The bear eats off yours face. Good job!") elif cat=="2"or cat == "scream at the bear": func_extra.dead("the bear eats your legs off. Good job!") else : print("Well doing %s is probably better. The bear ran away \n You win"%cat) print("there is nothing else to do ") S_dr_1_1 = input() def S_dr_1_1() : print("good") func_extra.play_again() def S_dr_1_1() : print("good") func_extra.play_again()
true
943d825de16d00b7e445aaa34666b1cad7ec2844
ishantk/GW2021PY1
/Session18C.py
2,084
4.125
4
# Why Inheritance # Code Redundancy -> Development Time class FlightBooking: def __init__(self, from_location, to_location, departure_date, travellers, travel_class): self.from_location = from_location self.to_location = to_location self.departure_date = departure_date self.travellers = travellers self.travel_class = travel_class def show(self): print("~~~~~~~~~~~~~~~~~~~~~~~~~~") print(self.from_location, self.to_location) print(self.departure_date) print(self.travellers, self.travel_class) print("~~~~~~~~~~~~~~~~~~~~~~~~~~") # RoundTripFlightBooking IS-A FlightBooking # extension class RoundTripFlightBooking(FlightBooking): def __init__(self, from_location, to_location, departure_date, travellers, travel_class, return_date): FlightBooking.__init__(self, from_location, to_location, departure_date, travellers, travel_class) self.return_date = return_date def show(self): FlightBooking.show(self) print(self.return_date) def main(): one_way_booking = FlightBooking(from_location="Delhi", to_location="Bangalore", departure_date="12th Aug 2021", travellers=2, travel_class="economy") print(vars(one_way_booking)) print() two_way_booking = RoundTripFlightBooking(from_location="Delhi", to_location="Bangalore", departure_date="12th Aug 2021", travellers=2, travel_class="economy", return_date="20th Aug 2021") print(vars(two_way_booking)) two_way_booking.show() if __name__ == '__main__': main() # Assignment: Code Inheritance looking into the PayTM App """ Types of Inheritance 1. Single Level class CA: pass class CB(CA): pass 2. Multi Level class CA: pass class CB(CA): pass class CC(CB): pass 3. Hierarchy class CD(CA): pass 4. Multiple class CE: pass class CF(CE, CA): pass """
true
fcc1f874bfc96c7da415baabe2cd152a7e831e2f
georgemaia/Logica_com_Python
/mundo01/ex008.py
387
4.15625
4
metro = float(input('Uma distância em metros: ')) km = metro * .001 hm = metro * .01 dam = metro * .1 dm = metro * 10 cm = metro * 100 mm = metro * 1000 print('A medida de {}m corresponde a'.format(metro)) print('{}km'.format(km)) print('{}gm'.format(hm)) print('{:.1f}dam'.format(dam)) print('{:.0f}dm'.format(dm)) print('{:.0f}mm'.format(cm)) print('{:.0f}mm'.format(mm))
false
7ad70114f889d526874f3bda353179532676a51c
rantsandruse/pytorch_lstm_01intro
/main_example.py
2,312
4.25
4
''' This is the "quick example", based on: https://pytorch.org/tutorials/beginner/nlp/sequence_models_tutorial.html ''' import numpy as np import torch import torch.nn as nn # This is the beginning of the original tutorial torch.manual_seed(1) # The first implementation # Initialize inputs as a list of tensors # passes each element of the input + hidden state to the next step. # Think of hidden state as memory # inputs = [torch.rand(1,3) for _ in range(5)] # for i in inputs: # # Step through the sequence one element at a time. # # after each step, hidden contains the hidden state. # out, hidden = lstm(i.view(1, 1, -1), hidden) # # inputs = torch.cat(inputs).view(len(inputs), 1, -1) lstm = nn.LSTM(3, 3) # Alternatively, we can just initialize input as a single tensor instead of a list. inputs = torch.randn(5, 1, 3) hidden = (torch.randn(1, 1, 3), torch.randn(1, 1, 3)) # clean out hidden state out, hidden = lstm(inputs, hidden) # Additional examples are given for understanding of NLL loss and Cross Entropy loss implementation in pytorch import torch.nn.functional as F softmax_prob = torch.tensor([[0.8, 0.2], [0.6, 0.4]]) log_softmax_prob = torch.log(softmax_prob) print("Log softmax probability:", log_softmax_prob) target = torch.tensor([0,0]) # Note the NLL loss is the negative log at the correct class # The real NLL Loss is the sum of negative log of the correct class. # NLL loss = -1/n (sum(yi dot log(pi)) # Note: (1/n is the average loss here, which is the default pytorch implementation (reduction=mean). What you usually # see in textbooks/wikipedia is the sum of all losses (i.e. without 1/n) (reduction=sum in pytorch). # What is being implemented by pytorch, where xi is the input. # It is taken for granted that xi = log(pi), i.e. it's already gone through the log_softmax transformation when you # are feeding it into NLL function in pytorch. # Pytorch NLL loss = -1/n (sum(yi dot xi)) # In the example below: # When target = [0,0], both ground truth classifications below to the first class --> y1 = [1,0], y2 = [1,0] # y1 = [1,0]; log(p1) = [-0.22, -1.61] # y2 = [1,0]; log(p2) = [-0.51, -0.91] # Pytorch NLL loss = -1/n (sum(yi dot xi)) = 1/2 * (-0.22*1 - 0.51*1) = 0.36 nll_loss = F.nll_loss(log_softmax_prob, target) print("NLL loss is:", nll_loss)
true
3c04e2019071ccdf771f3fd7c2bfb0189235ac59
hirenpatel1207/IPEM_Smart_Coffee
/WorkingDirectory/Raspberry_Pi_Code/calculateParticularFeature.py
1,037
4.15625
4
""" Brief: this file calculates particular features passed in the argument. Calculate various features to generate the feature vector which can be used for prediction """ import numpy as np # Note: pass the feature name correctly to avoid error def calculateParticularFeatureFunc(x, featureName): # calculateParticularFeature This function calculates various features based on arguments # X is column vector which has the given data # featureName is the name of feature the user wants to calculate featureVal = 0 if(featureName =='Root Mean Square'): featureVal = np.sqrt(np.mean(np.square(x))) if (featureName == 'Variance'): featureVal = np.var(x) if (featureName == 'Mean'): featureVal = np.mean(x) if (featureName == 'Sum Of Frequency Amplitudes'): featureVal = np.sum(x) if (featureName == 'Root Variance Of Frequency'): featureVal = np.sqrt( np.var(x)) # return the featureValue return featureVal
true
150583f46366913093372af43576e892f3d7b3e5
aysegulkrms/SummerPythonCourse
/Week3/10_Loops_4.py
345
4.1875
4
max_temp = 102.5 temperature = float(input("Enter the substance's temperature ")) while temperature > max_temp: print("Turn down the thermostat. Wait 5 minutes. Check the temperature again") temperature = float(input("Enter the new Celsius temperature ")) print("The temperature is acceptable") print("Check it again in 15 minutes")
true
5276c5526eb0c903de5a7849529da3df5d8ab49f
aysegulkrms/SummerPythonCourse
/Week2/04_Tuples_2.py
252
4.1875
4
# Accessing elements using indexing my_tuple = ('p', 'y', 't', 'h', 'o', 'n') print(my_tuple[0]) print(my_tuple[-1]) # print(my_tuple[6]) # Nested Tuple n_tuple = ("Lion", [8, 4, 6], (1, 2, 3)) # Nested Indexing # Access to n print(n_tuple[0][3])
false
2c72fae5d1d15217e09b590aafb02199897e1499
aysegulkrms/SummerPythonCourse
/Week3/01_ForLoops.py
669
4.1875
4
# Range in python list_1 = list(range(0, 11)) print(list_1) list_2 = list(range(0, 11, 2)) print(list_2) # print("Hello") # print("Hello") # print("Hello") # print("Hello") # print("Hello") for i in range(5): print("Hello {}".format(i)) for i in range(11): print(i, end=" ") print() # modulo print(17 % 5) print(10 % 3) print(18 % 7) # Example # Even numbers 2, 4, 6, 8, 10 # i % 2 == 0 for i in range(11): if i % 2 == 0: print(i, end=" ") print("\n") list_3 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for i in list_3: print(i ) print() for i in list_3: if i % 2 != 0: print(i) else: print("This is an even number")
false
ee1cc4de9e1fefc268d34dfc27d1ef6cd73573ea
nbrahman/LeetCode
/ReverseInteger.py
929
4.15625
4
''' Reverse digits of an integer. Example1: x = 123, return 321 Example2: x = -123, return -321 click to show spoilers. Note: The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows. ''' class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ strNum = str(x) intMult = 1 if (strNum[0]=="-"): strFinalNum = strNum[1:len(strNum)] intMult = -1 else: strFinalNum = strNum strRevNum = strFinalNum[::-1] print (strRevNum) rtype = 0 if (int(strRevNum)<=2147483647) and (int(strRevNum)>=-2147483648): rtype = intMult * int(strRevNum) return rtype if __name__ == '__main__': num1 = input ("enter the string for atoi: ") num2 = "9" result = Solution().reverse(num1) print (result)
true
3c7f4279f3901b455a9a8320029206845a06afc4
atriekak/LeetCode
/solutions/341. Flatten Nested List Iterator.py
2,459
4.1875
4
# """ # This is the interface that allows for creating nested lists. # You should not implement it, or speculate about its implementation # """ #class NestedInteger: # def isInteger(self) -> bool: # """ # @return True if this NestedInteger holds a single integer, rather than a nested list. # """ # # def getInteger(self) -> int: # """ # @return the single integer that this NestedInteger holds, if it holds a single integer # Return None if this NestedInteger holds a nested list # """ # # def getList(self) -> [NestedInteger]: # """ # @return the nested list that this NestedInteger holds, if it holds a nested list # Return None if this NestedInteger holds a single integer # """ class NestedIterator: #Approach: Stack of iterators #Time Complexity: O(l / n) #Space Complexity: O(d) #where l is number of lists and n is the number of integers in the nestedList #and, d is the maximum nesting depth def __init__(self, nestedList: [NestedInteger]): self.st = [] self.st.append(iter(nestedList)) def next(self) -> int: return self.nextEl.getInteger() def hasNext(self) -> bool: while self.st: try: self.nextEl = next(self.st[-1]) except: self.st.pop() continue if self.nextEl.isInteger(): return True else: self.st.append(iter(self.nextEl.getList())) return False """ from collections import deque class NestedIterator: #Approach: Flattening using recursion #Time Complexity: O(1) // flattening is a one time operation #Space Complexity: O(n) #where, n is the total number of integers in the nestedList def __init__(self, nestedList: [NestedInteger]): self.de = deque() self.flatten(nestedList) def next(self) -> int: return self.de.popleft() def hasNext(self) -> bool: return len(self.de) > 0 def flatten(self, nestedList): for el in nestedList: if el.isInteger(): self.de.append(el.getInteger()) else: self.flatten(el.getList()) return """ # Your NestedIterator object will be instantiated and called as such: # i, v = NestedIterator(nestedList), [] # while i.hasNext(): v.append(i.next())
true
7aa209132bb45a48ca45b8ec96e41af449436123
carlosmachadojr/Curso-em-Video-Python-3
/exercicio-018.py
1,245
4.5625
5
##### SENO, COSSENO E TANGENTE ##### """ CURSO EM VÍDEO - EXERCÍCIO PYTHON 18: Faça um programa que leia um ângulo qualquer e mostre na tela o valor do seno, cosseno e tangente desse ângulo. Link: https://youtu.be/9GvsphwW26k """ ############################################################################### ### INÍCIO DO PROGRAMA ######################################################## ############################################################################### from math import sin, cos, tan, radians separador = '\n' + '-'*80 + '\n' print(separador) angulo = float(input('Digite o valor do ângulo: ')) angulo_rad = radians(angulo) seno = round(sin(angulo_rad) , 2) cosseno = round(cos(angulo_rad) , 2) tangente = round(tan(angulo_rad) , 2) print('\nO seno de {}° é {}'.format(angulo , seno)) print('O cosseno de {}° = {}'.format(angulo , cosseno)) print('A tangente de {}° = {}'.format(angulo , tangente)) print(separador) ############################################################################### ### FIM DO PROGRAMA ########################################################### ###############################################################################
false
42f67ba9544b87f14631c7abce4a173e04e93f3a
carlosmachadojr/Curso-em-Video-Python-3
/exercicio-019.py
1,316
4.1875
4
##### SORTEANDO UM ITEM DE UMA LISTA ##### """ CURSO EM VÍDEO - EXERCÍCIO PYTHON 19: Um professor quer sortear um dos seus quatro alunos para apagar o quadro. Faça um programa que ajude ele, lendo o nome dos alunos e escrevendo na tela o nome do escolhido. Link: https://youtu.be/_Nk02-mfB5I """ ############################################################################### ### INÍCIO DO PROGRAMA ######################################################## ############################################################################### from random import choice separador = '\n' + '-'*80 + '\n' print(separador) aluno_1 = input('Digite o nome do primeiro aluno: ').title() aluno_2 = input('Digite o nome do segundo aluno: ').title() aluno_3 = input('Digite o nome do terceiro aluno: ').title() aluno_4 = input('Digite o nome do quarto aluno: ').title() lista = [aluno_1, aluno_2, aluno_3, aluno_4] sorteado = choice(lista) print('\nO aluno escolhido para apagar o quadro foi: {} '.format(sorteado)) print(separador) ############################################################################### ### FIM DO PROGRAMA ########################################################### ###############################################################################
false
30772d9bd9eddf2849b3c32e91c4c72179ad9e26
carlosmachadojr/Curso-em-Video-Python-3
/exercicio-003.py
949
4.25
4
##### SOMA DE DOIS NÚMEROS ##### """ CURSO EM VÍDEO - EXERCÍCIO PYTHON 003: Crie um programa que leia dois números e mostre a soma entre eles. Link: https://youtu.be/PB254Cfjlyk """ ############################################################################### ### INÍCIO DO PROGRAMA ######################################################## ############################################################################### separador = '\n' + '-'*80 + '\n' print(separador) num_1 = input('Digite um valor: ') num_2 = input('Digite outro valor: ') soma = int(num_1) + int(num_2) print('\nA soma entre {} e {} é: {}'.format(num_1 , num_2 , soma)) print(separador) ############################################################################### ### FIM DO PROGRAMA ########################################################### ###############################################################################
false
19e689c348748bbd674f6e95857764d9b9791300
carlosmachadojr/Curso-em-Video-Python-3
/exercicio-015.py
1,418
4.125
4
##### ALUGUEL DE CARROS ##### """ CURSO EM VÍDEO - EXERCÍCIO PYTHON 15: Escreva um programa que pergunte a quantidade de km percorridos por um carro alugado e a quantidade de dias pelos quais ele foi alugado. Calcule o preço a pagar, sabendo que o carro custa R$60 por dia e R$0,15 por Km rodado. Link: https://youtu.be/I4NYUeetLAc """ ############################################################################### ### INÍCIO DO PROGRAMA ######################################################## ############################################################################### separador_1 = '\n' + '-'*80 + '\n' separador_2 = '\n' + '-'*20 + '\n' print(separador_1) diarias = int(input('Quantidade de diárias: ')) quilometragem = round(float(input('\nQuilômetros percorridos: ')) , 2) custo_diaria = 60 custo_km = 0.15 custo_total = diarias * custo_diaria + quilometragem * custo_km print(separador_2) print('Com um total de {} diárias e {} quilômetros percorridos, o valor a ' .format(diarias , quilometragem) + 'pagar pelo aluguel do veículo ' + 'é de: R$ {}.'.format(custo_total)) print(separador_1) ############################################################################### ### FIM DO PROGRAMA ########################################################### ###############################################################################
false
6d8a378ed2c0b602736e903c28115b8eed176d1e
carlosmachadojr/Curso-em-Video-Python-3
/exercicio-036.py
1,488
4.46875
4
##### APROVANDO EMPRÉSTIMO ##### """ CURSO EM VÍDEO - EXERCÍCIO PYTHON 036: Escreva um programa para aprovar o empréstimo bancário para a compra de uma casa. Pergunte o valor da casa, o salário do comprador e em quantos anos ele vai pagar. A prestação mensal não pode exceder 30% do salário ou então o empréstimo será negado. Link: https://youtu.be/IV13X0QOMU8 """ ############################################################################### ### INÍCIO DO PROGRAMA ######################################################## ############################################################################### separador = '\n' + '-'*80 + '\n' print(separador) valor = float(input('Digite o valor do imóvel: R$ ')) salario = float(input('Qual o salário do comprador: R$ ')) financ = int(input('Quantos anos de financiamento: ')) prestacao = round(valor / (financ * 12), 2) valor = round(valor , 2) print(''' Uma casa no valor de R$ {} financiada em R$ {} nos resulta em {} prestações de R$ {}.'''.format(valor , financ , financ * 12 , prestacao)) if prestacao <= 0.30 * salario: print('\nEmpréstimo APROVADO.') else: print('\nEmpréstimo NEGADO.') print(separador) ############################################################################### ### FIM DO PROGRAMA ########################################################### ###############################################################################
false