blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
985059362425f8db3897ecab22b0ff818142911d
dvbnrg/lpthw
/ex5.py
524
4.15625
4
name = 'just dave' age = 28 height = 67 convertedHeight = height * 2.54 weight = 157 convertedWeight = weight * 0.45 eyes = 'brown' teeth = 'white' hair = 'black' print(f"Hi!, My name is: {name}") print(f"I'm {height} inches tall") print(f"I'm {convertedHeight} centimeters tall") print(f"I'm {weight} pounds") print(f"I'm {convertedWeight} kilograms") print(f"I have {eyes} eyes and {hair} hair") print(f"I bet my teeth aren't as {teeth} from all the coffee I drink") total = age + height + weight print(f"Total: {total}")
true
4e8f06660a2fdc0dbaf9d76031c2154cf53a08a8
wint-thiri-swe/cp1404practicals
/prac05/word_occurrences.py
1,071
4.5
4
""" Github link: https://github.com/wint-thiri-swe/cp1404practicals/blob/master/prac05/word_occurrences.py CP1404/CP5632 Practical Words in a dictionary Counting word occurrences """ words_to_count = {} # empty dictionary def count_occurrences(words): # for loop to count the number of occurrence for word in words: if word in words_to_count: words_to_count[word] += 1 else: words_to_count[word] = 1 def main(): words = input("Text: ").split() # ask for user input words.sort() # sort user input count_occurrences(words) # count occurrence function print_occurrence_value() # print occurrence value of each word def print_occurrence_value(): max_key_length = max([len(key) for key in words_to_count.keys()]) # align the outputs in one nice column # for loop to print occurrence value for word, count in words_to_count.items(): print("{:{col_width}} : {}".format(word, count, col_width=max_key_length)) if __name__ == '__main__': main()
true
85e0b101e85bf187e8c1f47dd991139532f8a246
gabmart1995/Tutorial-Python
/sintaxis Python/bucles/for.py
1,123
4.40625
4
""" Sintaxis for el elemento a recorrer puede ser una variable, tupla, cadena, etc for variable in elemento a recorrer: cuerpo del bucle for i in [1, 2, 3]: print( i ) # imprime 3 veces for estaciones in ["primavera", "verano", "otono", "invierno"]: print( estaciones ) # imprime 4 veces # recorriendo strings consultar la documentacion for k in ['pildoras', 'informaticas']: if ( k == 'informaticas' ): print( k, end="\n" ) else: print( k, end=" " ) El segundo parametro del print le dice a python que finalice la expresion con un salto o espacio """ for i in range( 5, 10 , 2 ): print( "valor de la cadena: " + str( i ) ) # print( f"valor de la cadena: { i }" ) # la funcion f dentro de print nos perimte realizar una notacion especial y jugar con datos # de diferente formato Python 3.6 valido = False email = input( "introduce tu email: " ) # len( variable ) obtiene la logitud de la cadena # print( len( email ) ) for i in range( len( email ) ): if ( email[i] == '@' ): valido = True if ( valido ): print( "el email es correcto" ) else: print( "email incorrecto" )
false
ee52e250cb25833096c2de3ceb0d33e9fbe2d9b0
karenTakarai/Python-Exercise
/ex11.py
1,219
4.21875
4
#show a string and avoid the line end with a new line print("How old are you", end=' ') #get the answer of the user and save it in the age variable age = input() #show a string and avoid the line end with a new line print("how tall are you?", end=' ') #get the answer of the user and save it in the height variable height = input() #show a string and avoid the line end with a new line print("How much do you weigh?", end=' ') #get the answer of the user and save ir in the weight variable weight = input() #show a string with the answers of the user. print(f"So, you're {age} old, {height} tall and {weight} heavy.") #---------------------------------------------------------------------> #Broken and Fixed Code print("How old are you", end=' ') age = input() print("how tall are you?", end=' ') height = input() print("How much do you weigh?", end=' ') weight = int(input()) print(f"So, you're {age} old, {height} tall and {weight + weight} heavy.") #other form------------------------------------------------------------> age = int(input("How old are you? ")) height = input("how tall are you? ") weight = input("How much do you weigh? ") print(f"So, you're {age + age} old, {height} tall and {weight} heavy.")
true
fcb9bdd16b9ebde7b675cc02823774197a5b98a4
andrewwhite5/CS-Unit-5-Sprint-2-Data-Structures
/DataStructuresI/stack.py
1,606
4.21875
4
# lets look at the idea of another data structure # a Stack like a stack of plates or books # LIFO (last in first out) # we can push items on to the stack # we can pop items off a stack # and we can peek at the item at the top of the stack # think of how you could utilise a linked list to form a stack """ A stack is a data structure whose primary purpose is to store and return elements in Last In First Out order. 1. Implement the Stack class using an array as the underlying storage structure. Make sure the Stack tests pass. 2. Re-implement the Stack class, this time using the linked list implementation as the underlying storage structure. Make sure the Stack tests pass. 3. What is the difference between using an array vs. a linked list when implementing a Stack? """ # Implement a Stack using an array for the underlying storage class StackA: def __init__(self): self.storage = [] def __len__(self): return len(self.storage) def push(self, value): self.storage.append(value) def pop(self): if len(self.storage) == 0: return None return self.storage.pop() from linked_list import LinkedList # Stack implementation using a Linked List class StackL: def __init__(self): self.size = 0 self.storage = LinkedList() def __len__(self): return self.size def push(self, value): self.storage.add_to_head(value) self.size += 1 def pop(self): if self.size == 0: return None self.size -= 1 return self.storage.remove_head()
true
81dda6ddd0e06477ff797b7619867357138f5c7c
QDylan/Learning-
/Leetcode/166. 分数到小数.py
1,619
4.125
4
""" @Time : 2020-07-07 23:11 @Author : QDY @FileName: 166. 分数到小数.py 给定两个整数,分别表示分数的分子 numerator 和分母 denominator,以字符串形式返回小数。 如果小数部分为循环小数,则将循环的部分括在括号内。 示例 1: 输入: numerator = 1, denominator = 2 输出: "0.5" 示例 2: 输入: numerator = 2, denominator = 1 输出: "2" 示例 3: 输入: numerator = 2, denominator = 3 输出: "0.(6)" """ class Solution: def fractionToDecimal(self, numerator, denominator): if numerator % denominator == 0: return str(numerator // denominator) sgn = 1 if numerator < 0: sgn *= -1 numerator = -numerator if denominator < 0: sgn *= -1 denominator = -denominator if sgn < 0: head = '-' else: head = '' head += str(numerator // denominator) + '.' # 整数部分 # print(head) r = numerator % denominator pos = 0 remainder = {} # 记录余数出现的位置 tmp = '' while True: tmp += str(r // denominator) # 记录小数部分 # print(tmp) r = r % denominator if r == 0: # 不是循环小数 return head + tmp[1:] if r in remainder: # return '%s%s(%s)' % (head, tmp[1:remainder[r] + 1], tmp[remainder[r] + 1:pos + 1]) else: remainder[r] = pos pos += 1 r *= 10
false
32514e18e5a9f3a37dc7cfac77e6c8e7e140d4c6
chrisli12/MiniGame
/game.py
2,492
4.21875
4
from random import randint # player_name = "Chris" # player_attack = 10 # player_heal = 5 # player_health = 100 # this is a list in python, it can store different type of data # player = ["Chris", 10, 5, 100] game_running = True # game begin here # while game_running is true, its gonna repeat runing this block of code def rand_monster_attack(): return randint(monster['attack_min'], monster['attack_max']) while game_running: # this is a dictionary, it can store key-matching value player = {"name": "Chris", "attack": 10, "heal": 20, "health": 100} monster = {'name': 'MadMax', 'attack_min': 5, 'attack_max': 30, 'health': 100} # enter player name print('---' * 10) print('enter player name') player["name"] = input() print(player["name"] + " has " + str(player["health"]) + " health") print("monster has " + str(monster['health']) + " health") print('---' * 10) # while this round is not false new_round = True while new_round: player_won = Falsex monster_won = False print("Monster's health now:") print(monster['health']) print("Player's health now: ") print(player["health"]) print('---' * 10) print('Please select a action') print('---' * 10) print('1) attack') print('2) heal') print('3) Exit Game') player_choice = input() # 1 if player_choice == 1: monster['health'] = monster['health'] - player["attack"] # if monster is dead if monster['health'] <= 0: player_won = True else: player["health"] = player["health"] - rand_monster_attack() # if you are dead if player["health"] <= 0: monster_won = True # 2 elif player_choice == 2: player["health"] = player["health"] + player["heal"] player["health"] = player["health"] - rand_monster_attack() if player["health"] <= 0: monster_won = True # 3 elif player_choice == 3: game_running = False new_round = False else: print("Invalid input") # if either player or monster won the game if player_won: print("game over, you win!") new_round = False if monster_won: print("game over, you lose!") new_round = False
true
2f12f5fe07bc9b2d9bced407f76c090e1bc1c5e3
langleyinnewengland/Complete_Python_Course
/29 - Destructuring Syntax.py
358
4.3125
4
#deconstructuring is taking a tuple and making many variables from it #here is a tuple currencies = 0.8, 1.2 #variables for the tuple usd, eur= c urrencies #4 tuples friends = [("Rolf", 25), ("Anne", 37), ("Charlie", 31), ("Bob", 22)] #assigns name and age to items in tuple for name, age in friends: print(f"{name} is {age} years old")
true
8e4fcb017b96f5bfc33a708207a8300942ddbe92
langleyinnewengland/Complete_Python_Course
/14 - Booleans.py
1,142
4.25
4
#booleans should be equal to true #age = int(input("Enter your age: ")) can_learn_programming = age > 0 and age < 150 #returns true of can_learn_programming is between 0-150. False otherwise print(f"You can learn programming: {can_learn_programming}.") #determine if you are of working age age = int(input("Enter your age: ")) usually_working = age >= 18 and age <=65 print(f"at {age}, you are usually not working: {usually_working}.") #one or the other. This prints Mr. Smith because Name is an empty string name = "" surname = "Smith" greeting = name or f"Mr. {surname}" #prints either name or surname. since name is empty, it uses surname print(greeting) name = input("Enter your name: ") surname = input("Enter your surname: ") greeting = name or f"Mr. {surname}" print (greeting) #and gives you the first value if it is false, otherwise it gives you the 2nd value #That's correct! The `or` keyword just returns the second value # if the first one evaluates to `False`. # That's correct! If the value on the left of the `and` operator is truthy, # we get the value on the right of the operator.
true
5bcd02b4e33ed14cff242b1c3e0223117076f6d0
santoshgawande/PythonPractices
/ds/nooccurence.py
333
4.1875
4
#No. of Occurence of each word in given string. def count(str1): count = dict() words = str1.split() for word in words : if word in count : count[word] += 1 else : count[word] = 1 return count str1 = 'india is my country all indian are my brothers and sister I love my country' print(count(str1))
true
0c966bce80c10e50d71d85f22861e471e26a161b
santoshgawande/PythonPractices
/ds/queue_using_collections.py
362
4.3125
4
#Queue using Collection.dequeue """use Dequeue from collection it will append and pop fastly in both end. """ from collections import deque queue = deque([2,3,4,5,6,8]) print("original queue: ",queue) print(type(queue)) #Operations #enqueue at last queue.append(9) print("after enqueue :", queue) #dequeue at first queue.popleft() print("after deque: ",queue)
true
14bba4e8e68a2db4e7119dbd8fbef836b8cd57da
duiliohelf/PYTHON_learning
/DHPS_NumberGuess.py
1,063
4.1875
4
#This finds out what number you are thinking about in a range of 0 to 100. #It uses a bisectin method. sec = 100 epsilon = 0.01 num_guesses = 0 low = 0 high = sec guess = (high + low)/2.0 c = guess print('Please think of a number between 0 and 100!') print('Is your secret number '+ str(guess) + '?') qst = str(input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.: ")) while qst != 'c': if qst == 'h' or qst == 'l': if qst == 'h': high = guess else: low = guess guess = (high + low) // 2 int(guess) num_guesses += 1 else: print("You have typed a wrong letter!") print('Is your secret number ' + str(guess) + '?') qst = str(input( "Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.: ")) print('Game over. Your secret number was: ' + str(guess))
true
afccd923fdb938f2cd1554a1f00e15209502133f
adhowa/Lab9
/lab9-85pt.py
563
4.25
4
############################################ # # # 85pt # # Who has a fever? # ############################################ # Create a for loop that will search through temperatureList # and create a new list that includes only numbers greater than 100 myList = [102,98,96,101,100,99,103,97,98,105] newList =[] # Insert for loop here for item in myList: if item > 100: newList.append(item) print newList # This should print [102,101,103,105]
true
0621b4a4a169ec30729a27274f8463fb6b77fc3a
kramer99/algorithms
/bst.py
1,459
4.21875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ A simple binary search tree. Works with simple key types numeric or string. """ class Node: def __init__(self, key, value): self.left = None self.right = None self.key = key self.value = value class BinarySearchTree: def __init__(self): self.root = None def get(self, key, node = None): if node == None: node = self.root if key == node.key: return node.value elif key < node.key: if node.left != None: return self.get(key, node.left) elif key > node.key: if node.right != None: return self.get(key, node.right) else: return None def insert(self, key, value, node = None): if node == None: if self.root == None: self.root = Node(key, value) return else: node = self.root if key > node.key: if node.right == None: node.right = Node(key, value) else: self.insert(key, value, node.right) elif key < node.key: if node.left == None: node.left = Node(key, value) else: self.insert(key, value, node.left) elif key == node.key: node.value = value
true
c90793f712cf30ca455c2b6716e0fb9238347a5e
pinstripezebra/Sp2018-Online
/students/John_Sekora/lesson01/Generators.py
1,646
4.1875
4
# John Sekora # Class 2, Lesson01, Generators # UW Certificate in Python, 4/9/2018 def intsum(): """ Sum of integers """ # 0 + 1 + 2 + 3 + 4 + 5 + … # so the next sequence is: # 0, 1, 3, 6, 10, 15 ... current_integer = 0 current_sum = 0 while True: yield current_sum current_integer += 1 current_sum += current_integer def intsum2(): """ Sum of integers """ # 0 + 1 + 2 + 3 + 4 + 5 + … # so the next sequence is: # 0, 1, 3, 6, 10, 15 ... current_integer = 0 current_sum = 0 while True: yield current_sum current_integer += 1 current_sum += current_integer def doubler(): ''' Doubler''' # Each value is double the previous value: 1, 2, 4, 8, 16, 32... current_number = 1 while True: yield current_number current_number *= 2 # Fibonacci Sequence def fib(): ''' The Fibonacci Sequence ''' # f(n) = f(n-1) + f(n-2) # 1, 1, 2, 3, 5, 8, 13, 21, 34 x = 1 y = 1 while True: yield x x, y = y, x + y # Prime Numbers def prime_set(x): ''' Prime Numbers ''' # Generate the prime numbers (numbers only divisible by them self and 1): # 2, 3, 5, 7, 11, 13, 17, 19, 23 … if x < 2: return False else: for n in range(2, x): if x % n == 0: return False else: return True def prime(): n = 2 while True: yield n n += 1 while True: if prime_set(n): break else: n += 1 continue
false
7f3aa4e4c9e42255112a74ed5be8c80672f4451a
pinstripezebra/Sp2018-Online
/students/alex_skrn/Lesson01/comprehensions_music.py
1,223
4.1875
4
#!/usr/bin/env python3 """Solutions to Lesson01 comprehensions assignment re music.""" import pandas as pd # Instructions summary: # 1) get artists and song names for tracks with danceability scores over 0.8 # and loudness scores below -5.0. # 2) these tracks should be sorted in descending order by danceability # 3) top five tracks are selected and printed # Load the database music = pd.read_csv("featuresdf.csv") # n, a, d, l are for name, artist, danceability, and loudness res = sorted( [ (n, a, round(d, 2), round(l, 2)) for n, a, d, l in zip(music.name, music.artists, music.danceability, music.loudness ) if d > 0.8 and l < -5.0 ], key=lambda x: x[2], reverse=True )[0:5] print(res) # prints # [('Bad and Boujee (feat. Lil Uzi Vert)', 'Migos', 0.93, -5.31), # ('Fake Love', 'Drake', 0.93, -9.43), # ('HUMBLE.', 'Kendrick Lamar', 0.9, -6.84), # ("You Don't Know Me - Radio Edit", 'Jax Jones', 0.88, -6.05), # ('Bank Account', '21 Savage', 0.88, -8.23)]
true
577c87107218e3392d172e84013df518aa3ac2ef
clwangje/cs290-hw1
/temp_convert.py
320
4.25
4
# Author: Chenliang Wang # Date: 10/3/2019 # Description: Asks the user for temperature in Celsius and then # converts and prints out the temperature in Fahrenheit print('Please enter a Celsius temperature.') Cel = float(input()) print('The equivalent Fahrenheit temperature is:') print((9 / 5) * Cel + 32)
true
d6fbd5afa53282c94accc79880ae4c24a6177205
jmaple4/Nickleforth
/nickleforth.py
683
4.5
4
# This is a program that prompts for a file name, then opens that file and # reads through the file, and print the contents of the file backwards. # you know...so Nicklebackk lyrics look like devil verses fileName = input("Enter file name: ") try: fileHandle = open(fileName) except: print('File cannot be opened:', fileName) quit() print("\nThese are the satanic verses\n".upper()) for line in fileHandle: line = line.rstrip()[::-1] print(line) # line = line.rstrip()[::-1] # this slicing reverses the strings characters: [::-1] # line = line[::-1] # this slicing reverses the strings characters: [::-1] # print('Here it is as satanic verse') # print(line)
true
d165ef7ed65511a627e011ed21bcbdb01190259b
BakerC1216/cti110
/M5HW1_DistanceTraveled_Baker.py
599
4.40625
4
# CTI-110 # M5HW1 - Distance Traveled  # BakerC1216 # 10/22/17 # Initialize the accumulator total = 0 # Get the miles traveled for each hour. for hour in range(1, 4): # Prompt the user. print("What is the speed of the vehicle in MPH?") speed = float(input("Speed: ")) # Input the speed of travel. print("How many hours has it traveled?") hours = float(input("hours: ")) # Add distance to total. distance = hour * speed total += distance # Display the toal miles. print('You have driven a total of', total, 'distance.')
true
8ec48fe9796cec3b950254398e87172ca174beb4
momopranto/CTFhub
/ctfstuff/caeserbruteforce.py
431
4.125
4
plainText = raw_input("What is your plaintext/ciphertext? ") def caesar(plainText, shift): cipherText = "" for ch in plainText: if ch.isalpha(): stayInAlphabet = ord(ch) + shift if stayInAlphabet > ord('z'): stayInAlphabet -= 26 cipherText += chr(stayInAlphabet) else: cipherText += ch print "Shifted " + str(shift) + ": ", cipherText return cipherText for shift in range(26): caesar(plainText, shift)
true
b76916f50fbdac4b887863b30f8d92430bf14306
rcmccartney/TA_code
/2014S/CSCI141/wk01/triangleWheel.py
629
4.3125
4
#!/usr/local/bin/python3 """ Using turtle to show how to make functions and the value of function re-use. It takes more to code initially, but gives us much more flexibility to re-use our drawTriangle function at a later time (shown by the one triangle off to the right after our original figure is drawn). """ from turtle import * def drawTriangle(): forward(60) left(120) forward(60) left(120) forward(60) left(120) def main(): drawTriangle() right(90) drawTriangle() right(90) drawTriangle() right(90) drawTriangle() right(90) up() forward(120) down() drawTriangle() main() input("Enter to close")
true
7cbbe9e4344cd8d8dc62627d3c468b7cd673a2dc
cpchoi/qbb2015-homework
/day2/types.py
1,015
4.125
4
#!/usr/bin/env python # String s = "A String" # Integer (can be unlimited!) i = 10000 # Floating point / real number f = 0.333 # Coerce a integer into a float, vice versa float into integer (will round) i_as_f = float(i) f_as_i = int(f) # Boolean truthy = True falsy = False # Dictionary (very improtant - because a lot of hte funcitons are built on dictionaries) d1 = { "key1":"value1", "key2":"value2" } d2 = dict( key1="value1", key2="value2" ) # putting a list in dictionary value #d3 = dict{"key1": ["hi", "bye"], "key1": "value2"} # dictionary containing a list of tuples d3 = dict( [ ("key1" , "value1"), ("key2", "value2") ] ) #Lists -- are mutable, conventions contains only one type l = [1,2,3,4,5] l.append(7) #Tuple -- can have different elements integers, strings, or floats, but are not immutable, they are a bit more efficient t = (1, "foo", 5.0) # comma after print, it will print each one with a space for value in (i, f, s, truthy, l, t, d1, d2, d3): print value, type( value )
true
91fc857dbc1e6277485bc968bff3df772ed69d00
asnewton/Data-Structure-and-Algorithm
/sorting/mergesort.py
822
4.15625
4
# Python program to implement merge sort # merge function takes two sorted arrays def merge(a, b): n = len(a) m = len(b) i, j, k = 0, 0, 0 result = [] while(i < n and j < m): if(a[i] < b[j]): result.append(a[i]) i += 1 else: result.append(b[j]) j += 1 while(i < n): result.append(a[i]) i += 1 while(j < m): result.append(b[j]) j += 1 return result def mergesort(arr, low, high): if(low == high): return arr[low] mid = (low + high) / 2 first_half = mergesort(arr, low, mid) second_half = mergesort(arr, mid+1, high) merge(first_half, second_half) if __name__ == "__main__": a = [2, 5, 3, 9, 4, 15, 55, 19, 20] mergesort(a, 0, len(a)) print(a)
false
1382a6ed437cad7868ab008786e2f719eb304510
EM180303/Prova-de-python
/Prova_3-Python/Q1.py
1,196
4.34375
4
''' [ Questão criada por Deyvid Gonçalves (adaptado)] Faça um programa que faça pesquisa do produto de um supermercado, preço e a quantidade em estoque. Para fazer esse programa use tupla e pelo menos duas funções. Para sair do programa será preciso digitar 0. A tupla deve ter no mínimo 5 produtos. ''' produtos = ('xxxxx', 'Banana','Laranja', 'Melancia', 'Manga', 'Uva', 'Caju', 'Abacate') quantidade = ('xxxxx', 50, 80, 13, 42, 30, 68, 28) preço = ('xxxx',5, 1, 10, 3, 5, 2, 7) continuaçao = True def exibir(x, y): print(f'{x}\t {y[x]} ') def verificar(x, y, z, p): print(f'Produto: {p[z]}') print(f'Quantidade em estoque: {x[z]}') print(f'Preço por unidade: R$ {y[z]}') while continuaçao == True: print('CÓDIGO\tPRODUTOS') print('-=' * 25) for i in [1,2,3,4,5,6,7]: exibir(i, produtos) print('-=' * 25) pergunta = int(input('Digite o código que deseja verificar a quantidade e o preço: (para encerrar digite 0) ')) if(pergunta == 0): print('Encerrando') break elif(pergunta < 0) or (pergunta > 7): print('Invalido, tente novamente') else: verificar(quantidade, preço, pergunta, produtos)
false
206f4aa2e7d82166f1facf2bdef21394d3b0373f
somnath1077/MachineLearningExercises
/ML_Using_Python/extras/newton_2_variable.py
1,376
4.375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Aug 10 13:57:11 2021 @author: This is code for an example on the Newton-Raphson technique for a function from R^2 to R^2. Taken from Advanced Calculus (Page 349). """ import numpy as np def f(z): x = z[0][0] y = z[1][0] x_1 = - 13 + x - 2 * y + 5 * y ** 2 - y ** 3 y_1 = - 29 + x - 14 * y + y ** 2 + y ** 3 return np.array([x_1, y_1]).reshape(2, 1) def numerator_expr_1(y): return 3 * y ** 2 + 2 * y - 14 def numerator_expr_2(y): return 3 * y ** 2 - 10 * y + 2 def denom_expr(y): return 6 * y ** 2 - 8 * y - 12 def f_jacobian(z): y = z[1][0] a = numerator_expr_1(y) / denom_expr(y) b = numerator_expr_2(y) / denom_expr(y) c = -1 / denom_expr(y) d = 1 / denom_expr(y) return np.array([[a, b], [c, d]]) def dist(v1, v2): return np.sqrt(np.sum(np.square(v1 - v2))) def newton(x0, y0, tol=1e-4): z_old = np.array([x0, y0]).reshape(2, 1) z_new = np.array([2 * x0, 2 * y0]).reshape(2, 1) d = dist(z_old, z_new) it = 0 while d > tol: z_new = z_old - np.matmul(f_jacobian(z_old), f(z_old)) d = dist(z_new, z_old) print(f'iteration: {it:3d}: x: {z_old[0][0]:10.5f}, y: {z_old[1][0]:10.5f}') z_old = z_new it += 1 return z_new if __name__ == '__main__': newton(10, 8)
false
c56d78604d914a4a49acd5fcbd2bb80910a59d88
coltensu/ZeroLearningPython
/src/logic_if.py
205
4.15625
4
""" 判断输入的边长能否构成三角形,如果能则计算出三角形的周长和面积 """ a = 1 b = 2 c = 3 if a + b > c and a + c > b and b + c > a: print('ok') else: print('not ok')
false
0904c99fe3aa6c48bd21031f18df618eba6aa7d5
DaveMcMahon/StudentGrade
/App.py
2,277
4.28125
4
#!/usr/local/bin/python3 import os import os.path class StudentGrader(object): def __init__(self): self.student_grades = {} def enter_grades(self, student_name, grade): self.student_name = student_name self.grade = grade print("Adding " + str(self.grade) + " to " + self.student_name + "'s grade scorecard..") if self.student_name in self.student_grades: self.student_grades[self.student_name] = self.grade print(str(self.grade) + " added to " + self.student_name + "'s scorecard successfully!") else: self.student_grades[self.student_name] = self.grade def remove_student(self, student_name): self.student_name = student_name if self.student_name in self.student_grades: del self.student_grades[self.student_name] print(self.student_name + " has been removed.") else: print(self.student_name + " is not in this class list") def calculate_avg_grades(self, student_name): self.student_name = student_name if self.student_name in self.student_grades: total = 0.0 count = 0 avg_total = 0.0 for key,value in self.student_grades.items(): total += self.student_grades[self.student_name] count += 1 avg_total = total / count print("The average total grade point average for " + self.student_name + " is: " + str(avg_total)) else: print(self.student_name + " is not in this class list") def show_class(self): print(self.student_grades) def main(): student_grade_obj = StudentGrader() print("[1] Enter Grades") print("[2] Remove Student") print("[3] Show the class") print("[4] Exit") user_input = input("Welcome, What would you like to do..? (1 - 3)") while user_input != "4": if user_input == "1": student_name = input("Enter the name of the student you would like to input grades for: ") grade = input("Enter the grade you would like to give to " + student_name) student_grade_obj.enter_grades(student_name, grade) elif user_input == "2": student_name = input("Enter the name of the student you would like to remove: ") student_grade_obj.remove_student(student_name) elif user_input == "3": student_grade_obj.show_class() else: print("Quitting the program...") break user_input = input("What would you like to do now? (1 - 3)") main()
false
75147fb46fe5aa27f2d710df3d8a0f30c971f718
aratik711/grokking-the-coding-interview
/two-pointers/remove-duplicates/remove-duplicates-sorted.py
852
4.1875
4
""" Given an array of sorted numbers, remove all duplicates from it. You should not use any extra space; after removing the duplicates in-place return the length of the subarray that has no duplicate in it. Example 1: Input: [2, 3, 3, 3, 6, 9, 9] Output: 4 Explanation: The first four elements after removing the duplicates will be [2, 3, 6, 9]. Example 2: Input: [2, 2, 2, 11] Output: 2 Explanation: The first two elements after removing the duplicates will be [2, 11]. Time complexity: O(N), where ‘N’ is the total number of elements in the given array. Space complexity: O(1) """ def remove_duplicates(arr): non_dup_index = 1 for i in range(1,len(arr)): if arr[i-1] != arr[i]: non_dup_index += 1 return non_dup_index print(remove_duplicates([2, 3, 3, 3, 6, 9, 9])) print(remove_duplicates([2, 2, 2, 11]))
true
ca0249c71dbaa7cb569d7fa6915360dda72cd741
aratik711/grokking-the-coding-interview
/sliding-window/no-repeat-substring/no-repeat-substring-sliding.py
874
4.4375
4
""" Given a string, find the length of the longest substring, which has no repeating characters. Example 1: Input: String="aabccbb" Output: 3 Explanation: The longest substring without any repeating characters is "abc". Example 2: Input: String="abbbb" Output: 2 Explanation: The longest substring without any repeating characters is "ab". Example 3: Input: String="abccde" Output: 3 Explanation: Longest substrings without any repeating characters are "abc" & "cde". Time complexity = O(n) """ def non_repeat_substring(string): startEle = 0 char_seen = [] max_length = 0 for i in range(len(string)): if string[i] in char_seen: char_seen = [] startEle = i char_seen.append(string[i]) max_length = max(max_length, i-startEle+1) return max_length string="abcabcd" print(non_repeat_substring(string))
true
cb086d04229636bda9be570f553cfc3b55c97eff
aratik711/grokking-the-coding-interview
/sliding-window/permutation-string/permutation-string-sliding.py
2,148
4.40625
4
""" Given a string and a pattern, find out if the string contains any permutation of the pattern. Permutation is defined as the re-arranging of the characters of the string. For example, “abc” has the following six permutations: abc acb bac bca cab cba If a string has ‘n’ distinct characters, it will have n! permutations. Example 1: Input: String="oidbcaf", Pattern="abc" Output: true Explanation: The string contains "bca" which is a permutation of the given pattern. Example 2: Input: String="odicf", Pattern="dc" Output: false Explanation: No permutation of the pattern is present in the given string as a substring. Example 3: Input: String="bcdxabcdy", Pattern="bcdyabcdx" Output: true Explanation: Both the string and the pattern are a permutation of each other. Example 4: Input: String="aaacb", Pattern="abc" Output: true Explanation: The string contains "acb" which is a permutation of the given pattern. Time complexity: O(N+M), where ‘N’ and ‘M’ are the number of characters in the input string and the pattern space complexity: O(M) """ def find_permutation(str, pattern): window_start, matched = 0, 0 char_freq = {} for chr in pattern: if chr not in char_freq: char_freq[chr] = 0 char_freq[chr] += 1 for window_end in range(len(str)): right_char = str[window_end] if right_char in char_freq: char_freq[right_char] -= 1 if char_freq[right_char] == 0: matched += 1 if matched == len(char_freq): return True if window_end >= len(pattern) - 1: left_char = str[window_start] window_start += 1 if left_char in char_freq: if char_freq[left_char] == 0: matched -= 1 char_freq[left_char] += 1 return False print('Permutation exist: ' + str(find_permutation("oidbcaf", "abc"))) print('Permutation exist: ' + str(find_permutation("odicf", "dc"))) print('Permutation exist: ' + str(find_permutation("bcdxabcdy", "bcdyabcdx"))) print('Permutation exist: ' + str(find_permutation("aaacb", "abc")))
true
1132fb08049e3b5368944d291a7945cac7794b99
prefect12/github
/LeetCode/62. Unique Paths.py
2,257
4.375
4
''' A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). How many possible unique paths are there? Above is a 7 x 3 grid. How many possible unique paths are there? Note: m and n will be at most 100. Example 1: Input: m = 3, n = 2 Output: 3 Explanation: From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: 1. Right -> Right -> Down 2. Right -> Down -> Right 3. Down -> Right -> Right Example 2: Input: m = 7, n = 3 Output: 28 ''' class Solution1: def uniquePaths(self, m, n): """ :type m: int :type n: int :rtype: int """ return (self.aux_uni([1, 1], [m, n], 0)) def aux_uni(self, cur, final, num): if cur == final: return num + 1 elif cur[0] < final[0] and cur[1] == final[1]: cur[0] += 1 num = self.aux_uni(cur, final, num) cur[0] -= 1 elif cur[1] < final[1] and cur[0] == final[0]: cur[1] += 1 num = self.aux_uni(cur, final, num) cur[1] -= 1 elif cur[0] < final[0] and cur[1] < final[1]: cur[0] += 1 num = self.aux_uni(cur, final, num) cur[0] -= 1 cur[1] += 1 num = self.aux_uni(cur, final, num) cur[1] -= 1 return num #----------------------------------------------------------------------------- def print_pretty(alist): for i in alist: for j in i: print(j,end='') print('\n') class Solution2: def uniquePaths(self, m, n): """ :type m: int :type n: int :rtype: int """ dp=[[0]*n for _ in range(m)] for i in range(m): for j in range(n): if not i: dp[i][j]=1 elif not j: dp[i][j]=1 else: dp[i][j]=dp[i-1][j]+dp[i][j-1] print_pretty(dp) return dp[m-1][n-1] n = Solution2() print(n.uniquePaths(2,3))
true
1346f067b6eb13331bf89f5f428617d094108129
tysonchamp/loan-calculator
/calculator.py
1,693
4.46875
4
# Loan Calculator # Function to calculate monthly payment def _mon_pay_(loan, interest, duration): # Interest rate r = ((interest / 100) / 12) # number of months mon = float(duration) * 12 # Calculate and return the monthly payments if interest > 0: mon_pay = loan * r * ((1 + r) ** mon) / ((1 + r) ** mon - 1) else: mon_pay = loan /(duration * 12) # Return the value return round(mon_pay, 2) # Calculating Remaining Balance def _balance_(loan, interest, duration, paid): # Interest rate r = ((interest / 100) / 12) # number of months mon = float(duration) * 12 # Calculate and return the monthly payments if interest > 0: bal = loan * (((1 + r) ** mon) - (1 + r) ** paid) / ((1 + r) ** mon - 1) else: bal = loan * (1 - (paid / mon)) # Return the value return bal # Main program starts principal = float(input("Enter loan amount:")) annual_interest_rate = float(input("Enter annual interest rate (percent):")) duration = int(input("Enter loan duration in years:")) month_pay = _mon_pay_(principal, annual_interest_rate, duration) # Output Loan's Basic Details print("LOAN AMOUNT:", principal ,"INTEREST RATE (PERCENT):", annual_interest_rate) print("DURATION (YEARS):", duration ,"MONTHLY PAYMENT:", int(month_pay)) # Counting and Printing yearly payments and remaining balance for y in range(1, duration + 1): month_pay = _mon_pay_(principal, annual_interest_rate, duration) paid = y * 12 remain_bal = _balance_(principal, annual_interest_rate, duration, paid) print("YEAR:", y ,"BALANCE:", int(remain_bal) ,"TOTAL PAYMENT", int(month_pay * (y * 12)))
true
91b05e647a9d2cfbc2966b294da72bb43a75ee01
AmitavaSamaddar/python_challenge
/pybank/bank_data.py
2,538
4.21875
4
# Importing os and csv module import os import csv # Initializing local variables row_count = 0 total_amt = 0 total_change = 0 amount = 0 previous_amt = 0 max_change = 0 max_change_month = "" min_change = 0 min_change_month = "" # csv file path csvpath = os.path.join("..", "python_data", "budget_data.csv") # Opening csv file with open(csvpath) as csvfile: # Reading csv file csvreader = csv.reader(csvfile, delimiter=',') # Read the header row first, which we will not use in the program csv_header = next(csvreader) # Read each row of data after the header for row in csvreader: #Increasing row count row_count += 1 #Reading amount for the month amount = float(row[1]) #Adding up to total total_amt += amount #Adding up to total change, activity from 2nd row onwards if row_count > 1: total_change += (amount - previous_amt) #Comparing Greatest Increase and Greatest Decrease if (amount - previous_amt) > max_change: max_change = amount - previous_amt max_change_month = row[0] elif (amount - previous_amt) < min_change: min_change = amount - previous_amt min_change_month = row[0] #Storing current amount as previous for processing previous_amt = amount #Print on screen print("Total Months: " + str(row_count)) print("Total: $" + "{:.0f}".format(total_amt)) print("Average Change: $" + "{:.2f}".format(total_change/(row_count - 1))) print("Greatest Increase in Profits: " + max_change_month + " ($" + "{:.0f}".format(max_change) + ")") print("Greatest Decrease in Profits: " + min_change_month + " ($" + "{:.0f}".format(min_change) + ")") #Writing in textfile #Open the txt file write_file = open("bank_out.txt", "w+") #Write into the file write_file.write("Bank Data Analysis") write_file.write("\n------------------\n") write_file.write("\nTotal Months: " + str(row_count)) write_file.write("\nTotal: $" + "{:.0f}".format(total_amt)) write_file.write("\nAverage Change: $" + "{:.2f}".format(total_change/(row_count - 1))) write_file.write("\nGreatest Increase in Profits: " + max_change_month + " ($" + "{:.0f}".format(max_change) + ")") write_file.write("\nGreatest Decrease in Profits: " + min_change_month + " ($" + "{:.0f}".format(min_change) + ")") #Close the files csvfile.close() write_file.close()
true
70280c626c91ad3ca048427ec0123fac7643e350
Nmazil-Dev/PythonCrashCoursePractice
/5-6.py
290
4.125
4
# life stages! age = input('Enter an age int: ') age = int(age) if age < 2: print ('Baby child') elif age < 4: print ('toddler') elif age < 13: print ('kiddo') elif age < 20: print ('teen') elif age < 65: print ('adult') elif age >= 65: print ('elder')
false
a2e7d477eab8851475257dab854e0aafba646d8c
jish6303/Python
/CourseraCourse ProgrammingforEverybody/Code/Wk4q6.py
837
4.3125
4
#Write a program to prompt the user for hours and rate per hour using raw_input #to compute gross pay. Award time-and-a-half for the hourly rate for all hours #worked above 40 hours. Put the logic to do the computation of time-and-a-half #in a function called computepay() and use the function to do the computation. #The function should return a value. Use 45 hours and a rate of 10.50 per hour #to test the program (the pay should be 498.75). You should use raw_input to #read a string and float() to convert the string to a number. Do not worry about #error checking the user input unless you want to - you can assume the user types #numbers properly. def computepay(h,r): if(h>40): a=r*40+1.5*r*(h-40) else: a=r*40 return a hrs = raw_input("Enter Hours:") h = float(hrs) p = computepay(h,10.5) print p
true
6db7394c57a52bf712abbf3758f5ab8b8f2c7712
gakshay198/python101
/ex15.py
530
4.4375
4
from sys import argv script, file = argv # Taking filename from command line. # Opening a file. txt = open(file) print(f"Here's your file {file}") # read() is used to read the opened file. # So we call read() function on txt to read the file. print(txt.read()) # Reading the file and printing it. txt.close() # Closing the file. print("Type the filename again") file1 = input(">") # Taking filename from user txt1 = open(file1) # Opening the file print(txt1.read()) # Reading the file and printing it. txt1.close()
true
56bebb2e38ac49f34effbfaabc6dd696e4a0c577
geekycaro/python-101
/Day1-Python/Input.py
973
4.375
4
# Create a variable called user_name that captures the user's first name. user_name = input("What's your name ") # Create a variable called neighbor_name that captures the name of the user's neighbor. neighbor_name = input("What's his name? ") # Create variables to capture the number of months the user has been coding. how_long = input("how long have you been coding? ") # Create variables to capture the number of months the user's neighbor has been coding. how_long1 = input("how long has he been coding? ") # Use math to calculate the combined months coded between the two users. combined = int(how_long) + int(how_long1) # Store this in a variable called total_months_coded. # Print results in the form: # I am <user_name> and my neighbor is <neighbor_name> # Together we have been coding for <total_months_coded> months! print ("I am " + user_name + " and my neighbor's name is " + neighbor_name) print ("Together we have been coding for " + str(combined))
true
a83ff8ebb975af99707f0d0f196a942852d09fab
alinefutamata/Python_Beginners
/Name_Length.py
231
4.28125
4
full_name = input("What's your full name? ") if len(full_name) <3: print("Name mus be at least 3 characteres") elif len(full_name) > 50: print("Name can be a maximum of 50 characteres") else: print("Name looks good!")
true
7bb22f454649d1c8da9b9eccc0ef44675315fbae
KevinChuang2/Foobar-With-Google
/Q2/Q2.5.py
1,974
4.125
4
#given a list of digits, find the largest number you can make out of #the digits that is divisible by 3. #for example: {3,1,4,1} would return 4311 because it is divisible by 3 def answer(l): list_finished = [] list1 = [] list2 = [] for num in l: #if the number is divisible by 3, it is always included in solution if num%3 == 0: list_finished.append(num) if num%3 == 1: list1.append(num) if num%3 == 2: list2.append(num) # list1 contains numbers who's remainder when divided by 3 is 1 list1.sort(reverse=True) # list2 contains numbers who's remainder when divided by 3 is 2 list2.sort(reverse=True) while len(list1) >= 3: # 3 numbers who have remainder of 1 can always be included # since it is sorted, we always just add the number at the front of the list # because it is the greatest number with remainder of 1 for x in range(0,3): list_finished.append(list1[0]) del list1[0] while len(list2) >= 3: # 3 numbers who have remainder of 2 can always be included for x in range(0, 3): list_finished.append(list2[0]) del list2[0] # can never add numbers in this case if len(list2) == 0 or len(list1) == 0: pass # only case where we can add two of the %3==1 and %3=2 elif len(list2) == 2: if len(list1) == 2: for x in range(0, 2): list_finished.append(list1[0]) list_finished.append(list2[0]) # otherwise, best we can do is one of the %3==1 and one of the %3==2 else: list_finished.append(list1[0]) list_finished.append(list2[0]) list_finished.sort() temp = 1 answer = 0 for num in list_finished: answer += num*temp temp *= 10 return answer def main(): list = [3,1,4,1] print(answer(list)) if __name__ == "__main__": main()
true
60d6a2b1dcbef85cf1e57920eaafd29b952b4bea
jooyg62/practice01
/prob08.py
362
4.25
4
# 문제8. 문자열을 입력 받아, 해당 문자열을 문자 순서를 뒤집어서 반환하는 함수 reverse(s)을 작성하세요. def reverse(s): result = ''; for i in range(0, len(s)): result += s[len(s)-i-1:len(s)-i] return result input_str = input('입력> ') reverse_str = reverse(input_str) print('결과>', reverse_str)
false
8871d0a5dc506243c9bdf3ce7f6d04751154f281
chl218/leetcode
/python/leetcoding-challenge/02-feb/10_copy_list_with_random_pointer.py
2,557
4.25
4
""" A linked list of length n is given such that each node contains an additional random pointer, which could point to any node in the list, or null. Construct a deep copy of the list. The deep copy should consist of exactly n brand new nodes, where each new node has its value set to the value of its corresponding original node. Both the next and random pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. None of the pointers in the new list should point to nodes in the original list. For example, if there are two nodes X and Y in the original list, where X.random --> Y, then for the corresponding two nodes x and y in the copied list, x.random --> y. Return the head of the copied linked list. The linked list is represented in the input/output as a list of n nodes. Each node is represented as a pair of [val, random_index] where: val: an integer representing Node.val random_index: the index of the node (range from 0 to n-1) that the random pointer points to, or null if it does not point to any node. Your code will only be given the head of the original linked list. Example 1: Input: head = [[7,null],[13,0],[11,4],[10,2],[1,0]] Output: [[7,null],[13,0],[11,4],[10,2],[1,0]] Example 2: Input: head = [[1,1],[2,1]] Output: [[1,1],[2,1]] Example 3: Input: head = [[3,null],[3,0],[3,null]] Output: [[3,null],[3,0],[3,null]] Example 4: Input: head = [] Output: [] Explanation: The given linked list is empty (null pointer), so return null. """ """ # Definition for a Node. class Node: def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None): self.val = int(x) self.next = next self.random = random """ class Solution: def copyRandomList(self, head: 'Node') -> 'Node': if not head: return None p = head temp = Node(p.val) copy = temp while p.next: p = p.next temp.next = Node(p.val) temp = temp.next p, q = head, copy while p: if p.random: idx = 0 target = p.random chase = head while chase != target: chase = chase.next idx += 1 qq = copy for i in range(idx): qq = qq.next q.random = qq p = p.next q = q.next return copy
true
7bb97587a87350568637f8ba10ae2618cc1d5415
chl218/leetcode
/python/hash-maps/049_group_anagrams.py
917
4.21875
4
""" Given an array of strings strs, group the anagrams together. You can return the answer in any order. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. Example 1: Input: strs = ["eat","tea","tan","ate","nat","bat"] Output: [["bat"],["nat","tan"],["ate","eat","tea"]] Example 2: Input: strs = [""] Output: [[""]] Example 3: Input: strs = ["a"] Output: [["a"]] Constraints: 1 <= strs.length <= 104 0 <= strs[i].length <= 100 strs[i] consists of lowercase English letters. """ from typing import List class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: hmap = {} for s in strs: w = ''.join(sorted(s)) if w in hmap: hmap[w].append(s) else: hmap[w] = [s] return hmap.values()
true
b7e5128724b4a3761ac54cd3811c50deb7835e09
chl218/leetcode
/python/leetcoding-challenge/04-apr/brick_wall.py
2,889
4.5
4
from collections import Counter from itertools import accumulate """ There is a brick wall in front of you. The wall is rectangular and has several rows of bricks. The bricks have the same height but different width. You want to draw a vertical line from the top to the bottom and cross the least bricks. The brick wall is represented by a list of rows. Each row is a list of integers representing the width of each brick in this row from left to right. If your line go through the edge of a brick, then the brick is not considered as crossed. You need to find out how to draw the line to cross the least bricks and return the number of crossed bricks. You cannot draw a line just along one of the two vertical edges of the wall, in which case the line will obviously cross no bricks. Example: Input: [[1,2,2,1], [3,1,2], [1,3,2], [2,4], [3,1,2], [1,3,1,1]] Output: 2 Explanation: Note: The width sum of bricks in different rows are the same and won't exceed INT_MAX. The number of bricks in each row is in range [1,10,000]. The height of wall is in range [1,10,000]. Total number of bricks of the wall won't exceed 20,000. """ class Solution: def leastBricks(self, wall): cnt = Counter() for line in wall: for place in list(accumulate(line))[:-1]: cnt[place] += 1 return len(wall) - max(cnt.values()) if cnt else len(wall) class Solution: def leastBricks(self, wall: List[List[int]]) -> int: height = len(wall) candidates = [] for curRow in range(height): if len(wall[curRow]) < 2: candidates.append(height) continue curSubSum = 0 for curCol in range(len(wall[curRow]) - 1): brickLen = wall[curRow][curCol] curSubSum += brickLen curIntersects = height - 1 # traverse up for prevRow in range(curRow-1, -1, -1): subSum = 0 for prevBrick in wall[prevRow]: subSum += prevBrick if subSum == curSubSum: curIntersects -= 1 break if subSum > curSubSum: break # traverse down for nextRow in range(curRow+1, height): subSum = 0 for nextBrick in wall[nextRow]: subSum += nextBrick if subSum == curSubSum: curIntersects -= 1 break if subSum > curSubSum: break candidates.append(curIntersects) return 0 if not candidates else min(candidates)
true
4bf06c7e422673abda64883e9d8a24aded68d900
chl218/leetcode
/python/arrays-and-strings/remove_element.py
1,952
4.125
4
""" Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The relative order of the elements may be changed. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Example 1: Input: nums = [3,2,2,3], val = 3 Output: 2, nums = [2,2,_,_] Explanation: Your function should return k = 2, with the first two elements of nums being 2. It does not matter what you leave beyond the returned k (hence they are underscores). Example 2: Input: nums = [0,1,2,2,3,0,4,2], val = 2 Output: 5, nums = [0,1,4,0,3,_,_,_] Explanation: Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4. Note that the five elements can be returned in any order. It does not matter what you leave beyond the returned k (hence they are underscores). Constraints: 0 <= nums.length <= 100 0 <= nums[i] <= 50 0 <= val <= 100 """ class Solution: def removeElement(self, nums: List[int], val: int) -> int: n = len(nums) i = 0 j = n - 1 while i <= j: if nums[i] == val: nums[i], nums[j] = nums[j], nums[i] j -= 1 n -= 1 else: i += 1 return n # def removeElement(self, nums: List[int], val: int) -> int: # slow=0 # for i in range(len(nums)): # if nums[i]!=val: # nums[slow]=nums[i] # slow+=1 # return slow
true
3830971c0a3e9beb8202092cf15ab74a956d6dbc
harshamenti/game.py
/game.py
920
4.15625
4
import random def win(comp,you): if you=='s': if comp =='s': return 'draw' elif comp =='g': return 'you lose' elif comp =='w': return 'you lose' elif you=='w': if comp =='s': return 'you lose' elif comp =='g': return 'you won' elif comp =='w': return 'draw' elif you=='g': if comp =='s': return 'you won' elif comp =='g': return 'draw' elif comp =='w': return 'you lose' else: return 'you have chosen the alphabet that is out of above 3' you = input('Your turn ') randm = random.randint(1, 3) if randm ==1: comp ="s" elif randm ==2: comp ="g" elif randm == 3: comp = "w" print(f'you have chosen "{you}" comp has choosen "{comp}" ') W=win(comp,you) print(W)
false
e616fb8e5c8af7c63146d514c922dfd46da6df3f
larrysong132/CSE-8A
/pa1.py
764
4.28125
4
#c represents celsius #f represents fahrenheit #1.1: Implementing the function to convert from Fahrenheit to Celsius def fahrenheit_to_celsius(temp_in_f): temp_in_c = (temp_in_f-32) * (5/9) return temp_in_c #1.2: Implement the interaction with the user temp_in_f_str = input('Enter temperature in fahrenheit: ' ) temp_in_f = float(temp_in_f_str) temp_in_c = fahrenheit_to_celsius(temp_in_f) print('Temperature in celsius =', temp_in_c) #1.3: Implement the function to convert from Celsius to Fahrenheit def celsius_to_fahrenheit(temp_in_c): temp_in_f = (temp_in_c * (9/5)) + 32 return temp_in_f #1.4: Converting back to Fahrenheit temp_in_f = celsius_to_fahrenheit(temp_in_c) print('Temperature in converted back to fahrenheit =', temp_in_f)
false
4aa4c6c252f53f41517afa75f20749b7988dcb3d
wpkeen/SSW540
/p3-wkeen.py
942
4.4375
4
# -*- coding: utf-8 -*- """ Created on Sun Feb 9 16:32:36 2020 @author: keenw William Patrick Keen 17th of February, 2020 Stevens Institute of Technology SSW 540 - Python Assignment #3 This script will take three inputs from the user, pass them to a user defined function and return the max of the three inputs. Parameters: inp1,2,3 - User inputs to the console that are passed to the function """ def maxOfThree(num1, num2, num3): if num1 > num2 and num1 > num3: maximum = num1 elif num2 > num1 and num2 >num3: maximum = num2 else: maximum = num3 print("The maximum of %d, %d, %d is %d" % (num1, num2, num3, maximum)) try: inp1 = int(input("Please enter the first number: \n")) inp2 = int(input("Please enter the second number: \n")) inp3 = int(input("Please enter the third number: \n")) maxOfThree(inp1, inp2, inp3) except: print("Please enter a valid number!")
true
868a57683dad3a23ea9236325f0b4c915c54a3d5
fsiddh/ALGORITHMS
/Sorting/1) Selection Sort/test.py
549
4.28125
4
def selectionsort(A): length = len(A) for i in range(0, length-1): position = i for j in range(i+1, length): if A[j] < A[position]: position = j temp = A[i] # To SWAP one can also write A[i] = A[position] # A[i], A[position] = A[position], A[i] A[position] = temp if __name__ == '__main__': unsorted_array = [3, 5, 8, 9, 5, 2] print('Unsorted Array: ', unsorted_array) selectionsort(unsorted_array) print('Sorted Array: ',unsorted_array)
false
51b7399bf8c4142fd5a9510ac909d48cb4106036
palandesupriya/python
/OOP/Inheritance/human_employee.py
747
4.125
4
''' Implement inheritance of Human Employee. ''' class Human(object): def __init__(self, name, gender): self.name = name self.gender = gender def getDetails(self): return self.name, self.gender class Employee(Human): def __init__(self, name, gender, experience, salary, desig): Human.__init__(self, name, gender) self.experience = experience self.salary = salary self.desig = desig def getDetails(self): return Human.getDetails(self), self.experience,self.salary,self.desig def main(): name,gender,experience,salary,desig = input("Enter name, gender, experience, salary, desig:") emp = Employee(name,gender,experience,salary,desig) #print emp.getDetails() print emp.__dict__ if __name__ == '__main__': main()
false
96b7d3c1943203be5ea71409490844f1260ca705
palandesupriya/python
/basic/fucntions/var_Arg_add.py
485
4.125
4
''' WAP to accept n numbers from user and display their addition. Note: use variable number of arguments ''' def add(*iNum): iSum = 0 for iTemp in iNum: iSum += iTemp return iSum def main(): print("Addition of two numbers:{}".format(add(2,3))) print("Addition of three numbers:{}".format(add(2,5,5))) print("Addition of four numbers:{}".format(add(2,3,4,5))) print("Addition of five numbers:{}".format(add(2,3,4,5,6))) if __name__ == '__main__': main()
true
3c093a08019d68316dc52febb42dabe79d88150b
palandesupriya/python
/regular expression/countoccurence_regexp.py
608
4.15625
4
''' WAP to accept pattern and string from user and count occurences of pattern in string using search method ''' import re def countalloccurence(pattern, st): lst = [] x = re.search(pattern, st) iStart = 0 iCnt = 0 while x != None: if pattern == st[x.start() + iStart: x.end() + iStart]: iCnt += 1 iStart += x.end() x = re.search(pattern, st[iStart:]) return iCnt def main(): szString = input("Enter string:") szPattern = input("Enter pattern:") print("Occurence of {} in {} are {}".format(szPattern, szString,countalloccurence(szPattern, szString))) if __name__ == '__main__': main()
true
2432af62b249bff14601613c5c46ed8d6affe74b
akshays-repo/learn.py
/files.py/basicANDtask/akshays_task1.py
1,969
4.15625
4
#1 : Write a python program to print “Hello World!” print("Hello World") #2 : Write a python program to add 3 numbers with and without using user input. print("with out int \n a = 1 \n b=2 \n c=3 ") a,b,c = 1,2,3 print("sum of a + b + c = ",(a+b+c)) x, y, z = input("Enter a three value to add use spacebar: ").split() print("sum of three numbers = ",int(x)+int(y)+int(z)) # 3 : Write a python program to find the area of a square and rectangle. a = input( "enter the length ") print("Area of square is ",int(a)*int(a)) #rectangle width = input("enter the width") height = input("enter the height") print("Area of rectanglr is ",int(width)*int(height)) #4 : Get the characters of str from 2 to 18 using both positive and negative indexing. Str = "This is a new beginning" print(f'The string is {Str}') print("postive",Str[3:20]) print("Negative",Str[-17:-3]) #listOperations(): list = [ 'abcd', 786 , 2.23, 'john', 70.2 ] print(f'The created list is {list}') print(f'Access an item from the list using its index. list[0] :{list[0]}') print(f'Access an item from the list using negative index. list[-4]: {list[-4]}') list[0] = 'xyxz' print(f'Modify an item in the list[0] : {list}') print(f'Access the items in the list using range(slicing). list[2:]: {list[2:]}') #setOperations(): set = { 'abcd', 786 , 2.23, 'john', 70.2 } print(f'The created set is {set}') #tupleOperations(): tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 ) print(f'The created list is {tuple}') print(f'Access an item from the tuple using its index. tuple[0] :{tuple[0]}') print(f'Access an item from the tuple using negative index. tuple[-4]: {tuple[-4]}') print(f'Modify an item in the tuple[0] : tuple is inmutable') print(f'Access the items in the tuple using range(slicing). tuple[2:]: {tuple[2:]}') #dictOperations(): dict = {'name': 'john','code':6734, 'dept': 'sales'} print(f'The created Dict is {dict}') dict["name"] = "akshays" print(f'The modified Dict is {dict}')
true
588ae324a6af24d831bc0479ab1c4b557b69c8ac
Harshit93192/Basic_prog
/Empdobdict.py
2,695
4.1875
4
# Maintaing the Dictionary of Employee Date of Birth by using Inner classes concept class Employee: def __init__(self, ename): self.name = ename print('Enter the Date of Birth of ',self.name) dd = int(input('Enter the Date in dd format: ')) # Enter the date of birth of Employee mm = int(input('Enter the Month in mm format: ')) yyyy = int(input('Enter the Year in yyyy format: ')) self.dob = self.DOB(dd,mm,yyyy,self.name) def display(self): self.dob.display() class DOB: def __init__(self, dd, mm, yyyy,name): self.dd = dd self.mm = mm self.yyyy = yyyy self.dd = self.ddate() self.yyyy = self.yyear() self.name = name def ddate(self): if self.mm == 1 or self.mm == 3 or self.mm == 5 or self.mm == 7 or self.mm == 8 or self.mm == 10 or self.mm == 12: if self.dd > 0 and self.dd < 32: return self.dd else: raise ValueError('Enter the date correctly') elif self.mm == 4 or self.mm == 6 or self.mm == 9 or self.mm == 11: if self.dd > 0 and self.dd < 31: return self.dd else: raise ValueError('Enter the date correctly') elif self.mm == 2 and self.yyyy% 4 == 0 and self.yyyy%100 == 0 and self.yyyy%400 == 0: if self.dd > 0 and self.dd < 30: return self.dd else: raise ValueError('Enter the date correctly') elif self.mm == 2 and self.yyyy% 4 == 0 and self.yyyy%100 == 0: if self.dd > 0 and self.dd < 29: return self.dd else: raise ValueError('Enter the date correctly') elif self.mm == 2 and self.yyyy%4 == 0: if self.dd > 0 and self.dd < 30: return self.dd else: raise ValueError('Enter the date correctly') elif self.mm == 2 and self.yyyy%4 != 0: if self.dd > 0 and self.dd < 29: return self.dd else: raise ValueError('Enter the date correctly') else: raise ValueError('Enter the month correctly') def yyear(self): if len(str(self.yyyy)) == 4: return self.yyyy else: raise ValueError('Enter the year in correct format') def display(self): Edict[self.name] = '{}/{}/{}'.format(self.dd,self.mm,self.yyyy) print(Edict) def decorator(somefunction): def wrapper(name, password): if name == 'harshit' and password == 'harshit': somefunction(name, password) else: print(' You are not authorized') return wrapper @decorator def authentic(a,b): print('Welcome to Employee Date of Birth Database') n = int(input('Enter the no. of Employees: ')) for i in range(n): ename = input('Enter the name of the employee: ') p = Employee(ename) p.display() Edict = {} username = input('Enter your name: ') password = input('Enter the password: ') authentic(username, password)
false
db26357430ce1f65b66696aee5e98eecce3fe84e
perez182/ejercicios-python
/uri1238.py
1,732
4.1875
4
'''Combinar Cadenas''' '''Implementar un programa Combiner que tome dos cadenas como parámetros y las combine, alternando letras, comenzando con la primera letra de la primera cadena, seguida de la primera letra de la segunda cadena, luego la segunda letra de la primera cadena, etc. los String más largos se añaden al final de la combinación String y se devuelve esta combinación String.''' ''' input: La entrada contiene varios casos de prueba. La primera línea de entrada contiene un número entero N que indica el número de casos de prueba. Cada caso de prueba se compone de una línea que contiene dos cadenas y cada cadena contiene entre 1 y 50 caracteres, inclusive. output: Combine las dos cadenas de entrada, como se muestra en el siguiente ejemplo, e imprima la cadena resultante. ''' # Sample Input Sample output # 2 TopCoder # Tpo oCder abab # aa bb def combiner(cadena): palabras=cadena.split(" ") cadena1=palabras[0] cadena2=palabras[1] tamaños=[len(cadena1),len(cadena2)] tamaños=sorted(tamaños,reverse=True) new_cadena="" tamaño=tamaños[0] for i in range(tamaño): if(i>=len(cadena1)): new_cadena+=cadena2[i] elif(i>=len(cadena2)): new_cadena+=cadena1[i] else: new_cadena+=cadena1[i] new_cadena+=cadena2[i] return new_cadena N=int(input()) for i in range(N): cadena=str(input()) combiner_string=combiner(cadena) print(combiner_string) def abreviatura(cadena): palabras=cadena.split(" ") print(palabras) cadena="hoje eu visitei meus pais" result=abreviatura(cadena)
false
5384f8764893a53f3723a3e368cabda950f71869
khygu0919/codefight
/Intro/sudoku.py
901
4.21875
4
''' Sudoku is a number-placement puzzle. The objective is to fill a 9x9 grid with digits so that each column, each row, and each of the nine 3x3 sub-grids that compose the grid contains all of the digits from 1 to 9. This algorithm should check if the given grid of numbers represents a correct solution to Sudoku. ''' def sudoku(grid): a=[] for k in range(3): a=[] for j in range(3): a=grid[k*3][j*3:j*3+3]+grid[k*3+1][j*3:j*3+3]+grid[k*3+2][j*3:j*3+3] for x in range(1,10): if a.count(x)>1: return False for m in range(9): a=[] for x in range(1,10): if grid[m].count(x)>1: return False for n in range(9): a.append(grid[n][m]) print a for x in range(1,10): if a.count(x)>1: return False return True
true
39a90b263de9eb6b5636e3e311d18a18b5834708
julionav/algorithms
/sorting.py
1,941
4.1875
4
def insertion_sort(array): for slot in range(1, len(array)): element = array[slot] for sorted_slot in range(slot - 1, -1, -1): sorted_element = array[sorted_slot] if element < sorted_element: array[sorted_slot] = element array[sorted_slot + 1] = sorted_element elif element >= sorted_element: break return array def selection_sort(array): for slot in range(0, len(array)): min_val = None prev_min_val_index = None for i in range(slot, len(array)): curr = array[i] if min_val is None or min_val > array[i]: min_val, prev_min_val_index = curr, i buffer = array[slot] array[slot] = min_val array[prev_min_val_index] = buffer return array def bubble_sort(array): swap = True while swap: swap = False for i in range(1, len(array)): prev = array[i - 1] curr = array[i] if prev > curr: array[i] = prev array[i - 1] = curr swap = True return array def _merge_ordered_arrays(left, right): result = [] i = 0 j = 0 for _ in range(len(left) + len(right)): if i == len(left): result.extend(right[j:]) break elif j == len(right): result.extend(left[i:]) break left_el = left[i] right_el = right[j] if left_el <= right_el: result.append(left_el) i += 1 elif right_el < left_el: result.append(right_el) j += 1 return result def merge_sort(array): if len(array) <= 1: return array half = len(array) // 2 left_array = merge_sort(array[:half]) right_array = merge_sort(array[half:]) return _merge_ordered_arrays(left_array, right_array)
true
f216d153b74b9269b5fe3a376c22f7794278b192
omitogunjesufemi/gits
/PythonBootcamp/day4/Assignment Four/Question_8.py
2,225
4.25
4
import math another_calculation = ("y" or "Y") while (another_calculation == "y") or (another_calculation == "Y"): import math first_number = float(input("Enter a number: ")) print(f""" Supported Operations + - Addition - - Subtraction * - Multiplication / - Division mod - Modulus ^ - Power log - Logarithm """) operation = str(input("Choose an operation: ")) second_number = float(input("Enter a number: ")) if operation == "+": result = first_number + second_number print(f"{first_number} {operation} {second_number} = {result}") elif operation == "-": result = first_number - second_number print(f"{first_number} {operation} {second_number} = {result}") elif operation == "*": result = first_number * second_number print(f"{first_number} {operation} {second_number} = {result}") elif operation == "/": result = first_number / second_number print(f"{first_number} {operation} {second_number} = {result}") elif operation == "mod": result = first_number % second_number print(f"{first_number} {operation} {second_number} = {result}") elif operation == "^": result = first_number ** second_number print(f"{first_number} {operation} {second_number} = {result}") elif operation == "log": if second_number == False: result = math.log(first_number) print(f"{operation} {first_number} = {result}") elif first_number == False: result = math.log(second_number) print(f"{operation} {second_number} = {result}") the_storage = [] for x in the_storage: the_storage[x] = result user_continuation = str(input(f"Do you still want to perform another calculation (Y/N/H): ")) another_calculation = user_continuation if (user_continuation == "n") or (user_continuation == "N"): # print("Thank you for using mini calculator") print(the_storage) elif (user_continuation == "h") or (user_continuation == "H"): for x in the_storage.items(): print(the_storage.items(x))
true
98ef1a203fa563107159f4be8fc74903edff0cde
omitogunjesufemi/gits
/PythonBootcamp/day2/Assignment Two/Question5.py
202
4.28125
4
# Calculating Interest balance = int(input("Enter balance: ")) interest_rate = float(input("Enter interest rate: ")) interest = balance * (interest_rate / 1200) print("The interest is " + str(interest))
true
dd30e2eb36ef307c4f6bc9910235d16c02581eb4
Kyotowired/Test
/Collatz.py
853
4.46875
4
#!/usr/bin/python ### "The purpose of this script is to verify the Collatz conjecture by inputting a single natural number (n), then, if even, enter the number into the formula n/2. If odd 3n+1." ### n = raw_input("Enter a natural number to begin.>>> ") start = n n = int(n) print "" print "" ##This definition verifies that n is a natural number def verify_nat(n): if n >= 1: pass else: print "Not a valid entry" verify_nat(n) count = 0 while n != 1: if n%2 == 0: ##Determines whether n is even n = n/2 else: n = 3*n+1 count = count+1 ##Can we print each number that is produced? ##Output to a .txt file??? print "Number of loops: " + str(count) print "Started at: " + str(start) print "" print "" exit = raw_input ("Enter 'q' to exit or a new natural number to repeat.") ##if exit == 'q': ##pass ##else: ##verify_nat(exit)
true
da01ed734b561168768c66d05e7af563da88bc88
brothenhaeusler/connect_four
/doc/dsl/flowers.py
2,255
4.125
4
class MyClass: """A simple example class""" i = 12345 def f(self): return 'hello world' class Flower: def __init__(self): self.name = "sunflower" self.color = "yellow" # element {1, .. , 10} self.objective_attraction_level = 6 # element {1, .. , 10} self.obvious_dating_ingenuity_level = 5 self.estimated_gift_pathos_level= self.calculate_gift_pathos_level() # name = "sunflower" # color = "yellow" # # element {1, .. , 10} # objective_attraction_level = 6 # # element {1, .. , 10} # obvious_dating_ingenuity_level = 5 # estimated_gift_pathos_level= self.calculate_gift_pathos_level() # #estimated_gift_pathos_level= 10 def calculate_gift_pathos_level(self): return int( (self.objective_attraction_level + self.obvious_dating_ingenuity_level) / 2) def __str__(self): return "Flower=>" + "[" + self.name + ","+ self.color + ", obvious_dating_ingenuity_level: " + str(self.obvious_dating_ingenuity_level) + ", objective_attraction_level: " + str(self.objective_attraction_level) + ", estimated_gift_pathos_level: " + str(self.estimated_gift_pathos_level) + "]" def set_name(self, _name): self.name = _name return self def set_color(self, _color): self.color = _color return self def set_attraction_index(self, _objective_attraction_level): self.objective_attraction_level = _objective_attraction_level self.estimated_gift_pathos_level=self.calculate_gift_pathos_level() return self def set_ingenuity_index(self, _obvious_dating_ingenuity_level): self.obvious_dating_ingenuity_level = _obvious_dating_ingenuity_level self.estimated_gift_pathos_level=self.calculate_gift_pathos_level() return self flower_1 = Flower() flower_2 = Flower() flower_3=Flower() flower_1.set_name("lily").set_color("violet").set_attraction_index(7).set_ingenuity_index(9) flower_2.set_name("tulip").set_color("red").set_attraction_index(8).set_ingenuity_index(3) flower_3.set_name("hyacinth").set_color("blue").set_attraction_index(5).set_ingenuity_index(8) print("Print Flowers...") print(flower_1) print(flower_2) print(flower_3)
false
8bd8681053cb24ad0b7b605d33483e321e67abbf
LittleDevXD/PythonCrashCourse-repo
/code/chapter5/stages_of_life.py
272
4.125
4
person_age = int(input("Your age: ")) if person_age < 2: print("Baby") elif person_age < 4: print("Toddler") elif person_age < 13: print("Kid") elif person_age < 20: print("Teenager") elif person_age < 65: print("Adult") else: print("Elder")
false
34d910882bac4e900eb8069e6f86a826faeae836
AveyBD/HelloPy
/7.formated string.py
341
4.28125
4
first_name = input('What is your first name') last_name = input("What is your last name") #Lets Add two Name con = first_name + last_name print(con) #formated String formated = f'{first_name} [{last_name}] is a computer programmer]' print(formated) #We Can also directly print. print(f'{first_name} [{last_name}] is a computer programmer]')
true
1bf62ec36bc567bac74f580d98ff644ecc4fbd22
AveyBD/HelloPy
/9.arithmetic.py
287
4.40625
4
#We can do all the mathematics operation in python print(10+5) print(10-5) print(10/5) print(10*5) print(7 % 3) #We can print without the decimal value. Just we have to add another forward slash print(7 // 2) #Power of a int print(10 ** 7 ) #augmented variable x = 5 x += 3 print(x)
true
ff0ee816edb67660fd8063add3ef4388ac138b30
mischelay2001/WTCSC121
/CSC121Lab01_Lab08_Misc/CSC121Lab5Problem4_RandomIntergerSearch.py
1,575
4.34375
4
__author__ = 'Michele Johnson' # Program Requirements # Write a Python program to do the following: # (a) Ask the user to enter 6 integers. Store them in a list. Display the list. # (b) Select elements that are larger than 20. # Copy these elements to another list. Display that list. # Introduce program print('This program requests integers to form a list. ' '\nValues in the list that meet program criteria will be copied to another list. \n') # Declare Variables list_len = 6 list_filter = 20 list_a = [] list_b = [] element_count = 0 filter_count = 0 # Get input from user print(list_len, 'numbers are needed for the list:\t\t\t\n') while element_count < list_len: user_number = int(input('Enter an integer:\t\t')) list_a.append(user_number) element_count = element_count + 1 print('\nThank you!\n' 'Values greater than', list_filter, 'will be added to a new list.') # Filter to new list element_count = 0 while element_count < list_len: if list_a[element_count] > list_filter: list_b.append(list_a[element_count]) element_count = element_count + 1 if list_b != []: list_len = len(list_b) list_b.sort() print('\nThe following values were greater than', list_filter, 'and have been added to a second list:') element_count = 0 while element_count < list_len: print(list_b[element_count]) element_count = element_count + 1 else: print('\nNone of the ', list_len, ' values entered were greater than ', list_filter, '.', sep='')
true
5c38f9c088f9e0a651f2d91276b6a1ee09f5f338
mischelay2001/WTCSC121
/CSC121Lab01_Lab08_Misc/CSC121Lab7Problem1_BMIAndBPCalculator.py
2,043
4.65625
5
__author__ = 'Michele Johnson' # Program Requirements # A health insurance company wants a program to promote health and fitness. # This program can do two things: calculate BMI (Body Mass Index) and determine # whether a person has high blood pressure. # To calculate BMI, the user must enter his height (in inches) and weight (in pounds). # Use the following formula to calculate BMI: # # BMI = (703 * weight) / (height*height) # # To determine whether a person has high blood pressure, # the user must enter his systolic pressure and diastolic pressure. # If the systolic pressure >= 140 or the diastolic pressure is >= 90, he has high blood pressure. # Define and use the following two functions in this program: # # calc_bmi: Get height and weight from the user. Calculate and display BMI. # hypertension: Get systolic pressure and diastolic pressure from the user. # # Determine and display whether the user has high blood pressure. # # Also write and use a main function to implement the mainline logic of the program. # The user calculates BMI first, then determines whether the user has high blood pressure. def main(): print('LEARN YOUR BODY MASS INDEX (BMI) AND IF YOUR BLOOD PRESSURE (BP) IS IN NORMAL RANGE\n') bmi() bp() def bmi(): bmi_height = int(input('Enter your height in inches:\t\t\t\t\t')) bmi_weight = int(input('Enter your weight in pounds:\t\t\t\t\t')) bmi_result = (703*bmi_weight)/(bmi_height*bmi_height) print('Your BMI is ' + format(bmi_result, ',.2f') + "%.\n") def bp(): systolic = int(input('Enter your systolic (top number) from your blood pressure reading:\t\t\t\t\t')) diastolic = int(input('Enter your diastolic (bottom number) from your blood pressure reading:\t\t\t\t')) if systolic >= 140 or diastolic >= 90: print('Your BP readings indicate you have high blood pressure. Consult your doctor.\n') else: print('Your BP readings indicate your blood pressure is within normal range.\n') main()
true
e78131f7e768fd2af6bdfb17d89dee17486ebead
mischelay2001/WTCSC121
/CSC121Lab01_Lab08_Misc/CSC121Lab3Problem2_BTUExtraSunlight.py
2,929
4.5625
5
__author__ = 'Michele Johnson' # Program requirements: # The program asks the user to enter the room’s length, width and height, # and uses the following formula to calculate the number of btu needed: # btu needed = room volume * 3.5 # Now we want to add one more consideration. # If the room gets a lot of sunlight, number of btu needed will increase by 20%. # The program needs to ask the user whether the room gets a lot of sunlight. # The user answers ‘yes’ or ‘no’. Adjust the number of btu needed if necessary. # Introduce the program print("This program will determine the air conditioner capacity in btu's required to cool a room." "\nIt will make adjustments for rooms with extra sunlight.\n") print('Please enter the following room dimensions...\n') # Get initial dimension input from user length = input('Enter length of the room in feet: ') width = input('Enter width of the room in feet: ') height = input('Enter height of the room in feet: ') boolean_valid_dimension = False # Validate if dimension input are floats while boolean_valid_dimension is False: try: length = float(length) width = float(width) height = float(height) boolean_valid_dimension = (float(length) >= 0) and (float(width) >= 0) and (float(height) >= 0) except: pass print('\nInvalid entry. Please re-enter each room dimension as a number...\n') # Re-ask for valid input length = input('Enter length of the room in feet: ') width = input('Enter width of the room in feet: ') height = input('Enter height of the room in feet: ') boolean_valid_dimension = (float(length) >= 0) and (float(width) >= 0) and (float(height) >= 0) # Get initial sunlight input from user extra_sunlight = int(input('\nDoes the room have extra sunlight? Please type "1" for YES or "2" for NO. ')) Boolean_Valid_Entry_Sun = extra_sunlight is 1 or extra_sunlight is 2 # Validate if sunlight input is 1 or 2 while Boolean_Valid_Entry_Sun is False: print('Invalid entry. Please type "1" for YES or "2" for NO.') # Re-ask for valid input extra_sunlight = int(input('\nDoes the room have extra sunlight? Please type "1" for YES or "2" for NO. ')) Boolean_Valid_Entry_Sun = extra_sunlight is 1 or extra_sunlight is 2 # Calculations btu = (float(length)) * (float(width)) * (float(height)) * 3.5 need_btu = btu + (btu * 0.20) # Output # There is extra sunlight if extra_sunlight is 1: print('\nYou have indicated there is extra sunlight in the specified room.') print('A ' + format(need_btu, ',.0f') + ' BTU capacity air conditioner would be required to cool this room.') # There is no extra sunlight else: print('\nSince the room does not receive extra sunlight, a ' + format(btu, ',.0f') + ' BTU capacity air conditioner would be sufficient to cool this room.')
true
ecd015be24e95166d0bc9b5f1cec8207e5d175f4
mischelay2001/WTCSC121
/CSC121Lab01_Lab08_Misc/CSC121Lab6Problem3_CopyLists.py
1,026
4.1875
4
__author__ = 'Michele Johnson' # Program Requirements # Write a Python program to do the following: # (a) Create a list named list1 to store this sequence of numbers: 4, 7, 5, 8, 1, 2, 6, 3. # (b) Create a list named list2. Copy all elements of list1 to list2. # Display list2. # (c) Create a list named list3. Copy the first 4 elements of list1 to list3. # Display list3. # (d) Create a list named list4. Copy the last 4 elements of list1 to list4. # Display list4. # Introduce program print('This program copies list elements to create new lists.\n') # Declare Variables list1 = [4, 7, 5, 8, 1, 2, 6, 3] list2 = [] list3 = [] list4 = [] all_lists = [] # Calculations list2 = list1 print(list2) for x in range(0,4,1): list3.append(list1[x]) print(list3) y = len(list1) -1 while y > 3: list4.append(list1[y]) y = y - 1 print(list4) # # # Output # print(list2) # print(list2) # print(list3) # print(all_lists) # for x in range(len(all_lists)): # print(all_lists[x])
true
e4fb9e7d9e0d52234ed6cb7193d8915087b9d890
mischelay2001/WTCSC121
/CSC121Lab13_OOP/CSC121Lab13Problem3_OOP_DriveNewCar/car.py
2,163
4.125
4
__author__ = 'Michele Johnson' """ Write a new version of the DriveCar project you wrote in Problem 1. Create a new Python project DriveCarNew and copy the files from the old project. Make the following changes to class Car: (a) Change all instance variables to private (b) Write getter method for speed. (c) Define a __str__ method to display the car’s make, model and speed. Car -make: String -model: String -speed: Integer +create(car_make: String) +accelerate(): Integer +decelerate(): Integer +getSpeed(): Integer +entry_choice(): Integer """ from Lab14_OOP2_Problem1_MealOrderTemp.valid_entry import integer_entry class Car: """ Creates three private instance variables to store the car’s make, model, and speed """ def __init__(self, car_make, car_model): """ constructor of class Car """ self.__make = car_make self.__model = car_model self.__speed = 0 def accelerate(self): """ increases speed by 5 """ self.__speed += 5 def decelerate(self): """ decreases speed by 5""" self.__speed -= 5 if self.__speed < 0: self.__speed = 0 def get_speed(self): """ gets and returns speed""" return self.__speed def __str__(self): """ converts class to string """ return '\nMake:\t\t\t' + self.__make + '\nModel:\t\t\t' + self.__model + '\nFinal speed:\t' + str( self.__speed) def entry_choice(self): """ gets valid menu choice """ a_choice = 0 is_valid = False while is_valid is False: print("Menu:\n" "\t 1 to Accelerate\n" "\t 2 to Decelerate\n" "\t 3 to Exit") request_text = "Enter selection" a_choice = integer_entry(request_text) if a_choice < 1 or a_choice > 3: print("\nNot a valid selection.\n" "Please try again.\n") else: is_valid = True return a_choice
true
68fd4a164ae5beb5bb00d1ff1eaa2ada28cd0d67
Clucas0311/hangman.py
/already_guessed.py
778
4.21875
4
already_guessed = "ijklm" while True: # Loop will keep asking the player for a letter until # they enter a letter that hasn't already been guessed guess = input("Guess a letter: ") guess = guess.lower() if len(guess) != 1: # if guess is not a single letter print("Please enter a single letter.") elif guess in already_guessed: # if letter has already been guesssed print("Come on! You've already guessed that letter please \ try again: ") elif guess.isalpha() == False: # Checks for alpha letter print("Please enter a LETTER") else: print(guess) # if all the conditions are false then the else # statement executes and returns the value of the guess letter
true
245b74a5b576dff83efaeab903c4767bb04b6acf
MayuriTambe/FellowshipPrograms
/LeapYear.py
495
4.3125
4
#Print the year Leap year or not year=int(input("Enter the year")) #Take input from user def LeapYear():#Defining function LeapYear if ((year % 400 == 0) or ((year % 4 == 0) and (year % 100 != 0))): #if the year is divisible 400 OR year is divisible by 4 # but not divisible by 100 print("This is leap year") # if condition is true then print leap year else: print("This is not leap year") # if condition is false then print not leap year print(LeapYear())
true
60d4119603ad7c83fd28b69eedda6729452c6373
GraceDurham/hackbright_challenges
/longest_word.py
269
4.3125
4
def find_longest_word(words): """Return longest word in list of words""" longest = len(words[0]) for word in words: if longest < len(word): longest = len(word) return longest print find_longest_word(["hi", "hello"])
false
633190ded36f318c11a4b2b6b4c38c61b0aa4445
DarrenMannuela/I2P-Exercise-3
/Exercise 3 I2P_no.1.py
465
4.25
4
def convert_to_days(): hours = int(input("Enter number of hours:")) minutes = int(input("Enter number of minutes:")) seconds = int(input("Enter number of seconds:")) hours_to_days = hours/24 minutes_to_days = minutes/1440 seconds_to_days = seconds/86400 days = round(hours_to_days + minutes_to_days + seconds_to_days, 4) print(days) return hours_to_days, minutes_to_days, seconds_to_days convert_to_days()
true
8820963655a764f8ec11af96cc107f2505aae5db
sumedhbadnore/Python-Projects
/Tkinter projects/Basics/entry.py
656
4.34375
4
from tkinter import * root = Tk() # to create input box e = Entry(root, width=30) e.pack() e.insert(0,"Enter Your Name:") def Button1(): hello = "Hello! " + e.get() label1 = Label(root, text=hello) label1.pack() # to create and display button # remember not use () after calling a function here myButton1 = Button(root, text="OK", command= Button1, padx=25) myButton1.pack() e2 = Entry(root, width=30) e2.pack() e2.insert(0,"Email ID:") def Button2(): label1 = Label(root, text=e2.get()) label1.pack() myButton2 = Button(root, text="OK", command=Button2, padx=25) myButton2.pack() root.mainloop()
true
6c604376ab08be9ded3a08eea2ffa163f38687b3
sumedhbadnore/Python-Projects
/Tkinter projects/Basics/grid.py
275
4.1875
4
from tkinter import * root = Tk() # Creating label myLabel = Label(root, text="Hello World!") myLabel2 = Label(root, text="My name is Sumedh, nice to meet you!") # Shoving it onto screen myLabel.grid(row=0, column=0) myLabel2.grid(row=1, column=0) root.mainloop()
true
84f42f565ac6a83f3cb8fa8dac689acd8f5bcacf
lulu-mae/Sign-Language-App
/main.py
631
4.40625
4
import sqlite3 with sqlite3.connect('countryinfo.db') as db: pass CREATE TABLE countryInfo( CountryName text, Vaccine text, WaterStatus text, Allergies text, Weather text, LGBTQsafety text, WomenSafety text, Primary Key(CountryName)); def display_info (place): choice = input("What would you like to know? 1) Vaccine+medicine status. 2) Drinking water. 3) Allergies. 4) Weather conditions. 5) LGBTQ+ safety. 6) Women's safety.") if choice == 1: fetchData = "SELECT Vaccine from countryinfo.db" print ("Hello user! Welcome to the app!") place = input("Where are you travelling to?")
true
7da4973e9c7579c8454f6adf4058566b3b4e2c4b
mike03052000/python
/Training/2014-0110-training/Code_python/Database/Solutions/db_read_simple.py
1,265
4.6875
5
#!/usr/bin/env python """ Sample of simple database query using the Python DB API. Show how to use the cursor object (1) to fetch rows and (2) to use the cursor object as an iterable. """ import sys import sqlite3 def test(): args = sys.argv[1:] if len(args) != 1: sys.stderr.write('\nusage: python db_read_simple.py <dbname>\n') sys.exit(1) dbname = args[0] connection = sqlite3.connect(dbname) cursor = connection.cursor() hr('Show rows using cursor as an iterable.') cursor.execute('select * from plants order by name') for row in cursor: print '1. row:', row hr('Show rows using fetchall().') cursor.execute('select * from plants order by name') rows = cursor.fetchall() for row in rows: print '2. row:', row hr('Show field descriptions') cursor.execute('select * from plants order by name') for field in cursor.description: print 'field:', field for row in cursor: for idx, field in enumerate(row): content = '%s: "%s"' % (cursor.description[idx][0], field, ) print content, print connection.close() def hr(msg): print '-' * 50 print msg print '-' * 50 if __name__ == '__main__': test()
true
999e23eab446d2d67def4ee4eb95f733849952ae
mike03052000/python
/Training/2014-0110-training/Code_python/TextAndFiles/Solutions/words3.py
1,742
4.3125
4
#!/usr/bin/env python """ Split each line in a file into words. Count the words. Use re.split(). Usage: python words.py [options] infile Options: -h, --help Display this help message. Example: python words.py myfile.txt """ # # Imports: import sys import getopt import re def count_words(infilename): """Count the words in a file. Return a dictionary of words and counts. """ infile = open(infilename, 'r') word_dict = {} for line in infile: if line.startswith('#'): continue words = split_words(line) for word in words: if word: if word in word_dict: word_dict[word] += 1 else: word_dict[word] = 1 infile.close() return word_dict PAT1 = re.compile(r'\W*') def split_words(line): words = re.split(PAT1, line) return words def show_words(word_dict): count = 0 words = word_dict.keys() words.sort() for word in words: word_count = word_dict[word] print 'Word: "%s" count: %d' % (word, word_count, ) count += word_count print '=' * 40 print 'Total words: %d' % (count, ) def test(infilename): word_dict = count_words(infilename) show_words(word_dict) USAGE_TEXT = __doc__ def usage(): print USAGE_TEXT sys.exit(1) def main(): args = sys.argv[1:] try: opts, args = getopt.getopt(args, 'h', ['help', ]) except: usage() for opt, val in opts: if opt in ('-h', '--help'): usage() if len(args) != 1: usage() infilename = args[0] test(infilename) if __name__ == '__main__': #import pdb; pdb.set_trace() main()
true
c2860edf6b587e0637914bfb9f1ddded78c87deb
mike03052000/python
/Training/2014-0110-training/Exercises_python/Solutions/elementtree_walk.py
2,336
4.3125
4
#!/usr/bin/env python """ Synopsis: Process an XML document with elementtree. Show the document tree. Modify the document tree and then show it again. Usage: python elementtree_walk.py [options] infilename Options: -h, --help Display this help message. Example: python elementtree_walk.py myxmldoc.xml Hints: - xml.etree.ElementTree module in the Python standard library - Or, if you have installed it, use Lxml () Solution: Solutions/elementtree_walk.py Solutions/lxml_walk.py """ import sys import getopt import time # use elementtree instead of lxml from xml.etree import ElementTree as etree def show_tree(doc): root = doc.getroot() show_node(root, 0) def show_node(node, level): show_level(level) print 'tag: %s' % (node.tag, ) for key, value in node.attrib.iteritems(): show_level(level + 1) print '- attribute -- name: %s value: "%s"' % (key, value, ) if node.text: text = node.text.strip() show_level(level + 1) print '- text: "%s"' % (text, ) if node.tail: tail = node.tail.strip() show_level(level + 1) print '- tail: "%s"' % (tail, ) for child in node.getchildren(): show_node(child, level + 1) def show_level(level): for x in range(level): print ' ', def modify_tree(doc, tag, attrname, attrvalue): root = doc.getroot() modify_node(root, tag, attrname, attrvalue) def modify_node(node, tag, attrname, attrvalue): if node.tag == tag: node.attrib[attrname] = attrvalue for child in node.getchildren(): modify_node(child, tag, attrname, attrvalue) def test(docname): """Test the functions in this module. """ doc = etree.parse(docname) show_tree(doc) print '-' * 50 date = time.ctime() modify_tree(doc, 'person', 'date', date) show_tree(doc) USAGE_TEXT = __doc__ def usage(): print USAGE_TEXT sys.exit(1) def main(): args = sys.argv[1:] try: opts, args = getopt.getopt(args, 'h', ['help', ]) except: usage() for opt, val in opts: if opt in ('-h', '--help'): usage() if len(args) != 1: usage() docname = args[0] test(docname) if __name__ == '__main__': #import pdb; pdb.set_trace() main()
true
3240a4861835743383217a7768313f9a16aa7df0
mike03052000/python
/Training/HackRank/Level-1/class-2.py
1,336
4.375
4
class Employee: 'Common base class for all employees' ''' An object's attributes may or may not be visible outside the class definition. You need to name attributes with a double underscore prefix, and those attributes then are not be directly visible to outsiders. ''' __empCount = 0 def __init__(self, name, salary): self.name = name self.salary = salary Employee.__empCount += 1 def displayCount(self): print("Total Employee %d" % Employee.__empCount) def displayEmployee(self): print("Name : ", self.name, ", Salary: ", self.salary) "This would create first object of Employee class" emp1 = Employee("Zara", 2000) "This would create second object of Employee class" emp2 = Employee("Manni", 5000) emp1.displayEmployee() emp2.displayEmployee() emp1.displayCount() # print("Total Employee %d" % Employee.__empCount) #error, cannot access __empCount emp1.age = 7 # Add an 'age' attribute. emp1.age = 8 # Modify 'age' attribute. # del emp1.age # Delete 'age' attribute. print(hasattr(emp1, 'age')) # Returns true if 'age' attribute exists print(getattr(emp1, 'age')) # Returns value of 'age' attribute print(setattr(emp1, 'age', 8)) # Set attribute 'age' at 8 print(dir(Employee)) # delattr(empl, 'age') # Delete attribute 'age'
true
6a0be9160a8a18409bcaf0d7f7153dad2e2dfeb5
mike03052000/python
/Training/2014-0110-training/Code_python/Oop/Solutions/point1.py
2,186
4.25
4
#!/usr/bin/env python """ Sample classes that support addition of points and calculation of vectors. """ import math NO_COLOR, RED, GREEN, BLUE = range(4) STR_COLOR_MAP = { NO_COLOR: 'white', RED: 'red', GREEN: 'green', BLUE: 'blue', } class Point(object): """A basic Cartesian point that knows its position in space (abscissa and ordinate). """ def __init__(self, x=0.0, y=0.0): self.x = x self.y = y def get_x(self): return self.x def set_x(self, x): self.x = x def get_y(self): return self.y def set_y(self, y): self.x = y class RGBPoint(Point): """A point that knows its color and can describe itself. """ def __init__(self, x=0.0, y=0.0, color=NO_COLOR): Point.__init__(self, x, y) self.color = color def describe(self): str_color = STR_COLOR_MAP[self.color] return 'x: %8.2f y: %8.2f color: %s' % (self.x, self.y, str_color, ) class CalculatingPoint(RGBPoint): """A point that can calculate the sum and difference between itself and another point. """ def vector(self, point): magnitude = 0 direction = 0 return magnitude, direction def sum(self, point): """Return the sum of this Point and another Point. """ x1 = self.x y1 = self.y x2 = point.get_x() y2 = point.get_y() x3 = x1 + x2 y3 = y1 + y2 return Point(x3, y3) __add__ = sum def difference(self, point): """Return the difference of this Point and another Point. """ x1 = self.x y1 = self.y x2 = point.x y2 = point.y distance = math.sqrt(((x2 - x1) ** 2) + ((y2 - y1) ** 2)) return distance __sub__ = difference def test(): p1 = CalculatingPoint(10.0, 10.0) p2 = CalculatingPoint(20.0, 20.0) print 'distance: %8.3f' % (p1.difference(p2), ) print 'distance: %f' % (p1 - p2, ) p2.set_x(30) p2.set_y(40) print 'distance: %f' % (p1 - p2, ) cp1 = RGBPoint(5.0, 8.0, RED) print cp1.describe() if __name__ == '__main__': test()
true
2ad1f251ebc95fc0efbc57a166695c6f630818a8
mike03052000/python
/Training/2014-0110-training/Code_python/TextAndFiles/Solutions/filter2.py
1,835
4.3125
4
#!/usr/bin/env python """ Filters using generator functions. Use generator functions to write filters. Each filter function takes the following arguments: 1. An iterable 2. A function that returns the line filtered or None if the item is to be skipped. Each filter function returns a generator (because the function contains yield). """ def isiterable(x): """Return True if the arg is iterable. """ try: iter(x) except TypeError: return False return True def filter(iterable, filter_func): """Filter the strings in iterable using filter_func. Return a generator function. """ for item in iterable: item = filter_func(item) if item is not None: yield item def add_double_mash(line): """Add comment characters ("## ") to the start of the line. """ return '## %s' % line def rstrip_line(line): """Strip whitespace off the right end of the line. """ return line.rstrip() def skip_if_emptystring(line): """Return None if the line is empty of contains only whitespace. """ if line.isspace(): return None else: return line def test(): """Run a test of this module. """ # Separate generator objects. infilename = 'filter2.py' infile = open(infilename, 'r') g1 = filter(infile, skip_if_emptystring) g2 = filter(g1, add_double_mash) g3 = filter(g2, rstrip_line) for line in g3: print line infile.close() # Nested calls to generator functions. print '-' * 50 infile = open(infilename, 'r') for line in filter( filter( filter(infile, skip_if_emptystring), add_double_mash), rstrip_line): print line infile.close() if __name__ == '__main__': test()
true
6046a1002038db799d92e03bac1db16182aac1d6
ziaurjoy/Python-Data-Structure-And-Algorithm
/Time and space complexity/Space complexity.py
819
4.3125
4
# n = int(input()) # # if n % 2 == 0: # Space complexity is O(1) # print(n, "Is even number") # else: # print(n, "Is odd number") # n = int(input()) # even = [False] * (n+1) # Space complexity is O(n) # for i in range(0, n+1, 2): # even[i] = True # print(even) # n = int(input()) # count = 0 # for i in range(n): # for j in range(n): # Complexity O(n^2) # count += 1 # print(count) # n = int(input()) # count = 0 # for i in range(n): # for j in range(n): # for k in range(n): # Complexity O(n^3) # count += 1 # print(count) n = int(input()) count = 0 for i in range(n): # Complexity 0(n) count += 1 for i in range(n): for j in range(n): # Complexity O(n^2) # """ # O(n+n^2) = O(n^2) # """ count += 1 print(count)
false
26803b446432b3d65eb0eb2ae3a6118a9163610b
jbbranch9/jbbranch9.github.io
/CS_160/Python_Programs/Programs/loan_calc/loan_calc.py
1,262
4.34375
4
import math #this function prompts for input while ensuring the returned value is a number def get_float(prompt): x = "x" while type(x) != float: try: x = float(input(prompt)) except ValueError: print("") print("Error: Input must be a number.") print("") return x #this function prompts for input while ensuring the returned value is an integer greater than zero def get_int(prompt): x = "x" while type(x) != int or x <= 0: try: x = int(input(prompt)) except ValueError: print("") print("Error: Input must be an integer.") print("") if type(x) == int and x <= 0: print("") print("Error: Input must be greater than zero.") print("") return x #prompt for variables pv = get_float("What is the amount of the loan?\n(in dollars and cents, written as a decimal)\n") r = .01 * get_float("What is the interest rate of the loan?\n(written as a percentage, not a decimal)\n") n = get_int("What is the term of the loan?\n(in months, written as a whole number)\n") p = (r * pv)/(1 - math.pow((1 + r), -n)) print("Your monthly payment will be: $", str(round(p, 2))) input()
true
68da0dbea32e4f6c32de27a35e6123a1d31d5954
rosepcaldas/Cursoemvideo
/ex093.py
1,050
4.21875
4
''' EXERCÍCIO 93 - Cadastro de jogador de Futebol Crie um programa que gerencie o aproveitamento de um jogador de futebol. O programa vai ter o nome do jogador e quantas partidas ele jogou. Depois vai ler a quantidade de gol feitos em cada partida. No final, tudo isso será mostrado em um dicionário, incluindo o total de gols feitos durante o campeonato. ''' jogador = dict() partidas = list() jogador['nome'] = str(input('Nome do jogador: ')) tot = int(input(f'Quantidade de partidas{jogador["nome"]} jogou? ')) for i in range(0, tot): partidas.append(int(input(f' Quantos gols na partida {i+1}? '))) jogador['gols'] = partidas[:] jogador['total'] = sum(partidas) print('-='*30) print(jogador) print('-='*30) for i, v in jogador.items(): print(f'O campo {i} tem o valor {v}.') print('-='*30) print(f'O jogador {jogador["nome"]} jogou {len(jogador["gols"])} partidas.') for i, v in enumerate(jogador['gols']): print(f' => Na partida {i+1}, fez {v} gols.') print(f'Foi um total de {jogador["total"]} gols')
false
a1c2b6792248ad9514832e3033ba4b76d51cb4a0
rosepcaldas/Cursoemvideo
/ex75b.py
884
4.40625
4
''' EXERCÍCIO 75 - ANÁLISE DE DADOS EM TUPLAS 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 ''' tupla = (int(input('Digite um número: ')), int(input('Digite outro número: ')), int(input('Digite mas um número: ')), int(input('Digite o último número: '))) print(f'Voce digitou os valores {tupla}') print(f'O valor 9 apareceu {tupla.count(9)} vezes' if tupla.count(9) > 0 else 'O valor 9 apareceu 0 vezes') print(f'O valor 3 apareceu na {tupla.index(3)+1}ª posção' if tupla.count(3) > 0 else 'O valor 3 não foi digitado em nenhuma posição') print(f'Os valores pares digitados foram:', end=' ') for c in tupla: if c % 2 == 0: print(c, end=' ')
false
0eba0063aff68fe2628f26f36749564a123690db
jhj9109/TIL
/Class_On_SWEA/Class_104/codes/9강 자료형인자 변환 (1).py
464
4.375
4
# _*_ coding:utf-8 _*_ #자료형인자 변환하는 함수 data_str = "Hello" data_list = list(data_str) print("{0},{1},{2}".format(data_str,type(data_list),data_list)) data_tuple = tuple(data_list) print("{0},{1},{2}".format(data_str,type(data_tuple),data_tuple)) data_set = set(data_list) print("{0},{1},{2}".format(data_tuple, type(data_set),data_set)) data_dict = dict(enumerate(data_set)) print("{0},{1},{2}".format(data_set,type(data_dict),data_dict))
false
b4a2ec21b21c2a0ef4d5b49b94108cb16f9d221f
kalyanrohan/LEARNING-AND-TESTING
/DICTIONARIES.py
2,849
4.625
5
#my_func is to tell which number is greater def my_func(): num1=float(input("enter the first number: ")) num2=float(input("enter the second number: ")) num3=float((input("enter the third number: "))) if num1>=num2 and num1>=num3: return num1 elif num2 >=num1 and num2 >= num3: return num2 else: return num3 #function_2 is to tell whether the sum of 2 numbers are even/odd def function_2(): num1=float(input("enter the first number: ")) num2=float(input("enter the second number: ")) if (num1+num2)%2 ==0: return("even") else: return("odd") #how dictionary works, ditionary uses {} #essentially it uses keys to indetify certain values Months= {"Jan":"Januray", "Feb":"February", "Mar":"March", "Apr":"April", "May":"May", "Jun":"June", "Jul":"July", "Aug":"August", 'Sept':"September", "Oct":"October", "Nov":"November", "Dec":"December" } #to print all of the keys in the dcitionary for x in Months: print(x) #to print the values of the keys in the dictionary for x in Months: print(Months[x]) #another way to print the values of the keys in the dictionary for x in Months.values(): print(x) #If want to print both values and keys for x in Months.items(): print(x) # you can also check whether a key exist in a dictionary if "Jan" in Months: print("January is there") # to change the values in the dictionary Months["Jan"]="janice" print(Months["Jan"]) # to add new items to the dictionary Months["year"]=2020 # another way to print keys and their corresponding items for x,y in Months.items(): print(x,y) # to remove an item from the dictionary Months.pop("Feb") # to remove the last item in the dictionary Months.popitem() print(Months) # to copy a dicitionary months2= Months.copy() months3=dict(Months) # creating dictionaries in a dictionary Patients= { "Patient 1":{"Name":"Marcus","Age":21}, "Patient 2":{"Name":"Joan","Age":24}, "Patient 3":{"Name":"Gabriel","Age":20} } # To get the value of the value print(Patients.get("Patient 2").get("Age")) # Alternatively Patient_1={"Name":"Marcus","Age":21} Patient_2={"Name":"Joan","Age":24} Patient_3={"Name":"Gabriel","Age":20} Pateints={"Patient 1":Patient_1,"Patient 2":Patient_2,"Patient 3":Patient_3} print(Patients.get("Patient 2").get("Age")) #Alternate way to create dictionaries Colors=dict(light="Yellow",dark="Black",mixed="Green") print(Colors["light"]) #to update your dictionary Colors.update({"black":"grey"}) print(Colors) #to check whether a key exists. If key don't exist, can add it as a new key. Colors.setdefault("grey","ash grey") print(Colors) days=("mon","tues","wed","thurs","fri","sat","sun") days1=("monday","tuesday","wednesday","thursday","friday","saturday","sunday")
true
9e16c49e706fd272bfbaa412fc698b022c7276c3
erikedwards/madlibs
/libz.py
1,060
4.25
4
# mad libz # 10-05-2019 # # take me _(direction)_ # to the Paradise City # where the _(noun)_ is _(color)_ # and the _(plural nouns)_ are _(adjective what rhymes with "City")_ # oh won't you please take me home. oh woh woh oh fun = True while fun: direction = input("Enter a direction in which one could be taken\n") noun = input("Enter a singular noun\n") color = input("Enter a color\n") plural_noun = input("Enter a plural noun\n") adj_rhyme = input("Enter an adjective that rhymes with 'City', like maybe 'gritty' or 'shitty' or even 'witty'.\n") print("\n" "\n" "\n" "take me {}\n" "to the paradise city\n" "where the {} is {} \n" "and the {} are {}\n" "OH WON'T YOU PLEASE\n" " TAKE ME HOME... WOH-OH-OH-AH\n" "\n" "".format(direction, noun, color, plural_noun, adj_rhyme)) ans = input("again? (y/n)\n") if ans == "n": print("ok, important guy. Go fuck off with your important stuff then.") fun = False
false
bb69486317743b8aa75fcc8bb79893ca299a159c
katiamega/python_language
/students/km61/Mehedyuk_Kateryna/homework3.py
2,818
4.40625
4
# your co---'For loop with range'-------------------- #task1 """Given two integers A and B (A<= B). #Print all numbers from A to B inclusively.""" a=int(input()) b=int(input()) #int, because a, b==numbers for i in range(a,b+1): print(i) #task2 """Given two integers A and B. Print all numbers from A to B inclusively, in increasing order, if A < B, or in decreasing order, if A>= B""" a=int(input()) b=int(input()) #int, because a, b==numbers if a<=b: for i in range(a,b+1): print(i) else: for i in range(a,b-1,-1): print(i) #task3 """10 numbers are given in the input. Read them and print their sum. """ # Use as few variables as you can sum=0 for i in range(10): sum+=int(input()) print(sum) #task4 """N numbers are given in the input. Read them and print their sum.""" sum=0 n=int(input()) #int, because n==numbers for i in range(n): sum+=int(input()) print(sum) #task5 """For the given integer N calculate the following sum of cubes.""" sum=0 n=int(input()) #int, because n==numbers for i in range(n+1): sum+=i**3 print(sum) #task6 """In mathematics, the factorial of of an integer n, denoted by n! is the following product:n!=1*2*…*n""" # Don't use math module in this exercise n=int(input()) #int, because n==factorial sum=1 for i in range(n): sum*=i+1 print(sum) #task7 """Given N numbers: the first number in the input is N, after that N integers are given. Count the number of zeros among the given integers and print it.""" # need to count the number of numbers that are equals to zero, not the number of zero digits n=int(input()) #int, because n==numbers sum=0 for i in range(n): x=int(input()) if x==0: sum+=1 print(sum) #task8 """For given integer n compute the sum 1!+2!+3!+...+n!1!+2!+3!+...+n!.""" #This problem has a solution with only one cycle, so try to discover it. And don't use the math library :) n=int(input()) sum=0 for i in range(n): fact=1 for j in range(i+1): fact*=j+1 sum+=fact print(sum) #task9 """There was a set of cards with numbers from 1 to N. One of the card is now lost. Determine the number on that lost card given the numbers for the remaining cards.""" #Given a number N, then N − 1 integers - numbers on remaining cards (distinct integer in range from 1 to N). Your program should print a number on the lost card n=int(input()) summ=0 needed_sum=0 for i in range(n-1): summ+=int(input()) needed_sum+=i+1 needed_sum+=n print(needed_sum-summ) #task10 """For given integer n ? 9 print a ladder of n steps. The k-th step consists of the integers from 1 to i without spaces between them.""" #To do that, you can use the sep and end arguments for the function print(). n=int(input()) for i in range(n): for j in range(i+1): print(j+1,end='') print() de goes here
true
1b707476cf42d351c5d4ffca2e6b1433bcf405ef
twumm/Algorithms
/eating_cookies/eating_cookies.py
1,131
4.21875
4
#!/usr/bin/python import sys # The cache parameter is here for if you want to implement # a solution that is more efficient than the naive # recursive solution def eating_cookies(n, cache=None): # set a list to contain the list of possible combinations if n < 0: return 0 elif n == 0: return 1 else: return eating_cookies(n - 1) + eating_cookies(n - 2) + eating_cookies(n - 3) # pass # print(eating_cookies(20)) # Python program to display the Fibonacci sequence # def recur_fibo(n): # if n <= 1: # return n # else: # return(recur_fibo(n-1) + recur_fibo(n-2)) # nterms = 10 # # check if the number of terms is valid # if nterms <= 0: # print("Plese enter a positive integer") # else: # print("Fibonacci sequence:") # for i in range(nterms): # print(recur_fibo(i)) if __name__ == "__main__": if len(sys.argv) > 1: num_cookies = int(sys.argv[1]) print("There are {ways} ways for Cookie Monster to eat {n} cookies.".format(ways=eating_cookies(num_cookies), n=num_cookies)) else: print('Usage: eating_cookies.py [num_cookies]')
true
9210082e389d8a1219d8f0e4aa689c88523ee285
artem9/CyberBionic
/home03/exersise03.py
2,304
4.1875
4
import datetime MINIMAL_YEAR = 2005 class Employee: def __init__(self, first_name='', last_name='', job_title='', year_of_registration=0): if not first_name: raise ValueError('First name is required!') if not last_name: raise ValueError('Last name is required!') if not job_title: raise ValueError('Job Title is required!') self.first_name = first_name self.last_name = last_name self.job_title = job_title if not year_of_registration: year_of_registration = datetime.date.today().year self.year_of_registration = year_of_registration def __str__(self): return 'Employee: {first_name!s}, {last_name!s}, {job_title!s}, ' \ '{year_of_registration!s}'.format_map(self.__dict__) @staticmethod def read_employee(): first_name = input('Please enter First name: ') last_name = input('Please enter Last name: ') job_title = input('Please enter Job title: ') hired_date = read_year('Please enter Hired date (or leave blank for current year): ') return Employee(first_name, last_name, job_title, hired_date) def check_valid_year(year): return MINIMAL_YEAR <= year <= datetime.date.today().year def safe_input(description, my_function=None): while True: try: input_value = int(input(description)) if my_function and not my_function(input_value): raise ValueError('Incorrect value') except ValueError as error: print('Error: ', error) else: return input_value def read_year(message): return safe_input(message, check_valid_year) def main(): number_of_people = safe_input('How many people do you want to add: ') employees = [] while len(employees) < number_of_people: try: employee = Employee.read_employee() except ValueError as error: print('Error: ', error) else: employees.append(employee) finally: print() year = read_year('Please enter year of registration: ') for person in employees: if person.year_of_registration >= year: print(person) if __name__ == '__main__': main()
false
e20f500c4d34b202e0c4a45bf6706c2c61b24613
ladnayan/Betahub-application
/sign_in.py
1,430
4.1875
4
import os def sign_in(d): """function for sign in by checking hash value stored in dictionary""" for i in range(3): print("Enter your user name:") name=input() l=d.keys() #change made if name not in l: os.system('clear') print("""User name not found. Enter registered user name """) else: #add except statement count=1 while True: print("Enter your password:") password=hash(input()) #encode_check=hashlib.sha256(b'password') if d[name][1]==password: os.system('clear') return(name) break else: if count==3: os.system('clear') print("Max password attempts reached") return(0) break else: # os.system('clear') print("Incorrect password") count=count+1
true
e8a1e67a7c17d7e4dad646f86cb8ede1089c9be0
kyle5358/Python-Code
/Standard/use_argparse.py
626
4.15625
4
'''argparse --- 命令行选项、参数和子命令解析器 argparse 模块可以让人轻松编写用户友好的命令行接口。 程序定义它需要的参数,然后 argparse 将弄清如何从 sys.argv 解析出那些参数。 argparse 模块还会自动生成帮助和使用手册,并在用户给程序传入无效参数时报出错误信息。 ''' import argparse parser = argparse.ArgumentParser() # 创建对象 # 添加参数 parser.add_argument("square", help="display a square of a given number", type=int) args = parser.parse_args() # 解析添加的参数 print(args.square**2)
false
1dfcf7366a1d039dd6b3a734faaee4c4115c18f4
soujanyaKonduru/learnprog
/InputListFuntionForPython.py
706
4.375
4
# input name = input('please enter your name:') # print with formatting # you can use 'f' (formatting) with print like below name = "sai" print(f'Hello {name} welcome') # with f in print function the variables in { and } will be replaced with its values # list # list is used to hold a variable with multiple values. hobbies = ['play', 'music', 'running'] # for # we can use for loop to do repetive tasks and also looping over the lists for hobby in hobbies: print(f'my hobby is {hobby}') # also for looping over given numbers we can use range function like below for x in range(1,10,1): print(x) # range function will have start, end and increment. In above start=1, end=10 and increment=1
true
854cfb58af8bb3a16ebe40ec87e5aca11af76f71
Object-Oriented101/LearningProgrammingFundamentals
/LearningPython/test.py
263
4.125
4
import tkinter as tk from tkinter import ttk # Create the application window window = tk.Tk() # Create the user interface my_label = ttk.Label(window, text="Hello World!") my_label.grid(row=1, column=1) # Start the GUI event loop window.mainloop()
true
1425cdeb87bee46d628961da883c8baa79316a8a
richardx14/pythonBeginners
/usernames.py
304
4.1875
4
usernames = {} while True: print(usernames) print("Enter username:") username = input() if username in usernames.keys(): print(username + " is the username of " + usernames[username]) else: print("Enter name:") name = input() usernames[username] = name print(usernames[username])
true
060c65fe1cc4496e24976a9cc53e52a79970f5f8
gloria-ho/algorithms
/python/convert_string_to_camel_case.py
707
4.40625
4
# https://www.codewars.com/kata/convert-string-to-camel-case # Complete the method/function so that it converts dash/underscore delimited words into camel casing. The first word within the output should be capitalized only if the original word was capitalized. # Examples # to_camel_case("the-stealth-warrior") # returns "theStealthWarrior" # to_camel_case("The_Stealth_Warrior") # returns "TheStealthWarrior" import re def to_camel_case(text): arr = re.split('[- _]', text) result = [arr[0]] for x in arr[1:]: result.append(x.title()) return ''.join(result) print(to_camel_case("the-stealth-warrior")) # "theStealthWarrior" print(to_camel_case("The_Stealth_Warrior")) # "TheStealthWarrior"
true
cfecd7c33bffda13c24f9d5248380e7c2c0041d4
gloria-ho/algorithms
/python/remove_the_minimum.py
1,117
4.125
4
# https://www.codewars.com/kata/563cf89eb4747c5fb100001b # The museum of incredible dull things wants to get rid of some exhibitions. Miriam, the interior architect, comes up with a plan to remove the most boring exhibitions. She gives them a rating, and then removes the one with the lowest rating. # However, just as she finished rating all exhibitions, she's off to an important fair, so she asks you to write a program that tells her the ratings of the items after one removed the lowest one. Fair enough. # Task # Given an array of integers, remove the smallest value. Do not mutate the original array/list. If there are multiple elements with the same value, remove the one with a lower index. If you get an empty array/list, return an empty array/list. # Don't change the order of the elements that are left. # Examples # removeSmallest([1,2,3,4,5]) = [2,3,4,5] # removeSmallest([5,3,2,1,4]) = [5,3,2,4] # removeSmallest([2,2,1,2,1]) = [2,2,2,1] def remove_smallest(numbers): if len(numbers) == 0: return numbers new_numbers = numbers new_numbers.remove(sorted(numbers)[0]) return new_numbers
true
c28fa1f661a241ac347bff80edd8f12aa077eda0
gloria-ho/algorithms
/python/find_the_unique_number.py
757
4.21875
4
# https://www.codewars.com/kata/find-the-unique-number-1 # There is an array with some numbers. All numbers are equal except for one. Try to find it! # findUniq([ 1, 1, 1, 2, 1, 1 ]) === 2 # findUniq([ 0, 0, 0.55, 0, 0 ]) === 0.55 # Its guaranteed that array contains more than 3 numbers. # The tests contain some very huge arrays, so think about performance. # This is the first kata in series: # Find the unique number (this kata) # Find the unique string # Find The Unique from collections import Counter def find_uniq(arr): counter = Counter(arr) for n in counter: if counter[n] == 1: return n # return n for n in counter if counter[n] == 1 print(find_uniq([ 1, 1, 1, 2, 1, 1 ])) # 2 print(find_uniq([ 0, 0, 0.55, 0, 0 ])) # 0.55
true
6ca4a40be9de8736614265926feade3f6280782a
ChrisCodesNow/wb
/01_basics/01_arrays/02_transpose.py
704
4.1875
4
''' Approach 1: Create matrix T with m rows. Fill T from A's old col to T's new row Runtime: O(nm) Space Complexity: O(nm) ''' # Asume input matrix is a 2D from typing import List class Solution: def transpose(self, A: List[List[int]]) -> List[List[int]]: T = [ [] for _ in range(len(A[0])) ] for row in A: for j,ele in enumerate(row): T[j].append(ele) return T # Test if __name__ == '__main__': s = Solution() A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print(s.transpose(A)) A = [[1,2,3],[4,5,6]] print(s.transpose(A)) # Error: Method expects 2D matrix # A = [1, 2, 3, 4] # print(s.transpose(A))
true