blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
16a137e575032e1435d56629409f9b01d6d665c7
kshitijvr93/Django-Work-Library
/modules/sqlalchemy_tools/core/try_alchemy.py
1,519
4.28125
4
''' Basic demo python3 code to use SqlAlchemy (SA) to create a table in a database. ''' import os import sys import sqlalchemy from sqlalchemy import ( Column, ForeignKey, Integer,create_engine, String, Table, MetaData, ForeignKey, Sequence,) print("Sqlalechemy version='{}'".format(sqlalchemy.__version__)) engine = create_engine('sqlite:///:memory:', echo=True) metadata = MetaData() users = Table('users', metadata, Column('id', Integer, Sequence('user_id_seq'), primary_key=True), Column('name', String(100)), Column('fullname', String(100)), Column('password', String(100)), ) ''' print(Table('users', metadata, Column('id', Integer, Sequence('user_id_seq'), primary_key=True), Column('name', String(100)), Column('fullname', String(100)), Column('password', String(100)), ).compile(bind=create_engine('sqlite://')) ) ''' addresses = Table('addresses', metadata, Column('id', Integer, Sequence('user_id_seq'), primary_key=True), Column('user_id', None, ForeignKey('users.id')), Column('email_address', String(100), nullable=False), ) metadata.create_all(engine) # NOTE: add your engine here, or create a python module # like sa.py to capture your personal creds for # your personal engines of interest. print("======================================") print(users.c.name + users.c.fullname) for e in ['mysql://','sqlite:///:memory:']: print("{}:{}".format(e,(users.c.name + users.c.fullname) .compile(bind=create_engine(e)))) metadata.create_all(engine)
false
2ed66b56971d82556312f1a1ab8139cb62d5378c
nkat66/python-1-work
/noble_kaleb_tipcalculatorapp.py
996
4.34375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Feb 25 19:00:12 2019 Kaleb Noble 2/27/2019 Python 1 - DAT-119 - Spring 2019 Tip Calculator Assignment This program takes an input of a meal bill, then calculates and presents the user with the 10%, 15%, and 20% tip values. @author: katnob8 """ #Set all three tip values for clarity when calculating. tip10 = float(.10) tip15 = float(.15) tip20 = float(.20) #Introduces the app. print("Hi there! Welcome to the Tip Calculator App 1.0!") #Requests that the user inputs the meal bill. meal_bill = float(input("To start, please provide me with your total bill: ")) #Calculate the 10%, 15%, and 20% tip. tip_value_10 = meal_bill * tip10 tip_value_15 = meal_bill * tip15 tip_value_20 = meal_bill * tip20 #Presents the total $ of the tip. print("Okay! Here's what the tip values are: ") print("10%: ", format(tip_value_10, ".2f")) print("15%: ", format(tip_value_15, ".2f")) print("20%: ", format(tip_value_20, ".2f"))
true
7b9f94392c28ae061f682df6ae65e2d4d3bbfcec
gwccu/day2-rachelferrer
/day3.py
283
4.21875
4
# my code prints my name, then stores it as a variable which I can then add things to such as my last name and repeating it multiple times print("Rachel") myName = "Rachel" print(myName) print(myName + "Ferrer") print(myName*78) print("What comes first the 'chicken' or the 'egg'?")
true
0647977b57c82a9ed439437957b7bafd13c0f406
kumarsourav1499/Miniproject-Python-
/mini_project.py
432
4.21875
4
first = int(input("enter first number : ")) operator = input("enter operator (+,-,*,/,%) : ") second = int(input("enter second number : ")) if operator == "+": print(first + second) elif operator == "-": print(first - second) elif operator == "*": print(first * second) elif operator == "/": print(first / second) elif operator == "%": print(first % second) else: print("Invalid Operation")
false
fa61cb6964caf46d16e3c390a51921bd0371d2f2
mRse7enNIT/Guess_The_Number_Python
/main.py
1,975
4.21875
4
# input will come from buttons and an input field # all output for the game will be printed in the console import simplegui import math import random range = 100 no_of_guess = 0 secret_number = 0 # helper function to start and restart the game def new_game(): # initialize global variables used in your code here global secret_number global range global no_of_guess print "\nNew game. Range is from 0 to " ,range if range == 100: no_of_guess = 7 elif range ==1000: no_of_guess = 10 print "Number of remaining guesses is " ,no_of_guess secret_number = random.randrange(0, range) # define event handlers for control panel def range100(): # button that changes the range to [0,100) and starts a new game global range range = 100 new_game() def range1000(): # button that changes the range to [0,1000) and starts a new game global range range = 1000 new_game() def input_guess(guess): # main game logic goes here print "\nGuess was ", guess global no_of_guess no_of_guess = no_of_guess - 1 if no_of_guess >=0: if int(guess) > secret_number : print "Lower!" print 'Number of remaining guesses is' ,no_of_guess elif int(guess) < secret_number : print "Higher!" print 'Number of remaining guesses is' ,no_of_guess elif int(guess) == secret_number : print "Correct!" new_game() else: print "Out of guesses" new_game() # create frame f = simplegui.create_frame("guess the number",200,200) # register event handlers for control elements and start frame f.add_button("Range is [0,100)", range100,100) f.add_button("Range is [0,1000)", range1000,100) f.add_input('Enter a guess', input_guess, 200) f.start() # call new_game new_game() # always remember to check your completed program against the grading rubric
true
49df8291b778d88203f849ee8fc7e39b37fede67
inwk6312winter2019/week4labsubmissions-praneethm45
/lab5T3.py
305
4.1875
4
class Time: """this class represents time""" """def print_time(self,t): print('the time is:','%.2d:%.2d:%.2d'%(t.hour,t.minute,t.second))""" time=Time() time.hour=9 time.minute=35 time.second=25 def print_time(t): print('the time is:','%.2d:%.2d:%.2d'%(t.hour,t.minute,t.second)) print_time(time)
false
08f8c4c315469294ebfedf93a8338cd3c6c368e5
qdaniel4/project3Finished
/validation.py
1,223
4.28125
4
def topic_validation(user_input): while user_input.isnumeric() is False or int(user_input) <= 0 or int(user_input) > 3: print('Please enter a whole number between 1 & 3:') user_input = input() user_input = int(user_input) if user_input == 1: topic = 'Sports' return topic elif user_input == 2: topic = 'Geography' return topic else: topic = 'Food&Drink' return topic def answer_validation(answer): while answer.isnumeric() is False or int(answer) <= 0 or int(answer) > 4: print('Please enter a whole number between 1 & 4: ') answer = input() answer = int(answer) return answer def question_num_validation(question_input): while question_input.isnumeric() is False or int(question_input) <= 0 or int(question_input) > 2: print('Please enter a whole number between 1 & 2:') question_input = input() question_input = int(question_input) if question_input == 1: q_num = 5 return q_num else: q_num = 3 return q_num def name_validation(name): while name == '': print('This field cannot be blank: ') name = input() return name
true
db0e1096127e695e22eb59543b0329f8bbdad662
isi-frischmann/python
/exercise.py
1,611
4.28125
4
# 1. # SET greeting AS 'hello' # SET name AS 'dojo' # LOG name + greeting greeting = 'hello' name = 'dojo' print greeting +" "+ name # 2. # Given an array of words: ['Wish', 'Mop', 'Bleet', 'March', 'Jerk'] # Loop through the array # Print each word to consol array = ['Wish', 'Mop', 'Bleet', 'March', 'Jerk'] for i in range(0, len(array)): print array[i] # 3. # Write a function that takes a number. # Create an empty list. # Multiply that number by 2. # Push the new number to our empty list. # Repeat 25 times. # Print list. def function(value): lst = [] value *= 2 for i in range(0, 25): lst.append(value) print lst function(5) # 4. # Define a small program that accepts strings as inputs # Have your program create a blank string. # Starting at the back of the input string and walking backwards: 3a. Push each character into the blank string. 3b. #Repeat for all characters in input string. # Print the reversed string. x = 'hello' def strings(str): newString = "" for i in range(len(str)-1,-1,-1): newString += x[i] # print x[i] print newString strings(x) # 5. x = 10 # x EQUALS 10 x = x * 7 # x EQUALS x TIMES 7 y = 30 # y EQUALS 30 z = y + x # z EQUALS y PLUS x z = z * 3 # z EQUALS z TIMES 3 z = z - y # z EQUALS z MINUS y z = z / 27 # z EQUALS z DIVIDED_BY 27 x = z + y # x EQUALS z PLUS y y = 3 # y EQUALS 3 x = x + y # x EQUALS x PLUS y # RETURN TRUE if x MODULUS 10 EQUALS 0 # OTHERWISE RETURN FALSE def hello(x): if (x % 10 == 0): print "true" else: print "false" hello(10)
true
6b7d0b73e2881d111d33dd98118593847032d83f
isi-frischmann/python
/multiplication_table.py
579
4.125
4
''' pseudocode: -create two lists from 0 - 12 (listHorizontal and listVertical) - create a for loop which goes through each index of listVertical -create a for loop in the for loop which goes through each index in listHorizontal -and multiplies it with index 0 from listVertical ''' #first row (horizontal) is wrong. There needs to be numbers and no x listVertical = [1,2,3,4,5,6,7,8,9,10,11,12] listHorizontal = [1,2,3,4,5,6,7,8,9,10,11,12] for i in listVertical: newLine = '' for a in listHorizontal: newLine += str(i * a) + ' ' print 'x', newLine
true
621db9104577cb2de94faa182aaae81ec2d7a855
gpereira-blueedtech/BlueTurma2B-mod1
/Aula08/Aula08_revisao_funcoes.py
1,454
4.46875
4
# Criando as funções: # "Ensinando" ao programa o que ele deve fazer quando a função for chamada # Importante lembrar que nesse momento a função não é executada, apenas criada! # Para executar, eu preciso chamar a função pelo nome dela no programa def testa_idade(idade=18): print(idade) if idade >= 18: print("Maior de idade\n") else: print("Menor de idade\n") def soma_tudo_do_sangue(hema, plaq, leuco): sangue_total = hema + plaq + leuco print("O sangue total é: ", sangue_total) return sangue_total sangue = soma_tudo_do_sangue(10, 5, 30) #Armazena na var sangue o que foi retornado pela função chamada #print("O sangue total é:", sangue) #print(soma_tudo_do_sangue(8, 8, 8)) # Printa o retorno da função #soma_tudo_do_sangue(7, 7, 7) # Apenas executa a função. print(" SEMANA 1:\n") sangue = soma_tudo_do_sangue(10, 5, 30) if sangue > 300: print("Cuidado, você vai morrer\n\n") else: print("Toma cuidado mesmo assim.\n\n") print(" SEMANA 2:\n") sangue = soma_tudo_do_sangue(180, 200, 2) if sangue > 300: print("Cuidado, você vai morrer\n") else: print("Toma cuidado mesmo assim.\n") print(" SEMANA 3:\n") h = int(input("Digite valor H: ")) p = int(input("Digite valor P: ")) l = int(input("Digite valor L: ")) sangue = soma_tudo_do_sangue(h, p, l) if sangue > 300: print("Cuidado, você vai morrer\n") else: print("Toma cuidado mesmo assim.\n")
false
e302581c0b1983a2f8f02cdde2372ab78899d151
qimo00/timo
/def1_huiwen.py
348
4.21875
4
def Palindrome(str_in): len_s=len(str_in) i=0 flag=1 while i<len_s/2: if str_in[i]==str_in[len_s-1-i]: i+=1 else: flag=0 break if flag==1: print("it is a Palindrome") else: print("it is not a Palindrome") string=input("input a string:") Palindrome(string)
false
aa1bdb2b6f2dfc31f467de5d05807bbd3a3ac8c9
sirinsu/GlobalAIHubPythonHomework
/project.py
2,657
4.1875
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: """Student Management System""" def calculateFinalGrade(grades):#takes a dictionary including midterm, final and project grades then returns the final grade after some calculations. midterm = int(grades.get('midterm')) final = int(grades.get('final')) project = int(grades.get('project')) final_grade = (midterm * 30 / 100) + (final * 50 / 100) + (project * 20 / 100) return final_grade def determinePassingGrade(grade): pass_grade = "" if grade >= 90: pass_grade = "AA" elif grade <90 and grade >=70: pass_grade = "BB" elif grade < 70 and grade >= 50: pass_grade = "CC" elif grade <50 and grade >= 30: pass_grade = "DD" else: pass_grade = "FF" return pass_grade def studentManagementSystem(): from random import randrange attempts = 3 while attempts > 0: name = input("Please enter your name..") surname = input("Please enter your surname..") if name == "" or surname == "": print("Incorrect name or surname. Please enter both your name and surname correctly.") attempts = attempts - 1 else: break if attempts == 0: print("Please try again later.") return lessons = [] for i in range(1,6): lesson = input("Please write the name of the course you want to take or write q to continiue.") if lesson == 'q': if len(lessons) < 3: return('You failed in class') else: break else: lessons.append(lesson) i = 1 print() print("----- Lessons You Took -----") for lesson in lessons: print(f"Lesson {i} - {lesson}") i = i + 1 while True: try: chosen_lesson = int(input(f"Please choose a lesson number to take exams.(1 - {len(lessons)})")) if chosen_lesson < 1 or chosen_lesson > len(lessons): print("Please choose a correct lesson number.") else: break except: print("Please choose a correct lesson number.") lesson = lessons[chosen_lesson - 1] #print(lesson) midterm = randrange(101) final = randrange(101) project = randrange(101) grades = {"midterm": midterm, 'final':final, 'project':project} final_grade = calculateFinalGrade(grades) note = determinePassingGrade(final_grade) if note == "FF": pass else: print(f"NOTE: {note}") studentManagementSystem() # In[ ]:
true
d9eae7edf62fa1c37699ee15d4a7b7a63c065bf9
hemanth9516/pythonlab
/function1.py
320
4.15625
4
def func(num1,num2,num3): if (num1 >= num2) and (num1 >= num3): return num1 elif (num2 >= num1) and (num2 >= num3): return num2 else: return num3 a= float(input("Enter first number: ")) b= float(input("Enter second number: ")) c= float(input("Enter third number: ")) largest=func(a,b,c) print(largest)
false
8ba1f5a63053442a3d804fff31c0af7554fb8d1d
GuillemGodayol/Ironhack_Data_Labs
/Week_3/lab-code-simplicity-efficiency/your-code/challenge-3.py
1,120
4.625
5
""" You are presented with an integer number larger than 5. Your goal is to identify the longest side possible in a right triangle whose sides are not longer than the number you are given. For example, if you are given the number 15, there are 3 possibilities to compose right triangles: 1. [3, 4, 5] 2. [6, 8, 10] 3. [5, 12, 13] The following function shows one way to solve the problem but the code is not ideal or efficient. Refactor the code based on what you have learned about code simplicity and efficiency. """ import numpy as np def my_function(X): solutions = [] # Using list comprehension to reduce the for loops into a 1 statement. solutions = [[a, b, c] for a in range(5,X) for b in range(4, X) for c in range(3,X) if (a*a == b*b+c*c)] # Using numpy method 'max' to find the max from a list of lists. return np.max(solutions) # Although it is not Error Handling, I added more text to ask for a number bigger than 5. X = input("What is the maximal length of the triangle side? Enter a number equal or bigger than 5: ") print("The longest side possible is " + str(my_function(int(X))))
true
7dcb240d949c5299263b562fbb1bb3a76943e44b
Matt-GitHub/Sprint-Challenge--Data-Structures-Python
/reverse/reverse.py
2,019
4.21875
4
class Node: def __init__(self, value=None, next_node=None): self.value = value self.next_node = next_node def get_value(self): return self.value def get_next(self): return self.next_node def set_next(self, new_next): self.next_node = new_next class LinkedList: def __init__(self): self.head = None def add_to_head(self, value): node = Node(value) if self.head is not None: node.set_next(self.head) self.head = node def contains(self, value): if not self.head: return False current = self.head while current: if current.get_value() == value: return True current = current.get_next() return False def reverse_list(self, node, prev): # the value of the current node is our first param # the value of the previous node is our second param # we need to do this recurisevly if node is None: return None # ** if we are at the tail of our list --> set the tail to equal our new head # ** set the next node of the new head to equal the previous value if node.next_node is None: self.head = node node.next_node = prev else: # ** if we are not at the tail --> the node we pass into reverse list next_node = node.next_node node.next_node = prev self.reverse_list(next_node, node) """ Inside of the `reverse` directory, you'll find a basic implementation of a Singly Linked List. _Without_ making it a Doubly Linked List (adding a tail attribute), complete the `reverse_list()` function within `reverse/reverse.py` reverse the contents of the list using recursion, *not a loop.* For example, ``` 1->2->3->None ``` would become... ``` 3->2->1->None ``` While credit will be given for a functional solution, only optimal solutions will earn a ***3*** on this task."""
true
919fc9a46afa10b97448ff531296f4d33966717e
raresteak/py
/collatz.py
1,203
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # def collatz(checkNum): if checkNum % 2 == 0: newNum = checkNum // 2 #print('Entered EVEN branch, value is now: ' + str(newNum) ) return newNum else: newNum = 3 * checkNum +1 #print('Entered ODD branch, value is now: ' + str(newNum) ) return newNum def numLoops(Looper): Looper = Looper + 1 return Looper def main(args): myCnts = 0 print('Collatz Conjecture - Enter a number: ') print('Hint, use 9780657630 produces the largest number of Collatz steps') myNum = int(input()) # add check for negative and strings and throw error while myNum != 1: myCnts = numLoops(myCnts) myNum = collatz(myNum) print('Result: '+ str(myNum)) print('collatz steps: ' + str(myCnts)) # The longest progression for any initial starting number less than 100 million is # 63,728,127, which has 949 steps. # For starting numbers less than 1 billion it is 670,617,279, with 986 steps, and for # numbers less than 10 billion it is 9,780,657,630, with 1132 steps # source: http://en.wikipedia.org/wiki/Collatz_conjecture if __name__ == '__main__': import sys sys.exit(main(sys.argv))
true
6f7eb3a41ec46526088ff54b4eff82c032c09a30
rasna-skumar1306/mini_problems
/age_detect.py
473
4.125
4
from datetime import datetime as date def detect(): if (dy-int(yyyy)) >= 18: if int(mm) < dm: print("you are eligible to vote") elif int(mm) == dm: if int(dd) <= da: print("you may proceed to vote") print("you may proceed to vote") else: print("you are not allowed to vote") da = date.now().day dm = date.now().month dy = date.now().year print("enter your dob with \'-\' as separation") dd,mm,yyyy = input("enter your DOB").split("-") detect()
false
ab26864a12aa195190b3d3b24d29b1d97f17eb1a
Kratharth/1BM17CS035
/string experiments/reverse.py
242
4.125
4
def reverse(s): l=s.split() l=l[::-1] for word in l: print(word,end=" ") print('\n') l=l[::-1] for i in range(len(l)): l[i] = l[i][::-1] for word in l: print(word, end=" ") print('\n') st = input('enter a string :') reverse(st)
false
17edae88160faec456d5c69ca2b7ac0f05cd3b1e
linkdesu/python-lessons
/lesson5/range.py
503
4.3125
4
# -*- coding: utf-8 -*- """ range """ # ==== 基础 ==== print(range(10)) # range(start, stop) c = list(range(1, 11)) print("c: ", c) # range(start, stop[, step]) d = list(range(1, 11, 2)) print("d: ", d) e = list(range(0, -10, -1)) print("e: ", e) # ==== 深入 ==== # range 函数返回的是一个可遍历的 Range 对象。 a = range(10) print("a: ", a) # 使用 list 函数可以将 Range 对象转为 List 对象,不过并没有这样的必要。 b = list(range(10)) print("b: ", b)
false
5ac87e9ccf3322d89904858defb1134deded6633
linkdesu/python-lessons
/lesson4/if_else.py
766
4.34375
4
# -*- coding: utf-8 -*- """ if """ # 当条件为真,执行 if 代码块的代码。 if True: print('This code will be execute.') else: print('This code will not be execute.') if True or False: print('This code will be execute.') else: print('This code will not be execute.') if 1 <= 2: print('This code will be execute.') else: print('This code will not be execute.') # 当条件为假,不执行 if 代码块的代码。 if False: print('This code will not be execute.') else: print('This code will be execute.') if 2 > 2: print('This code will not be execute.') else: print('This code will be execute.') if 10 % 3 == 0: print('This code will not be execute.') else: print('This code will be execute.')
false
9536c136bf37e24b80ad48d59e667010b8b20cdc
beowlf/exercicio-python
/Modifique o programa anterior para imprimir de 1 ate o numero digitado pelo usuario mas dessa vez apensas o numeros impares.py
235
4.21875
4
''' Modifique o programa anterior para imprimir de 1 ate o numero digitado pelo usuario mas dessa vez apensas o numeros impares ''' fim = int(input("Digite um numero: ")) x = 1 while x <= fim == 1: print (x) x = x + 1
false
8f0b416ef147905aa8de95a096079e793270370f
ssciere/100-days-of-python
/days_ago.py
530
4.25
4
"""promblem solved for the Talk Python course https://github.com/talkpython/100daysofcode-with-python-course""" import datetime from datetime import date, timedelta print("This program allows you to enter a date to find out how many days ago it occurred") day = int(input("Enter the day: ")) month = int(input("Enter the month: ")) year = int(input("Enter the year: ")) date_entered = date(year, month, day) now = date.today() days = (now - date_entered).days print("The date",date_entered, "was", days, "ago.")
true
e59230a3886cb74b298041992eabf99d2247bd94
gaylonalfano/blockchain-cryptocurrency
/loops_conditionals_assignment.py
1,003
4.34375
4
# My attempt: # 1) Create a list of names and use a for loop to output the length of each name (len() ). names = ['Robert', 'Archie', 'Rudolph', 'Cloud', 'Raistlin', 'Miller', 'Fitz', 'Falco', 'Jon'] # for name in names: # print(len(name)) # 2) Add an if check inside the loop to only output names longer than 5 characters. # for name in names: # if len(name) > 5: # print(name) # 3) Add another if check to see whether a name includes a “n” or “N” character. # If it does have an "n" or "N", then print the len(name) for name in names: if len(name) > 5 and ("n" or "N") in name: print(f"{name} -- {len(name)}") # 4) Use a while loop to empty the list of names (via pop() ) while len(names) > 0: print(f"Popping: {names.pop()}!") else: print(names) # Instructor's for name in names: if len(name) > 5 and ('n' in name or 'N' in name): print(name) print(len(name)) while len(names) >= 1: names.pop() print(names)
true
43d613bf1f83f8951017fd296bebfe5b0e094360
samuelleonellucas/Aulas-impacta
/AULAEX25.py
1,370
4.1875
4
''' num = float(input(" ")) if 1 <= num and num <= 100: print("dentro do intervalo") num = float(input(" ")) if 30 < num and num <70: print("dentro do intervalo") else: print ("fora do intervalo") ''' ''' num1 = int(input( )) num2 = int(input( )) num3 = int(input( )) if num1 < num2 < num3: print(num1, "num1") elif num2 > num1 <num3: print (num2, "num2") else: print(num3, "num3") ''' ''' a = int(input("a ")) b = int(input("b ")) c = int(input("c ")) if a < b and a < c : print(a, "a") if b < c: print(b, "b") print(c, "c") else: print (c, "c") print (b, "b") elif b < a and b < c: print(b, "b") if a < c: print (a, "a") print (c, "c") else: print (c, "c") print (a, "a") if a < b: print (b, "b") print (a, "a") ''' '''' soma = 0 while True: num1 = int(input(' ')) soma = soma + num1 if num1 == 0: break print (soma) ' '' num1 = int(input()) soma = 0 while num1 != 0: soma = soma + num1 num1 = int(input(' ')) print (soma) ''' ''' while True: sal = int(input('quantidade')) if sal > 0: break else: print ('Quantidade inválida') soma = 0 for cont in range (sal): salario = float(input('salario')) soma += sal print (soma ) '''
false
00fe8b198e8cf153a2ada8b8236033e9f801856b
mradoychovski/Python
/PAYING OFF CREDIT CARD DEBT/bisection_search.py
863
4.25
4
# Uses bisection search to find the fixed minimum monthly payment needed # to finish paying off credit card debt within a year balance = float(raw_input("Enter the outstanding balance on your credit card: ")) annualInterestRate = float(raw_input("Enter the annual credit card interest rate as a decimal: ")) monthlyInteretRate = annualInterestRate/12.0 high =(balance * (1 + monthlyInteretRate)**12)/12 total = 0 tempBalance = balance while tempBalance > 0: month = 0 while month < 12: interest = (tempBalance - high) * monthlyInteretRate tempBalance = (tempBalance - high) + interest total += high finalbalance = tempBalance - total month += 1 if tempBalance < -0.01 or tempBalance > 0.01: high += tempBalance / 12.0 tempBalance = balance else: break total=0 print('Lowest Payment: %.2f' % high)
true
726f473731b428a8e9cb2268c125088f15f410bd
skeapskeap/learn-homework-1
/1_if1.py
1,214
4.15625
4
""" Домашнее задание №1 Условный оператор: Возраст * Попросить пользователя ввести возраст при помощи input и положить результат в переменную * Написать функцию, которая по возрасту определит, чем должен заниматься пользователь: учиться в детском саду, школе, ВУЗе или работать * Вызвать функцию, передав ей возраст пользователя и положить результат работы функции в переменную * Вывести содержимое переменной на экран """ age = int(input('Каков Ваш возраст?\n')) def main(age): if age < 0 or age > 100: occupation = 'Вы врёте' elif age < 7 : occupation = 'В детсокм саду' elif age < 17 : occupation = 'В школе' elif age < 21 : occupation = 'В ВУЗе' else : occupation = 'Работает' return occupation if __name__ == "__main__": main(age) print (main(age))
false
fa01852f7695ac8e0530932e47a49641d4f99e8a
fekisa/python
/lesson_3/homework_3_4.py
1,001
4.28125
4
''' 4. Программа принимает действительное положительное число x и целое отрицательное число y. Необходимо выполнить возведение числа x в степень y. Задание необходимо реализовать в виде функции my_func(x, y). При решении задания необходимо обойтись без встроенной функции возведения числа в степень. ''' def my_func(x,y): if x < 0 or y > 0: print("Данные не соответствуют условиям. x - действительное положительное число, y - целое отрицательно число") elif x == 0 or y == 0: print("Тут не понятно, кто прав") else: print(x**y) my_func(int(input("Введите x: ")), int(input("Введите y: ")))
false
52a2b99fac1e18fd1579af864e8443a001bae6de
kgashok/algorithms
/leetcode/algorithms/spiral-matrix/solution.py
1,391
4.21875
4
#!/usr/bin/env python class Solution(object): def spiralOrder(self, matrix): """ Returns the clockwise spiral order traversal of the matrix starting at (0, 0). Modifies the matrix to contain all None values. :type matrix: List[List[int]] :rtype: List[int] """ if len(matrix) == 0 or len(matrix[0]) == 0: return [] # Size of the matrix. n = len(matrix) m = len(matrix[0]) # Current row and column that we are on. r = 0 c = 0 # The delta values to get the next row and column. dr = 0 dc = 1 # The resulting spiral order and next insertion index. spiral = [0] * (n * m) i = 0 for i in range(0, n * m): spiral[i] = matrix[r][c] matrix[r][c] = None # Mark this cell as visited i += 1 # Check if the current delta will result in revisting a cell. nextr = (r + dr) % n nextc = (c + dc) % m if matrix[nextr][nextc] is None: dr, dc = dc, -dr # Turn right. # Go to next cell. r += dr c += dc return spiral def main(): print('Please run this solution on LeetCode.') print('https://leetcode.com/problems/spiral-matrix/') if __name__ == '__main__': main()
true
53a441d1adf62e68789c06718842ae64aae974a7
Kha-Lik/Olimp-Informatics-I_10-11_2021
/calculate_function.py
308
4.125
4
from math import sqrt, sin, cos def calculate(x, y): first_part = (x**3)/(3*y) third_part = 3*sin(y)/cos(x/y) num = x**3-8*x if num < 0: print("Error: cannot get sqrt of negative number") return second_part = sqrt(num) return first_part + second_part + third_part
true
482b59bb08c334c1c689197ea222fe4d6e68a19d
finjo13/assignment_II
/FinjoAss2/Qno8.py
234
4.1875
4
''' 8. Write a Python program to remove duplicates from a list. ''' someList=[23,43,33,23,12,13,13,13,67,89,89] newList=[] for item in someList: if item not in newList: newList.append(item) print(newList)
true
e57364064fc0ffd7f176bea85eded3e22fc2cb37
Levintsky/topcoder
/python/leetcode/math/970_powerful_int.py
1,278
4.1875
4
""" 970. Powerful Integers (Easy) Given two positive integers x and y, an integer is powerful if it is equal to x^i + y^j for some integers i >= 0 and j >= 0. Return a list of all powerful integers that have value less than or equal to bound. You may return the answer in any order. In your answer, each value should occur at most once. Example 1: Input: x = 2, y = 3, bound = 10 Output: [2,3,4,5,7,9,10] Explanation: 2 = 2^0 + 3^0 3 = 2^1 + 3^0 4 = 2^0 + 3^1 5 = 2^1 + 3^1 7 = 2^2 + 3^1 9 = 2^3 + 3^0 10 = 2^0 + 3^2 Example 2: Input: x = 3, y = 5, bound = 15 Output: [2,4,6,8,10,14] Note: 1 <= x <= 100 1 <= y <= 100 0 <= bound <= 10^6 """ class Solution(object): def powerfulIntegers(self, x, y, bound): """ :type x: int :type y: int :type bound: int :rtype: List[int] """ base = 1 xs = [] while base < bound: xs.append(base) base *= x if x == 1: break base = 1 ys = [] while base < bound: ys.append(base) base *= y if y == 1: break res = set() for x in xs: for y in ys: if x + y <= bound: res.add(x+y) return list(res)
true
2ebfad24c9d71a8889f98b6f2f668e3e6d8cce56
Levintsky/topcoder
/python/leetcode/array/subarray_cont/992_subarray_K_diff_int.py
2,475
4.3125
4
""" 992. Subarrays with K Different Integers (Hard) Given an array A of positive integers, call a (contiguous, not necessarily distinct) subarray of A good if the number of different integers in that subarray is exactly K. (For example, [1,2,3,1,2] has 3 different integers: 1, 2, and 3.) Return the number of good subarrays of A. Example 1: Input: A = [1,2,1,2,3], K = 2 Output: 7 Explanation: Subarrays formed with exactly 2 different integers: [1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2]. Example 2: Input: A = [1,2,1,3,4], K = 3 Output: 3 Explanation: Subarrays formed with exactly 3 different integers: [1,2,1,3], [2,1,3], [1,3,4]. Note: 1 <= A.length <= 20000 1 <= A[i] <= A.length 1 <= K <= A.length """ """ Solution 1: O(KN), will TLE A[i..j]: K+1 for an item key, record: (1) how many times cnt; (2) where a number last appears; if memo[k]=(cnt, t), remove all numbers before index t will still maintain the number time complexity: O(N) numbers x O(K) for min() operator every time """ """ Solution 2: Write a helper using sliding window, to get the number of subarrays with at most K distinct elements. Then f(exactly K) = f(atMost K) - f(atMost K-1). Of course, you can merge 2 for loop into ones, if you like. Time Complexity: O(N) """ import collections class Solution(object): def subarraysWithKDistinct(self, A, K): return self.atMostK(A, K) - self.atMostK(A, K - 1) def atMostK(self, A, K): count = collections.Counter() res = i = 0 for j in range(len(A)): if count[A[j]] == 0: K -= 1 count[A[j]] += 1 while K < 0: count[A[i]] -= 1 if count[A[i]] == 0: K += 1 i += 1 res += j - i + 1 return res def solve2(self, A, K): memo = {} result = 0 begin = 0 for j in range(len(A)): memo[A[j]] = j if len(memo) == K + 1: min_index = min(memo.values()) begin = min_index + 1 del memo[A[min_index]] if len(memo) == K: # case # find minimum in values() min_index = min(memo.values()) result += min_index - begin + 1 return result if __name__ == "__main__": a = Solution() print(a.subarraysWithKDistinct([1, 2, 1, 2, 3], 2)) print(a.solve2([1, 2, 1, 2, 3], 2))
true
b3a226938dbe7c5b8ed39e06d8486edcec65fec0
Levintsky/topcoder
/python/leetcode/numerical/1073_add_negbin.py
2,526
4.25
4
""" 1073. Adding Two Negabinary Numbers (Medium) Given two numbers arr1 and arr2 in base -2, return the result of adding them together. Each number is given in array format: as an array of 0s and 1s, from most significant bit to least significant bit. For example, arr = [1,1,0,1] represents the number (-2)^3 + (-2)^2 + (-2)^0 = -3. A number arr in array format is also guaranteed to have no leading zeros: either arr == [0] or arr[0] == 1. Return the result of adding arr1 and arr2 in the same format: as an array of 0s and 1s with no leading zeros. Example 1: Input: arr1 = [1,1,1,1,1], arr2 = [1,0,1] Output: [1,0,0,0,0] Explanation: arr1 represents 11, arr2 represents 5, the output represents 16. Note: 1 <= arr1.length <= 1000 1 <= arr2.length <= 1000 arr1 and arr2 have no leading zeros arr1[i] is 0 or 1 arr2[i] is 0 or 1 """ """ Really similar to 1017. """ class Solution(object): def addNegabinary(self, arr1, arr2): """ :type arr1: List[int] :type arr2: List[int] :rtype: List[int] """ arr1 = arr1[::-1] arr2 = arr2[::-1] n = max(len(arr1), len(arr2)) res = [0] * n for i in range(n): if len(arr1) > i: res[i] += arr1[i] if len(arr2) > i: res[i] += arr2[i] while res.count(2) > 0 or res.count(-1) > 0: # step 1: remove 2 n = len(res) for i in range(n): if res[i] == 2: res[i] = 0 if i + 1 != n: res[i + 1] -= 1 else: res.append(-1) # remove -1 n = len(res) for i in range(n): if res[i] == -1: res[i] = 1 if i + 1 != n: res[i + 1] += 1 else: res.append(1) while len(res) > 1 and res[-1] == 0: _ = res.pop() res = res[::-1] return res def solve2(self, A, B): res = [] carry = 0 while A or B or carry: carry += (A or [0]).pop() + (B or [0]).pop() res.append(carry & 1) carry = -(carry >> 1) while len(res) > 1 and res[-1] == 0: res.pop() return res[::-1] if __name__ == "__main__": a = Solution() # print(a.addNegabinary([1,1,0,1], [1,1,0,1,1])) print(a.solve2([1, 1, 0, 1], [1, 1, 0, 1, 1]))
true
69c850829a9c6a9bded7752eb4f485eaccc8e8e1
NenadPantelic/GeeksforGeeks-Must-Do-Interview-preparation
/Queues/StackUsingTwoQueues.py
888
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Feb 21 20:11:12 2020 @author: nenad """ ''' :param x: value to be inserted :return: None queue_1 = [] # first queue queue_2 = [] # second queue ''' queue_1, queue_2 = [],[] def push_in_stack(x): # global declaration global queue_1 global queue_2 # code here queue_2.append(x) for i in range(len(queue_1)): queue_2.append(queue_1.pop(0)) queue_1, queue_2 = queue_2, queue_1 def pop_from_stack(): ''' :return: the value of top of stack and pop from it. ''' # global declaration global queue_1 global queue_2 if len(queue_1) == 0: return -1 return queue_1.pop(0) push_in_stack(2) push_in_stack(3) print(queue_1, queue_2) print(pop_from_stack()) push_in_stack(4) print(pop_from_stack())
true
c8ab858fae3988afeca03d06a5eb669bbc614be9
Connor-Cahill/call-routing-project
/project/trie.py
2,423
4.28125
4
#!python class TrieNode: """ TrieNode is the node for our Trie Class """ def __init__(self): """ Initializes new TrieNode """ self.children = [None]*10 self.cost = None def __repr__(self): return f"NODE({self.children})" class Trie: def __init__(self): """ Initializes new instance of Trie class with a root node """ self.root = TrieNode() def insert(self, phone_number: str, cost: float): """ Inserts new item into trie """ node = self.root # iterate over to keep appending numbers to tree for num in phone_number: num = int(num) # cast to int b/c used as index # check if there is a child at index # if not then add Node if node.children[num] is None: node.children[num] = TrieNode() # traverse down tree node = node.children[num] # check to see if the current node has a cost property # if it does see if it is less than or greater than param cost value if node.cost is not None: if cost > node.cost: return # set nodes cost to the cost passed as param # only happens if there was no cost or the previous cost # was greater than node.cost = cost def search(self, phone_number: str) -> str: """ Searches for a phone number in trie and returns cost """ if phone_number[0] == "+": # Clean input phone_number = phone_number[1:] # start traversing from root node node = self.root # cost var to keep track of # costs as we traverse down tree cost = 0 # traverse down tree by each digit in phone number for num in phone_number: num = int(num) # if there is a child node in that index # traverse down if node.children[num] is not None: node = node.children[num] # check if node has a cost property # if True assign to our cost var if node.cost is not None: cost = node.cost # return the cost at node if there is one # if not return the stored cost from higher up in tree return node.cost if node.cost is not None else cost
true
f43f784dcb819b4408f0578ac590b4e2fcbc12e4
fwr666/ai1810
/aid/day05/shengdanshu.py
419
4.15625
4
# 3.输入一个整数,此整数代表树干的高度,打印一颗如下 # 形状的圣诞树 #  如: #    输入 3  #     打印如下: #    * # *** # ***** # * # * # * height = int(input('请输入树干高度')) for blank in range(1,height+1): print(' '*(height-blank)+'*'*(2*blank-1)) for _ in range(height): print(' '*(height-1)+'*')
false
c92eb2d64a506f56af0ce03156176b1766f67d22
gdesjonqueres/py-complete-course
/generators/map.py
842
4.15625
4
friends = ['Rolf', 'Jose', 'Randy', 'Anna', 'Mary'] friends_lower = map(lambda x: x.lower(), friends) print(next(friends_lower)) # this is equivalent to: friends_lower = [f.lower() for f in friends] friends_lower = (f.lower() for f in friends) # prefer generator comprehension over the other two class User: def __init__(self, name, password): self.name = name self.password = password @classmethod def from_dict(cls, data): return self(data['name'], data['password']) user_list = [ {'name': 'Jose', 'password': '123'}, {'name': 'Rolf', 'password': '456'} ] users = [User.from_dict(user) for user in user_list] # in this case map is preferable because it is more readable # and there no overhead of declaring a variable 'user' as in the comprehension users = map(User.from_dict, user_list)
true
65163e63c3495fa837d8d3ae7cb0f3a320b63bed
djpaguia/SeleniumPythonProject1
/Demo/PythonDictionary.py
1,360
4.34375
4
# There are 4 Collection data types in Python # List | Tuple | Set | Dictionary # List - [] - ordered | indexed | changeable | duplicates # Tuple - () - ordered | indexed | unchangeable | duplicates # Set - {} - unordered | unindexed | no duplicates # Dictionary - {K:V} - unordered | indexed | changeable | no duplicates my_dict = { "class" : "animal", "name" : "giraffe", "age" : 10 } print(my_dict) print(my_dict["name"]) # Prints value of the key = "name" print(my_dict.get("name")) # Prints value of the key = "name" print(my_dict.values()) # Prints all Values for x in my_dict: print(x) # Prints all Keys. for x in my_dict: print(my_dict[x]) # Prints all Values. for x,y in my_dict.items(): # Prints all keys and values print(x, y) my_dict["name"] = "elephant" # Updates value of existing Key print(my_dict) my_dict["color"] = "grey" # Adds a new key and value since the key is previously non-existent. print(my_dict) my_dict.pop("color") # Removes key "color" and its value from the Dictionary print(my_dict) my_dict.popitem() # Removes last item from the dictionary. print(my_dict) del my_dict["class"] print(my_dict) my_dict.clear() print(my_dict) del my_dict
true
7bb8a309c528e4d676b9cd88a38a02a44dd171b1
djpaguia/SeleniumPythonProject1
/Demo/PythonSet.py
2,007
4.5
4
# There are 4 Collection data types in Python # List | Tuple | Set | Dictionary # List - [] - ordered | indexed | changeable | duplicates # Tuple - () - ordered | indexed | unchangeable | duplicates # Set - {} - unordered | unindexed | no duplicates # Dictionary - {K:V} - unordered | indexed | changeable | no duplicates my_set = {"Chalk", "Duster", "Board"} print(my_set) # print(my_set[1]) # cannot use this in Set because it is unindexed. But you can use a for loop for x in my_set: print(x) print("Chalk" in my_set) # True my_set.add("Pen") print(my_set) my_set.update(["Pencil", "Eraser"]) print(my_set) print(len(my_set)) my_set.remove("Pencil") # Once an element is removed, it will throw an exception if you try to remove it again. print(my_set) my_set.discard("Pen") # If an element is discarded, it will NOT throw an exception if you try to discard it again. print(my_set) my_set.pop() # Randomly deletes an element within a set print(my_set) del my_set # Deletes a set. my_set_2 = {"Apples", 1, 2, (3, 4, 5)} print(my_set_2) my_list = [1,2,3] print(my_list) my_set_3 = set(my_list) # Converts List to a Set. print(my_set_3) # UNION | INTERSECTION | DIFF| SYMMETRIC DIFF A = {'A', 'B', 1, 2, 3} B = {'B', 'C', 3, 4, 5} print(A.union(B)) # Prints values that are present in A or B. print(A | B) # Pipe symbol "|" is similar to Union. print(A.intersection(B)) # Prints values that are both present to A and B print(A & B) # And symbol "&" is similar to Intersection. print(A.difference(B)) # Prints values that are present in A but not in B print(A - B) # Minus symbol "-" is similar to Difference. print(A.symmetric_difference(B)) # Prints values that are unique to both A and B. Common elements are not printed. print(A ^ B) # Cap symbol "^" is similar to Symmetric Difference.
true
36542eea9c4084eab54698adf5cb8f56f31c16f8
wanderleibittencourt/Python_banco_dados
/Modulo-2/Aula2-ClassesHerança/aula1.py
1,667
4.34375
4
# Agora que já conhecemos sobre classes e alguns dos seus comportamentos # Vamos conhecer uma outra pratica muito usada a Herança # Existem dois tipos de Herança # - Herança Simples # - Herança Multipla # Para este curso abordaremos a Herança simples # O que é Herança na programação? # # Herança como o proprio nome ja diz é herdar algo de sua classe Pai ou SuperClass # O que uma classe pode herdar para outra pode ser absolutamente tudo # podemos pensar que a classe Filha e a classe Pai são praticamente a mesma classe pois # instanciando a classe filha temos as mesmas caracteristicas da classe Pai # Exemplo: # Aqui temos a classe Animal que é a classe pai nesse exemplo: # Se quisermos uma classe Cachorro por exemplo teriamos que repetir o mesmo código na classe Cachorro # Pois um animal pode ter patas, calda e emitir um som # Como fazemos a Herança? # Para herdar devemos criar a classe filha e nesta classe ao final do nome abrimos dois parenteses () # e passamos para esse parenteses o nome da classe Pai # Exemplo: class Animal: def __init__(self, patas, calda, som): self.patas = patas self.calda = calda self.som = som def emitir_som(self): print(self.som) class Cachorro(Animal): def nadar(self): print("Sou um cachorro estou nadando") class Cobra(Animal): def subir_em_arvores(self): print("Sou uma cobra e estou subindo na arvore") cachorro = Cachorro(patas=4, calda=True, som="Au au au") cachorro.emitir_som() cachorro.nadar() cobra = Cobra(patas=0, calda=True, som="ZZZzzzzZZZzzzzZ") cobra.emitir_som() cobra.subir_em_arvores()
false
335c2bdee5d841a95132706f8a5a3924c3ab05f0
Esther-Wanene/training101
/lists.py
1,181
4.46875
4
empty_string = "" my_first_number = 0 empty_list = [] noise_makers= ["Brian", "Mike", 9, True] days_of_the_week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] print(days_of_the_week) number_of_days_in_a_week = len(days_of_the_week) print(number_of_days_in_a_week) # list indexing to retrieve the 3rd element: n-1 print(days_of_the_week[2]) # list to retrieve monday to wednesday print(days_of_the_week[0:3]) # list to retrieve from thursday to sunday print(days_of_the_week[3:]) details=["Esther", 23, "testingwdg21@outlook.com", "Dublin"] # to retrieve age age = details[1] # to retrieve location location = details[3] # output the list in reverse print(details[::-1]) numbers=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # print 8 and 9 sub_num = numbers[-3:-1] print(sub_num) # append is used to add a value to a list days_of_the_week.append("val") print(days_of_the_week) # you can append a list to another list # days_of_the_week.append(numbers) # # the appended list becomes an element # print(days_of_the_week[-1]) days_of_the_week.extend(numbers) print("extend", days_of_the_week) list1= [0, 1] list2 = [2, 3] list1.append(list2) list3 = list1+list2 print(list3)
true
90aa42e73081e6f1177ccb48753d847c18243855
Esther-Wanene/training101
/Trainee_task3.py
569
4.40625
4
#Write a program that takes a list of numbers (for example, a = [5, 10, 15, 20, 25]) and #makes a new list of only the first and last elements of the given list. For practice, #write this code inside a function # define the list you want to use as input a = [7,5, 10, 15, 20, 25] # function to slice the list with parameter x def slice_list(x): # assign a new variable to represent the new list # x[0] reps first element of the list and x[-1] reps the last element of the list # new_list = [x[0], x[-1]] return new_list print(slice_list(a))
true
6382d8350f3b9e57274a3154075ab165e089f5d5
NazmulMilon/problem-solving
/if_else_condition.py
302
4.125
4
n=int(input("Enter a integer number:")) if(n%2==0): if (n>=2 and n<6): print("Not Weird") #print("Weird") #elif (n>=2 and n<6): #print("Not Weird") elif (n>6 and n<=20): print("Weird") elif(n>20): print("Not Weird") else: print("Weird")
false
b1de842fe2c8dd3ce6ca046b074ef97b3fcf9571
rRamYah/Python-Basics
/1_Swap2Nos.py
425
4.15625
4
#n1 = 10 #n2 = 20 n1 = input('Enter number 1: ') n2 = input('Enter number 2: ') print('value of number 1 before swapping:', n1) print('value of number 2 before swapping:', n2) #Approach 1 using temporary variables #temp = n1; #n1 = n2; #n2 = temp; # Approach 2 without using temp variable n1,n2 = n2,n1 print('value of number 1 after swapping:', n1) print('value of number 2 after swapping:', n2)
false
5c33fea35ba7602309c76f301a95950656aedffe
CellEight/Interest-Rate-Prediction
/interestRatePrediction.py
240
4.3125
4
def stringTo3TupleList(string): """Takes as input a string and returns a list of all possible 3-tuples of ajacent words""" output = [] string = string.split() for i in range(len(string-2)): output.append(string[i:i+3]) return ouput
true
d33c6ade75a190274d1b81d472fe55b2b3702ebf
laurmertea/simple-chatty-bot-python-developer
/scripts/simple_counting_interaction.py
1,788
4.53125
5
# Description # Now you will teach your bot to count. It's going to become an expert in numbers! # Objective # At this stage, you will program the bot to count from 0 to any positive number users enter. # Example # The greater-than symbol followed by space (> ) represents the user input. Notice that it's not the part of the input. # Example 1: a dialogue with the new version of the bot # `Hello! My name is Aid.` # `I was created in 2020.` # `Please, remind me your name.` # > Max​​​​​​​ # `What a great name you have, Max!` # `Let me guess your age.` # `Tell me remainders of dividing your age by 3, 5 and 7.` # > 1 # > 2 # > 1 # `Your age is 22; that's a good time to start programming!` # `Now I will prove to you that I can count to any number you want.` # > 5 # `0 !` # `1 !` # `2 !` # `3 !` # `4 !` # `5 !` # `Completed, have a nice day!` # Note: each number starts with a new line, and after a number, # the bot should print the exclamation mark. # Use the provided template to simplify your work. # You can change the text if you want, but be especially careful when counting numbers. print('Hello! My name is Aid.') print('I was created in 2020.') print('Please, remind me your name.') name = input() print('What a great name you have, ' + name + '!') print('Let me guess your age.') print('Enter remainders of dividing your age by 3, 5 and 7.') rem3 = int(input()) rem5 = int(input()) rem7 = int(input()) age = (rem3 * 70 + rem5 * 21 + rem7 * 15) % 105 print("Your age is " + str(age) + "; that's a good time to start programming!") print('Now I will prove to you that I can count to any number you want.') number = int(input()) x = range(number) for n in x: print(str(n) + ' !') print(str(number) + ' !') print('Completed, have a nice day!')
true
12f05b5978590f815410b84095b880e3c48c3c0e
jfenton888/AdvancedCompSciCode
/CS550 Fall/September 19/helloWorld.py
490
4.125
4
import sys names = ["John", "Henry", "Palmer", sys.argv[1]] for x in range(0, 3): currentName = names[x] print("Hello, "+ currentName + "!") #if names[3] == "Mrs. Healy" or names[3] == "Healy" or names[3] == "Meghan" or names[3] == "Ms. Hoke" or names[3] == "Mrs Healy": print(names[3].find("Healy")) if names[3] in ["Mrs. Healy", "Healy", "Meghan", "Ms. Hoke", "Mrs Healy"]: print(names[3] + ", thank you for joining us!") else: print(names[3] , " what are you doing here? This isn't your table!")
false
a0ae3540f2e8420fb821634146e3cf63b8363221
quanganh1996111/30days-python
/day-09-conditionals/exercise-3.py
363
4.28125
4
# Get two numbers from the user using input prompt. If a is greater than b return a is greater than b, if a is less b return a is smaller than b, else a is equal to b. Output: a=float(input('Nhap a bang: ')) b=float(input('Nhap b bang: ')) if a>b: print('a is greater than b') elif a<b: print('a is smaller than b') elif a==b: print('a is equal to b')
true
052db6ab09a5a9d85d0b54202c84037aa55eb657
Rishabhjain-1509/Python
/Python Project/HomeEx3.py
389
4.25
4
# Area of the triangle Side1 = int( input( "Enter the First side of the triangle = " ) ) Side2 = int( input( "Enter the Second side of the triangle = " ) ) Side3 = int( input( "Enter the Third side of the triangle = " ) ) SSum = ( Side1 + Side2 + Side3 ) / 2 Area = (SSum * ( SSum - Side1 ) * ( SSum - Side2 ) * ( SSum - Side3 ) ) ** 0.5 print( "The area of the triangle = " , Area )
false
b8c68289d8c60b9311eb440f5ba84cd28ce0f94e
jeremysong/rl-book-exercises
/chap_4/jacks_car_rental/jacks_car_rental.py
2,317
4.25
4
"""Jack manages two locations for a nationwide car rental company. Each day, some number of customers arrive at each location to rent cars. If Jack has a car available, he rents it out and is credited $10 by the national company. If he is out of cars at that location, then the business is lost. Cars become available for renting the day after they are returned. To help ensure that cars are available where they are needed, Jack can move them between the two locations overnight, at a cost of $2 per car moved. We assume that the number of cars requested and returned at each location are Poisson random variables, meaning that the probability that the number is n (the expected number). To simplify the problem slightly, we assume that there can be no more than 20 cars at each location (any additional cars are returned to the nationwide company, and thus disappear from the problem) and a maximum of five cars can be moved from one location to the other in one night. """ import numpy as np from chap_4.jacks_car_rental.policy_iteration import PolicyIteration from chap_4.jacks_car_rental.rental_policy import RentalPolicy class RentalLocation: def __init__(self, request_rate, return_rate, max_cars=20): self._request_rate = request_rate self._return_rate = return_rate self._max_cars = max_cars def rent_cars(self, avail_cars): """ Draws number of rental cars from the poisson distribution. If there is no sufficient number of cars, deduct the rewards. """ num_rents = np.random.poisson(self._request_rate) if avail_cars >= num_rents: reward = num_rents * 10 left_cars = avail_cars - num_rents else: reward = avail_cars * 10 left_cars = 0 return left_cars, reward def return_cars(self, avail_cars): num_returns = np.random.poisson(self._request_rate) return min(self._max_cars, avail_cars + num_returns) if __name__ == '__main__': rental_policy = RentalPolicy() print(rental_policy.get_state_values()) print(rental_policy.get_policy()) policy_iteration = PolicyIteration(rental_policy) policy_iteration.evaluate() print(rental_policy.get_state_values()) print("Optimal policy {}".format(rental_policy.get_policy()))
true
b3cd1a9c0b97e05dc5c1de8eeafbaf665e8e0227
cwdbutler/python-practice
/Algorithms/binary search.py
680
4.15625
4
def binary_search(array, element): # return the index of the element left = 0 right = len(array) while left < right: # this should always be true so it makes the if statements loop mid = (left + right) // 2 if array[mid] == element: # if mid = element we are looking for just return mid return mid elif array[mid] < element: # if less than element, ignore the left, search the right left = mid elif array[mid] > element: # vice versa right = mid return left print(binary_search([2, 5, 7, 8, 12, 14, 16, 18, 21, 23, 28, 33], 7)) # the array we input must be sorted
true
99a13ff2ab97c4222f0a82d951b9d843a40fe9c5
adisonlampert/include-projects
/Advanced-Concepts/starter-code/rock-paper-scissors/rockpaperscissors.py
1,365
4.5
4
import random import tkinter #NOTE: A function that determines whether the user wins or not # Passes the user's choice (based on what button they click)to the parameter def get_winner(call): # Access variables declared after the function so that the variables can be changed inside of the function global wins, win, output # 1. Create random integer 1-3 to use as computer's play # 2. Using if-statements, assign the computer to a choice (rock, paper, scissors) using the random integer generated # 3. Determine the winner based on what the user chose and what the computer chose # Rock beats Scissors # Paper beats Rock # Scissors beats Paper # It's a tie if the computer and user chose the same object # If the user wins, increase win by 1 # Use the output label to write what the computer did and what the result was (win, loss, tie) # Use these functions as "command" for each button def pass_s(): get_winner("scissors") def pass_r(): get_winner("rock") def pass_p(): get_winner("paper") window = tkinter.Tk() #Variable to count the number of wins the user gets win = 0 #START CODING HERE # 1. Create 3 buttons for each option (rock, paper, scissors) # 2. Create 2 labels for the result and the number of wins # 3. Arrange the buttons and labels using grid window.mainloop()
true
a6659ece35f1f6c0f03446c1a11278f7c25d7288
lin0110/Data-Science---Unit-1-Python
/PythonBreak.py
1,145
4.53125
5
#Scenario #The break statement is used to exit/terminate a loop #Design a program that uses a while loop and continuously asks the user to enter a word unless the user enters “Chupacabra” as the secret exit word. In which case, the message “You’ve successfully left the loop.” should be printed to the screen, and the loop should terminate. #Don’t print ANY of the words entered by the user. Use the concept of conditional execution and the break statement. #start coding below here: some code is pre-filled for you. #create the "secret_word" variable secret_word = "" #start your while loop - which will run while something is True while True: #create a "loop control variable" - a way for secret_word to be updated by user input() secret_word = input("Enter a word unless the user enters “Chupacabra” as the secret exit word. ") #create a conditional argument - if the user enters “Chupacabra”, break out of the loop if secret_word == “Chupacabra”: break #print out a message to run after your loop is terminated. “You’ve successfully left the loop. print("You’ve successfully left the loop.")
true
c46c747b079d3422b9646de1390a8670e29257b9
ghostklart/python_work
/08.03.py
277
4.15625
4
def make_shirt(size, text): rmsg = f"You have ordered a {size} size shirt with '{text}' print!" print(rmsg) prompt_0 = "What size are you: " prompt_1 = "What text would you like to have printed on: " size = input(prompt_0) text = input(prompt_1) make_shirt(size, text)
true
1892d459ba8f4a64d381fe10cee41fd6270bf173
ninux1/Python
/decorators/simple_deco1.py
936
4.28125
4
#!/usr/bin/env python """ Plz refer to simple_deco.py for some reference on decorators. This syntax may not be exactly like the decorator but its the same for exact syntax plz refer to actual_deco.py at same location. """ def called(func): # This is a function to receive the function to be modified/decorated. i.e decorator def exe(num): # This is a new function where the decoration/modification of the original function happens. return func(num) return exe # Returning the modified function pointer.to the callee def mul(num): print('From the Decorated function {}'.format(num)) #foo = called(mul) # foo has the decorated function which is returned from the wrapper function called() mul=called(mul) # Now instead of new function variable what if we replace the original function with its modified/decorated version directly. print(mul(10)) # Derefrencing to execute/invoke the decorated function.
true
2653c8b66067aa50c5701f2bec1c69e468c6b664
rajsingh7/Cracking-The-Machine-Learning-Interview
/Supervised Learning/Regression/question13.py
942
4.3125
4
# When would you use k-Nearest Neighbors for regression? from sklearn import neighbors import numpy as np import matplotlib.pyplot as plt # Let's create a small random dataset np.random.seed(0) X = 15 * np.random.rand(50, 1) y = 5 * np.random.rand(50, 1) X_test = [[1], [3], [5], [7], [9], [11], [13]] # We will use k=5 in our example and try different weights for our model. n_neighbors = 5 weights = ['uniform', 'distance'] for i, weight in enumerate(weights): knn_regressor = neighbors.KNeighborsRegressor(n_neighbors=n_neighbors, weights=weight) knn_regressor.fit(X, y) y_pred = knn_regressor.predict(X_test) plt.subplot(2, 1, i + 1) plt.scatter(X, y, c='r', label='data') plt.scatter(X_test, y_pred, c='g', label='prediction') plt.legend() plt.title("KNeighborsRegressor (k = %i, weights = '%s')" % (n_neighbors, weights[i])) plt.show()
true
d2dbe7bb9c6eee567fb4ad09a449e2ac2a0ac31c
EmirVelazquez/thisIsTheWay
/lists.py
1,716
4.28125
4
# Working with lists basics (similar to an array from JS) random_numbers = [44, 4, 5, 24, 42, 10] office_char = ["Michael", "Jim", "Dwight", "Pam", "Karen", "Toby", "Dwight", "Dwight"] print(office_char) # Return element index 4 print(office_char[4]) # Return element from index 2 and forward print(office_char[2:]) # Return elements within specified range print(office_char[1:4]) # ================================================================================== # Common list functions # ================================================================================== # Combines the passed list at the end of the list office_char.extend(random_numbers) print(office_char) # Inserts the speficifed element to the end of list office_char.append("Oscar") print(office_char) # Inserts the second paramater at the specific index office_char.insert(1, "Michael") print(office_char) # Removes a specific element from the list office_char.remove("Toby") print(office_char) # Removes all of the elements from the list office_char.clear() print(office_char) # Removes last element from list office_char.pop() print(office_char) # Get the index of an existing element in the list only (will error if it doesn't exist in list) print(office_char.index("Jim")) print(office_char.index("Creed")) # Will return the number of times the specified element exists in the list print(office_char.count("Dwight")) # Will sort in ascending order (Alphabetical in this case) office_char.sort() print(office_char) # Ascending order (lowest number to highest) random_numbers.sort() print(random_numbers) # Self explanatory random_numbers.reverse() print(random_numbers) office_char2 = office_char.copy() print(office_char2)
true
4fd7fe64bf80f30b56911568b72a5cfa2371bb60
Vinodkannojiya/PythonStarter1
/8_Swapping_numbers.py
318
4.125
4
#method 1 Swapping with temp/extra variable a,b=5,2 print("a before is ",a," and b before is ",b) temp=a a=b b=temp print("a after is ",a," and b after is ",b) #Method swapping wothout extra variable c,d=5,2 print("c before is ",c," and d before is ",d) d=c+d c=d-c d=d-c print("c after is ",c," and d after is ",d)
true
db4b0b8eb0c68c5275b092287821c4a45deb47f1
SenpaiPotato/gwc
/chatbot.py
2,169
4.1875
4
import random # --- Define your functions below! --- def introduction(): acceptable_answers = ["hey", "hello", "hi", "holla", "what's up"] answer = input("Hello? ") if answer in acceptable_answers: print("I am nani nice to meet you ") else: print("That's cool!") def rock_paper_scissors(): answer = input("Rock, Paper, or Scissors? ") choices = ["rock", "scissors", "paper"] word = random.choice(choices) done = False while done is not True: if answer == word: print("I choose" + word) answer = input("Try Again ") elif answer == "rock" and word == "scissors": print("I choose " + word) print("you win ") done = True elif answer == "paper" and word == "scissors": print("I choose " + word) print("you lose") done = True elif answer == "rock" and word == "paper": print("I choose " + word) print("you lose") done = True elif answer == "scissors" and word == "paper": print("I choose " + word) print("you win") done = True elif answer == "scissors" and word == "rock": print("I choose " + word) print("you lose") done = True elif answer == "paper" and word == "rock": print("I choose " + word) print("you win") done = True else: answer = input("Try again, rock, paper, or scissors? ") done = False def goodbye(): print("goodbye") print(" (\_/)") print(" |. .|") print("=\_T_/=") print(" / \ .-.") print(" | _ |/") print("/| | ||") print("\)_|_(/") # --- Put your main program below! --- def main(): while True: introduction() response = input("would you like to play rock, paper, scissors? ") if response == "yes": rock_paper_scissors() if response == "no": exit() goodbye() exit() # DON'T TOUCH! Setup code that runs your main() function. if __name__ == "__main__": main()
true
80531e604b5a016e89fc250874f79126dffb3a76
mikej803/digitalcrafts-2021
/python/homework/shortS.py
265
4.15625
4
strings = ['work', 'bills', 'family', 'vacation', 'money'] def shortest(strings): shortest = strings[0] for i in strings: if i <= shortest: shortest = i print('This is the shortest string:', shortest ) shortest(strings)
true
9cf48628d1fb72c1396ff5e5482e494bfb7ee98d
vtt-info/ECE40862
/glasere_lab1/part1/program3a.py
238
4.15625
4
num = int(input("How many Fibonacci numbers would you like to generate? ")) fib = [1, 1] while len(fib) < num: fib.append(fib[-1] + fib[-2]) fibs = [str(val) for val in fib[:num]] print("The Fibonacci Sequence is: " + ", ".join(fibs))
false
c5ef5a96108672e690cbe1c15b2e0a47660fadbe
SaranyaEnesh/luminarpython
/luminarpython1/regularexpression/quantifiers.py
392
4.25
4
from re import * #pattern="a+"#it check only the position of more than a #pattern="a*"#it check all positions #pattern="a?"#it check all position individually #pattern="a{2}"#chk 2 num of a pattern="a{2,3}"#mini 2 and max 3 num of a matcher=finditer(pattern,"aabaaaabbabbaaaa") count=0 for match in matcher: print(match.start()) print(match.group()) count+=1 print("count",count)
true
7e63ab3efe3060db6eacb498029fb8971ff9c4e2
SaranyaEnesh/luminarpython
/luminarpython1/operators/arithemeticoperator.py
538
4.125
4
num1=int(input("enter value for num1")) num2=int(input("enter value for num2")) addresult=num1+num2 print("additional rslt=",addresult) num1=int(input("enter value for num1")) num2=int(input("enter value for num2")) subresult=num1-num2 print("sub rslt=",subresult) num1=int(input("enter value for num1")) num2=int(input("enter value for num2")) multiresult=num1*num2 print("multi rslt=",multiresult) num1=int(input("enter value for num1")) num2=int(input("enter value for num2")) addresult=num1+num2 print("additional rslt=",addresult)
false
9b82843212c68e9143b61223a32880523f094253
Jiangfengtime/PythonDemo
/Test02/Class2.py
2,894
4.125
4
# 类中如果属性名和方法名相同的话,属性会覆盖方法 # class C: # def x(self): # print("x-man") # # # c = C() # c.x() # c.x = 1 # print(c.x) # c.x() # 绑定 # class BB: # def printAA(): # print("printAA") # # def printBB(self): # print("PrintBB") # # # BB.printAA() # 如果没有加self,则可以通过类名访问 # # BB.printBB() # 报错 # bb = BB() # # bb.printAA() # 如果加了self,则不能通过类名访问 # bb.printBB() # class CC: # def setXY(self, x, y): # self.x = x # self.y = y # # def printXY(self): # print(self.x, self.y) # # # __dict__:获取当前对象所包含的属性 # dd = CC() # print(dd.__dict__) # print(CC.__dict__) # dd.setXY(4, 5) # print(dd.__dict__) # 一些相关的BIF # issubclass(class, classinfo):判断一个类是否是另一个类的子类 # 注意: # 1、一个类被认为是其自身的子类 # 2、classinfo可以是类对象组成的元祖,只要class与其中任何 # 一个候选类的子类,则返回True # class A: # pass # # # class B(A): # pass # # # # 一个类被认为是其自身的子类 # print(issubclass(A, A)) # print(issubclass(B, A)) # isinstance(Object, classinfo):判断一个对象是否属于指定的类 # class A: # pass # # # class B: # pass # # # a = A() # b = B() # print(isinstance(a, A)) # print(isinstance(b, A)) # 1、hasattr(object, name):判断属性名是否属于该对象 # 2、getattr(object, name, [,default]): # 获取对象的指定属性,如果属性不存在,则返回参数3的提示信息 # 3、setattr(object, name, value):给对象的属性赋值 # 4、delattr(object, name):删除指定属性,如果属性不存在,则抛出异常 # class C: # def __init__(self, x=0): # self.x = x # # # c = C() # # 注意:属性名需要括起来 # print(hasattr(c, 'x')) # print(getattr(c, 'x', '你访问的属性不存在')) # print(getattr(c, 'y', '你访问的属性不存在')) # setattr(c, 'y', 100) # print(getattr(c, 'y', '你访问的属性不存在')) # delattr(c, 'y') # print(getattr(c, 'y', '你访问的属性不存在')) # property(fget=get, fset=set, fdel=None, doc=None) # 第一个属性是获取属性的方法,第二个属性是设置属性的方法 # 第三个属性是删除属性的方法,第四个 class C: def __init__(self, size=10): self.size = size def getSize(self): return self.size def setSize(self, size): self.size = size def delSize(self, size): del self.size x = property(getSize, setSize, delSize) # 原始的操作方法 # c = C(5) # print(c.getSize()) # c.setSize(10) # print(c.getSize()) # 现在的操作方法 d = C() d.x = 10 # 相当于:d.setSize() print(d.x) # 相当于:d.getSize() del d.x # 相当于:d.delSize()
false
a4e978fb0aa774bc27dfef08caf8767008a5fe16
Jiangfengtime/PythonDemo
/Test02/Turtle.py
2,127
4.15625
4
# class Animal: # # 属性 # legs = 4 # name = 'animal' # shell = False # # 方法 # def run(self): # print('动物向前爬') # # def sleep(self): # print("动物要睡觉") # # # class Turtle(Animal): # # 属性 # color = 'green' # weight = 10 # legs = 4 # shell = True # mouth = '大嘴' # # # 方法 # def climb(self): # print("向前爬") # # def run(self): # print("向前跑") # # def bite(self): # print("咬人") # # def sleep(self): # print("睡觉") # # # tt = Turtle() # tt.sleep() # class MyList(list): # pass # # # list2 = MyList() # # list2.append(5) # list2.append(3) # list2.append(4) # list2.append(1) # print(list2) # list2.sort() # print(list2) # self # class Ball: # def setName(self, name): # self.name = name # # def kick(self): # print("我叫%s,该死的,谁踢我" % self.name) # # # a = Ball() # a.setName("球A") # b = Ball() # b.setName("球B") # a.kick() # b.kick() # 魔法方法 # class Ball: # def __init__(self, name): # self.name = name # # def kick(self): # print("我叫%s,该死的,谁踢我" % self.name) # # # a = Ball("球A") # b = Ball("球B") # a.kick() # b.kick() # 私有元素 # class Person: # __name = "小甲鱼" # # def getName(self): # return self.__name # # p = Person() # print(p.getName()) # # print(p._Person__name) # 组合 # class Turtle: # def __init__(self, x): # self.num = x # # # class Fish: # def __init__(self, x): # self.num = x # # # class Pool: # def __init__(self, x, y): # self.turtle = Turtle(x) # self.fish = Fish(y) # # def print_num(self): # print("乌龟有 %d 只,小鱼有 %d 条" # % (self.turtle.num, self.fish.num)) # # # pool = Pool(5, 7) # # pool.print_num() class C: count = 0 a = C() b = C() c = C() print(a.count) print(b.count) print(c.count) c.count = 10 print(a.count) print(b.count) print(c.count) C.count = 100 print(a.count) print(b.count) print(c.count)
false
9f3a411c0a1d10705d11edb67c292267deafce42
nathphoenix/DataScience
/python/class.py
310
4.28125
4
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # for loop # for number in numbers: # if 5 > 3 : # print(number **2) # for number in numbers: # if number > 3 : # print(number) 10 in numbers # greater_than_three = 5 > 3 # greater_than_three if not 3 > 5 : print('This is weird')
false
a024de3e492cbcfe653c2b6e7a08a9c58c313e98
Mahalakshmi7619523920/Mahalakshmi.N
/maxofthreenumbers.py
218
4.15625
4
def max (a,b,c): if a>b and b>c: l=a elif b>a and a>c: l=b else: l=c return l print("enter three values") a=input() b=input() c=input() l=max(a,b,c) print("largest is",l)
true
b9adbdd32cf3825be8c02145d9c8db7d11deeee0
afarica/Task2.16
/p26.py
426
4.15625
4
# If you were on the moon now, your weight will be 16,5% of your earth weight. # To calculate it you have to multiple to 0,165. If next 15 years your weight will # increase 1 kg each year. What will be your weight each year on the moon next # 15 years? your_weight=float(input("Enter your weight:")) years=int(input("How many years:")) on_the_moon=your_weight*0.165 for x in range(0,years+1): y=x*0.165+on_the_moon print(y)
true
87515d27267a8b3e56be0a458a530192473f3a7f
jeromepeng183/Warehouse
/Quadratic_solutions.py
1,276
4.3125
4
#!/usr/bin/env python # coding: utf-8 # In[1]: import math # In[8]: def main(): print('This program find the real solutions to a quadratic\n') a,b,c=eval(input('Please enter the coefficients(a,b,c):')) delta=pow(b,2)-4*a*c if delta>=0: discRoot=math.sqrt(delta) root1=(-b+discRoot)/(2*a) root2=(-b-discRoot)/(2*a) print('\nThe solutions are:',root1,root2) else: print('The equation has no real roots') main() # In[ ]: # In[ ]: # In[15]: def main(): print('This program find the real solutions to a quadratic\n') a,b,c=eval(input('Please enter the coefficients(a,b,c):')) delta=pow(b,2)-4*a*c if delta>0: discRoot=math.sqrt(delta) root1=(-b+discRoot)/(2*a) root2=(-b-discRoot)/(2*a) print('\nThe solutions are:',root1,root2) else: if delta==0: root3=-b/(2*a) print('There is a double root at',root3) else: print('The equation has no real roots') main() # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]:
false
c972456c92ebe364ca07cec941b0de83d664e4bd
INOS-soft/Python-LS-LOCKING-Retunning-access
/3.3 Weighted Independent Set.py
2,175
4.15625
4
""" 3.Question 3 In this programming problem you'll code up the dynamic programming algorithm for computing a maximum-weight independent set of a path graph. This file (mwis.txt) describes the weights of the vertices in a path graph (with the weights listed in the order in which vertices appear in the path). It has the following format: [number_of_vertices] [weight of first vertex] [weight of second vertex] ... For example, the third line of the file is "6395702," indicating that the weight of the second vertex of the graph is 6395702. Your task in this problem is to run the dynamic programming algorithm (and the reconstruction procedure) from lecture on this data set. The question is: of the vertices 1, 2, 3, 4, 17, 117, 517, and 997, which ones belong to the maximum-weight independent set? (By "vertex 1" we mean the first vertex of the graph---there is no vertex 0.) In the box below, enter a 8-bit string, where the ith bit should be 1 if the ith of these 8 vertices is in the maximum-weight independent set, and 0 otherwise. For example, if you think that the vertices 1, 4, 17, and 517 are in the maximum-weight independent set and the other four vertices are not, then you should enter the string 10011010 in the box below. """ def dataReader(filePath): with open(filePath) as f: data = f.readlines() numVertices = int(data[0]) weights = list(map(int, data[1:])) return numVertices, weights def DynamicProgramming(numVertices, weights): dp = [None] * (numVertices + 1) dp[0], dp[1] = 0, weights[0] for i in range(2, len(dp)): dp[i] = max(dp[i - 1], dp[i - 2] + weights[i - 1]) return dp def reconstruction(dp): path = [False] * len(dp) i = len(dp) - 1 while i > 0: if dp[i] == dp[i - 1]: i -= 1 else: path[i] = True i -= 2 return path def main(): filePath = "data/mwis.txt" numVertices, weights = dataReader(filePath) dp = DynamicProgramming(numVertices, weights) path = reconstruction(dp) vertices = [1, 2, 3, 4, 17, 117, 517, 997] for v in vertices: print("Vertex {} contained: {}".format(v, path[v])) if __name__ == "__main__": main()
true
121db2d5907a4251729c7ecf67ebe77673f90bc4
trainingpurpose/python_exercises
/src/py_exercises/lists.py
339
4.21875
4
# -*- coding: utf-8 -*- from py_exercises.recursion import * def my_last(arr): """Find the last element of a list""" return arr[-1] def my_last_recursive(arr): return head(arr) if not tail(arr) else my_last_recursive(tail(arr)) def my_but_last(arr): """Find the last but one element of a list""" return arr[-2]
true
691e45c3e27dd22286408a645c9b3de691002632
theamurtagh/exercises
/fibo.py
1,486
4.34375
4
# Ian McLoughlin # A program that displays Fibonacci numbers. def fib(n): """This function returns the nth Fibonacci number.""" i = 0 j = 1 n = n - 1 while n >= 0: i, j = j, i + j n = n - 1 return i # Test the function with the following value. x = 21 ans = fib(x) print("Fibonacci number", x, "is", ans) # Ian McLoughlin # A program that displays Fibonacci numbers using people's names. def fib(n): """This function returns the nth Fibonacci number.""" i = 0 j = 1 n = n - 1 while n >= 0: i, j = j, i + j n = n - 1 return i name = "Murtagh" first = name[0] last = name[-1] firstno = ord(first) lastno = ord(last) x = firstno + lastno ans = fib(x) print("My surname is", name) print("The first letter", first, "is number", firstno) print("The last letter", last, "is number", lastno) print("Fibonacci number", x, "is", ans) "52167ian.mcloughlin@gmit.ie -> Discussions -> Fibonacci exercise responses -> Re: Fibonacci exercise responses by THEA MURTAGH - Tuesday, 23 January 2018, 10:28 PM My name is Thea so the first and last letter of my name (T + A = 20 + 1) give the number 21. The 21st Fibonacci number is 10946" "52167ian.mcloughlin@gmit.ie -> Discussions -> Week 2 task -> Re: Week 2 task by THEA MURTAGH - Thursday, 1 February 2018, 12:12 AM My surname is Murtagh The first letter M is number 77 The last letter h is number 104 Fibonacci number 181 is 30010821454963453907530667147829489881 Ord () returns a number defining the position of something in a series, "
true
315c8e3a35b4cfb73c61ac77cafd96d11d22e9e3
zardra/Book_Catalog
/books.py
2,144
4.5
4
class Book(object): """Class for creating individual book objects. The defaults for bookcase and shelf are empty strings because a book can be created without placing it on a bookcase shelf. The default for the has_read setting is False because it is assumed that books are being cataloged as they are gotten. Methods for the Book class reflect things people might do with books: - Mark a book as read. - Mark a book as unread. - Place a book on a bookcase shelf. - Get a description of the book. """ bookcase = "" shelf = "" has_read = False def __init__(self, title, author, pub_date): self.title = title self.author = author self.pub_date = pub_date def book_description(self): print "Title: " + self.title print "Author: " + self.author print "Publication Date: " + self.pub_date if self.has_read == True: print "Have Read: Yes" else: print "Have Read: No" def mark_as_read(self): self.has_read = True def mark_as_unread(self): self.has_read = False def place_on_shelf(self, bookcase, shelf): self.bookcase = bookcase self.shelf = shelf class Bookcase(object): """Class for creating individual bookcase objects. Main focus is to give a bookcase an id and assign it shelves. Not sure if I actually need this class, or if just Shelf objects would be enough. """ bookcase_shelves = [] def __init__(self, bookcase_id): self.bookcase_id = bookcase_id def add_shelf(self, shelf): if shelf not in self.bookcase_shelves: self.bookcase_shelves.append(shelf) print shelf + " added." else: print "Shelf in Bookcase already." def remove_shelf(self, shelf): self.bookcase_shelves.remove(shelf) class Bookshelf(object): """Class for creating individual bookshelf objects. Main focus is to give a bookshelf an id and assign it to a bookcase. """ def __init__(self, shelf_id): self.shelf_id = shelf_id
true
2d9092c4d466439da70443d490dbb13fd5fbe574
edimaudo/Python-projects
/daily_coding/coding_bat/Warmup-1/front3.py
315
4.21875
4
#Given a string, we'll say that the front is the first 3 chars of the string. If the string length is less than 3, the front is whatever is there. Return a new string which is 3 copies of the front. def front3(str): if len(str) >= 3: return 3*(str[0]+str[1]+str[2]) else: return 3*str
true
235a331f4571490ddcafe04dddabe5662af7eb0c
edimaudo/Python-projects
/daily_coding/coding_bat/List-2/centered_average.py
1,151
4.1875
4
##Return the "centered" average of an array of ints, which we'll say is the mean average of the values, except ignoring the largest and smallest values in the array. If there are multiple copies of the smallest value, ignore just one copy, and likewise for the largest value. Use int division to produce the final average. You may assume that the array is length 3 or more. def centered_average(nums): if len(nums) < 3: return -1 else: nums.sort() del nums[0] del nums[len(nums)-1] numsSum = sum(nums) numsCount = len(nums) output = int(numsSum/numsCount) return output print(centered_average([1, 2, 3, 4, 100])) print(centered_average([1, 1, 5, 5, 10, 8, 7])) print(centered_average([-10, -4, -2, -4, -2, 0])) print(centered_average([1,1,99,99])) print(centered_average([5, 3, 4, 6, 2])) print(centered_average([5, 3, 4, 0, 100])) print(centered_average([100, 0, 5, 3, 4])) print(centered_average([1000, 0, 1, 99])) print(centered_average([6, 4, 8, 12, 3])) print(centered_average([4, 4, 4, 4, 5])) print(centered_average([4, 4, 4, 1, 5]))
true
073075a4df76770564bc9de4ddf3e0eb6360f74c
AntonioZZanolli/Calculadora
/calculadora.py
1,067
4.34375
4
print("Super calculadora!!") def soma(numero): numero2 = input("Dígite outro número: ") return print(float(numero) + float(numero2)) def subtracao(numero): numero2 = input("Dígite outro número: ") return print(float(numero) - float(numero2)) def divisao(numero): numero2 = input("Dígite outro número: ") return print(float(numero) / float(numero2)) def multiplicacao(numero): numero2 = input("Dígite outro número: ") return print(float(numero) * float(numero2)) def escolher_operacao(numero): operacao = input("Dígite a operação desejada:") if operacao == "/" or "*" or "+" or "-": if operacao == "+": soma(numero) if operacao == "-": subtracao(numero) if operacao == "/": divisao(numero) if operacao == "*": multiplicacao(numero) else: print("Operação indisponivel") def main(): numero = input("Dígite um número: ") escolher_operacao(numero) main()
false
85b30fa9b54a1d41fbd1bccaa44ec96e21f8cade
tanlangqie/coding
/暴力递归与动态规划/不同路径.py
1,698
4.1875
4
[typeq''' 一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为“Start” )。 机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。 问总共有多少条不同的路径? 深度优先遍历 栈 递归 ''' class Solution(object): def move(self,m, n): num = 0 if (m == 1 & n == 1): return 1 if (m > 1): num += self.move(m - 1, n) if (n > 1): num += self.move(m, n - 1) return num s = Solution() print(s.move(2,1)) ''' 二维动态规划 -- class Solution(object): #将二维空间优化至一维空间 def uniquePaths(self, m, n): cur = [1] * n for i in range(1, m): for j in range(1, n): cur[j] += cur[j-1] return cur[-1] # def __init__(self): # self.count = 0 # def uniquePaths(self, m, n): # """ # :type m: int # :type n: int # :rtype: int # """ # # count = 0 # def helper(i,j,m,n): # if i == m - 1 and j == n -1: # self.count += 1 # return # if i + 1 < m and j < n: # helper(i+1,j,m,n) # if i < m and j + 1 < n: # helper(i,j+1,m,n) # helper(0,0,m,n) # return self.count # 作者:powcai # 链接:https://leetcode-cn.com/problems/two-sum/solution/dong-tai-gui-hua-by-powcai-2/ # 来源:力扣(LeetCode) # 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 '''
false
501da8583c29b6287991d0bf2f849ce92d8f0980
uykykhj/hometask-2
/hometask076/main.py
326
4.1875
4
sp=[] for i in range(3): n=input('ведите имя') sp.append(n) x = input('Хотите добавить новые имена?') if x=='yes': while x!='no' : n1=input('Введите имя') sp.append(n1) x = input('Хотите добавить новые имена?') print(sp)
false
2b7d614e8999eaed17d15fb4b89c9907d2263044
marangoni/nanodegree
/Rascunhos/Aula 04 - classes - turtle/turtle1.py
808
4.21875
4
# Programa para desenhar um quadrado # # # # # import turtle def draw_square(): zeca = turtle.Turtle() zeca.shape("turtle") zeca.color("yellow") zeca.speed("normal") nsides = 4 for n in range(0, nsides): zeca.forward(100) zeca.right(90) def draw_circle(): zoca = turtle.Turtle() zoca.shape("turtle") zoca.color("green") zoca.speed("normal") zoca.circle(100) def draw_triangle(): zana = turtle.Turtle() zana.shape("square") zana.color("green") zana.speed("normal") for n in range(0,3): zana.forward(100) zana.right(60) window = turtle.Screen() window.bgcolor("blue") draw_triangle() draw_square() draw_circle() window.exitonclick()
false
bab6f2a3306cbc34bc355d2b07b1e97238668921
marangoni/nanodegree
/Rascunhos/Lição 12 - Resolução problemas/aniversario.py
1,476
4.1875
4
# Given your birthday and the current date, calculate your age # in days. Compensate for leap days. Assume that the birthday # and current date are correct dates (and no time travel). # Simply put, if you were born 1 Jan 2012 and todays date is # 2 Jan 2012 you are 1 day old. # IMPORTANT: You don't need to solve the problem yet! # Just brainstorm ways you might approach it! daysOfMonths = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] def isLeapYear(year): ## # Your code here. Return True or False # Pseudo code for this algorithm is found at # http://en.wikipedia.org/wiki/Leap_year#Algorithm ## if year % 4 <> 0: return False elif year % 100 <> 0: return True elif year % 400 <> 0: return False else: return True def daysBetweenDates(y1, m1, d1, y2, m2, d2): ## days = 0 sum_year = 0 sum_month = 0 for y in range(y1,y2): if isLeapYear(y): sum_year = sum_year + 364 else: sum_year = sum_year + 365 if m2 > m1: for m in range(m1,m2): sum_month = sum_month + daysOfMonths[m] else: for m in range(m2,m1): sum_month = sum_month + daysOfMonths[m] if d2 > d1: sum_days = d2 - d1 else: sum_days = d1 - d2 days = sum_year + sum_month + sum_days ## return days print 'Parabens voce tem ' + str(daysBetweenDates(2000,02,01,2000,03,01)) + ' dias de vida'
true
22b165f8dcee9d2c1caad06e83e45085952cade8
Wanna101/CSC119-Python
/accountBalance.py
863
4.125
4
""" David Young CSC119-479 6/14/2020 Julie Schneider """ def main(): # initial balance is $1000 # 5% interest per year # find balance after first, second, and third year # expected answers: # year 0 = 1000 # year 1 = 1050 # year 2 = 1102.5 # year 3 = 1157.625 # set variables INITIAL = 1000 INTEREST = 0.05 print("Interest of $1000 after 3 years") # set work for balance after 3 years year = 1 value_for_1year = INITIAL * ((1 + INTEREST) ** year) print("%s %.2f" % ("YEAR 1: ", value_for_1year)) year = 2 value_for_2year = INITIAL * ((1 + INTEREST) ** year) print("%s %.2f" % ("YEAR 2: ", value_for_2year)) year = 3 value_for_3year = INITIAL * ((1 + INTEREST) ** year) print("%s %.2f" % ("YEAR 3: ", value_for_3year)) main()
true
b9d441dfd55730285e13e86e7a476f6ee62c0e7b
dugiwarc/Python
/old/find_factors.py
288
4.1875
4
def find_factors(num): """ parameters: a number returns: a list of all of the numbers which are divisible by starting from 1 and going up the number """ factors = [] i = 1 while i <= num: if num % i == 0: factors.append(i) i += 1 return factors print(find_factors(100))
true
ff90e6c18e4b2de09c1ff1e8c240b87b9e3a7211
kerslaketschool/Selection
/if_improvement_excercise.py
905
4.21875
4
#Toby Kerslake #25-09-14 #selection improvement exercise month = int(input("Please enter a month as a number between 1-12: ")) if month == 1: print("The first month is January") elif month == 2: print("The second month is February") elif month == 3: print("The third month is March") elif month == 4: print("The fourth month is April") elif month == 5: print("The fifth month is May") elif month == 6: print("The sixth month is June") elif month == 7: print("The seventh month is July") elif month == 8: print("The eighth month is August") elif month == 9: print("The ninth month is September") elif month == 10: print("The tenth month is October") elif month == 11: print("The eleventh month is November") elif month == 12: print("The final month of the year is December") else: print("Please enter a valid input next time")
true
8dd68555cb736710a37048ec57c3d34d0bf042d1
algorithm006-class01/algorithm006-class01
/Week_02/G20190343010191/LeetCode_144_191.py
906
4.125
4
""" 给定一个二叉树,返回它的 前序 遍历。  示例: 输入: [1,null,2,3] 1 \ 2 / 3 输出: [1,2,3] """ """ 思路: 这周主要练习递归,所以迭代的方法后续再补上 对于N 叉树, 不仅有左子树与右子树 而且是 child1,child2,child3,....childN 于后序而言 先走访 (由左至右) 所有的儿子 最后访问根结点 """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def preorderTraversal(self, root: TreeNode) -> List[int]: if root: res = [] res.append(root.val) res.extend(self.preorderTraversal(root.left)) res.extend(self.preorderTraversal(root.right)) else: res = [] return res
false
570355c3e6194b38f10fc7c0d72d1a829b08c60e
Pranjul-Sahu/Assignment
/Assignment 1 Question2.py
263
4.5
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: #Write a Python program that accepts a word from the user and reverse it. rev_word = input() print("Enter the Word -", rev_word) reversed_word = rev_word[-1::-1] print("After reversing the word -",reversed_word)
true
91427a056a6b775cc3a27efba4e79939b8d495eb
JacobFrank714/CSProjects
/cs 101/labs/lab07.py
2,114
4.5
4
# ALGORITHM : # 1. display the main menu and ask user what task they want performed # 2. check what their answer is # 3. depending on what the answer is, ask the user what the want encoded/decoded or quit the program # 4. ask how many numbers they want to shift the message by # 5. perform the encode/decode function # 6. present the encoded/decoded message # 7. start from the main menu until user wants to quit # import statements # functions def encode(msg, shift): msg = msg.upper() en_msg = [] for i in msg: if i == ' ': en_msg.append(i) continue if (ord(i)+shift) > ord('Z'): i = chr(ord(i)-26) en_msg.append(chr(ord(i)+shift)) en_msg = ''.join(en_msg[:]) return en_msg def decode(msg, shift): msg = msg.upper() de_msg = [] for i in msg: if i == ' ': de_msg.append(i) continue if (ord(i) - shift) < ord('A'): i = chr(ord(i) + 26) de_msg.append(chr(ord(i) - shift)) de_msg = ''.join(de_msg[:]) return de_msg if __name__ == "__main__": # main program while True: choice = input('MAIN MENU\n' '1) Encoding a string\n' '2) Decode a string\n' 'Q) Quit\n' 'Enter your selection ==> ') print() if choice == '1': message = input('Enter (brief) text to encrypt: ') shift_number = int(input('Enter the number to shift letters by: ')) print('Encrypted: {}\n'.format(encode(message, shift_number))) continue elif choice == '2': message = input('Enter (brief) text to decrypt: ') shift_number = int(input('Enter the number to shift letters by: ')) print('Decrypted: {}\n'.format(decode(message, shift_number))) continue elif choice == 'Q' or choice == 'q': break else: continue
true
a2b93cfc53ae35c80dba5f35d37c9832d49604bd
JacobFrank714/CSProjects
/cs 101/programs/program 1.py
1,393
4.3125
4
#Jacob Frank, session 0002, Program #1 #getting the values of all the ingredients for each recipe set recipe_cookies = {'butter':2.5, 'sugar':2, 'eggs':2, 'flour':8} recipe_cake = {'butter':0.5, 'sugar':1, 'eggs':2, 'flour':1.5} recipe_donuts = {'butter':0.25, 'sugar':0.5, 'eggs':3, 'flour':5} print('Welcome to TOGO Bakery\n') #asking for how many of each thing they are wanting to make num_cookies = int(input('How many dozen cookies? => ')) num_cakes = int(input('\nHow many cakes? => ')) num_donuts = int(input('\nHow many dozen donuts? => ')) print() #getting all the calculations done beforehand for readability cups_butter = (recipe_cookies['butter'] * num_cookies) + (recipe_cake['butter'] * num_cakes) + (recipe_donuts['butter'] * num_donuts) cups_sugar = (recipe_cookies['sugar'] * num_cookies) + (recipe_cake['sugar'] * num_cakes) + (recipe_donuts['sugar'] * num_donuts) cups_eggs = (recipe_cookies['eggs'] * num_cookies) + (recipe_cake['eggs'] * num_cakes) + (recipe_donuts['eggs'] * num_donuts) cups_flour = (recipe_cookies['flour'] * num_cookies) + (recipe_cake['flour'] * num_cakes) + (recipe_donuts['flour'] * num_donuts) #printing the recipe print('\nYou will need to order') print('{:.1f} cups of butter'.format(cups_butter)) print('{:.1f} cups of sugar'.format(cups_sugar)) print('%d eggs'%cups_eggs) print('{:.1f} cups of flour'.format(cups_flour))
true
1606161e3c414654b506c6879b60761229ed0244
mandarvu/project_euler
/python3/prob19.py
1,598
4.28125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jul 20 20:13:15 2020 @author: mandarupasani projecteuler.net problem 19 : Counting Sundays """ n_months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] lp_months = n_months.copy() lp_months[1] = 29 days = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"] def leap_chk(year): """1 A function to check whether a year is leap or not. Parameters ---------- year : int A year from christ's birth. Returns ------- bool True if leap, false otherwise Example ------- >>> leap_chk(1996) True >>> leap_chk(2005) False """ if (year % 4) == 0: if (year % 100) == 0: if (year % 400) == 0: return True else: return False else: return True else: return False sunday_count = 0 init_day = 'tue' for year in range(1901,1906): # print(init_day) if (leap_chk(year)): months = lp_months else: months = n_months for i in range(len(months)): nxt_day = days[(days.index(init_day) + (months[i] % 7)) % 7] # init_day = nxt_day if (nxt_day == 'sun'): sunday_count += 1 if (leap_chk(year)): init_day = days[(days.index(init_day) + 2) % 7] else: init_day = days[(days.index(init_day) + 1) % 7]
false
1fb7869848da06f165db950213f1d56ac07524d7
joshuajweldon/python3-class
/exercises/ch08/calc.py
1,020
4.15625
4
def add(x, y): return x + y def subtract(x, y): return x - y def multiply(x, y): return x*y def divide(x, y): try: r = x / y except ZeroDivisionError: r = "Undef." return r operators = { '+': add, '-': subtract, '*': multiply, '/': divide } input("Calculator Application: \nYou may enter an expression of the form x [+-*/]+ y.\nYou my enter 'q' to quit. \nPress ENTER to start.") while True: expression = input(">>> ") if not expression: continue if expression == 'q': break try: curr_x, op, curr_y = expression.split() except ValueError: print("Error: expression must be of the form x [+-*/]+ y") continue try: curr_x = float(curr_x) curr_y = float(curr_y) except ValueError: print("Error: both x ({})and y ({}) must be real numbers".format(curr_x, curr_y)) continue print(operators.get(op, "Invalid Operator ({})".format(op))(curr_x, curr_y))
true
49df67062148f557043a9005b57a7ca95b8c8ae5
General-Blue/Intro-to-Python
/py_basics_1.py
466
4.1875
4
# print hello to the world print("hello world") # ask the user of your program their name and save it into a variable x = input("What is your username? ") # say hello to the user print("hello "+ x) # import the random library import random # use the random library to save a random number into a variable x = random.randint(4, 44) # print that random number to the user print(x) # multiply the random number by 2 and print the result print(x*2) print("END OF CODE")
true
685c3c74dd8bf3a85f02ebff4e51e5d80d124f82
juliakastrup/estudos
/Ex016.py
473
4.25
4
#criar um program aque ao ler um numero quebrado (ex: 6.13652) mostre sua porção inteira (ex: 6) import math num = float(input('Digite um numero: ')) a = math.trunc(num) print('O numero arredondado de {} é {}.'.format(num, math.floor(num))) # poderia ser usado a variável com o math.floor(num) ou math.trunc ao invés de tacar no format # poderia só importar os métodos trunc ou floor # poderia ser usado int(num) que int é inteiro e corta os valores após o ponto
false
786ad1354e9d9a8ed76fd34cce4d72c2ede568d4
isidoraorellana/IntensivoNivelacion
/26082019/000500.py
489
4.1875
4
# -*- coding: utf-8 -*- """ """ e = {"George": 24, "Tom": 32} #se crea diccionario #valores pueden ser de cualquier tipo #las keys generalmente son strings o numeros e[10] = 100 #se agrega una key que es un numero asociado a un valor que tambien es un numero print e #iterar en pares key-valor for key, value in e.items(): #ciclo for imprimira cada key con su valor asignado print ("key:") print(key) print("value:") print (value) print("")
false
5fa811d85c8c128549e67f391425a37f164363a3
aakashp4/Complete-Python-3-Bootcamp
/ch01_overview/task1_2_starter.py
1,348
4.6875
5
""" task1_2_starter.py For this task, you are to manually extract the domain name out of the URLs mentioned on our slide. The URLs are: https://docs.python.org/3/ https://www.google.com?gws_rd=ssl#q=python http://localhost:8005/contact/501 Additional Hints: 1. Prompt for a URL input Example: user_input_str = input('Enter a value: ') 2. Check if URL begins with any of the prefixes by using .startswith() If it does, capture the remaining part of the URL using slicing Example: value = 'hello world' if value.startswith('hello') remaining = value[len('hello'):] 3. Repeat this task for the suffixes. Use .find() for the suffixes. find() returns a -1 for items not found in the string For example: value = 'hello world' position = value.find('world') remaining = value[:position] """ prefixes = ['http://', 'https://'] suffixes = [':', '/', '?'] url = input ('Enter URL with http/s://: ') for prefix in prefixes: if url.startswith(prefix): domain = url[len(prefix):] for suffix in suffixes: position = domain.find(suffix) if position != -1: domain = domain[:position] print(domain)
true
721df54252575dfe9319dee08d2fac9f19f7a2c5
memelogit/python
/module3/numpy - reshape.py
218
4.1875
4
# RESHAPE # ------- import numpy as np arreglo = np.array([2, 3, 9, 4, 6, 7, 2, 1, 0]) print(arreglo.shape) # transforma el arreglo 9, en uno de 3x3 arreglo = arreglo.reshape(3,3) print(arreglo.shape) print(arreglo)
false
ee32e2ec51a0e67de543feca29072aaed27a606b
memelogit/python
/module1/control - actividad if.py
627
4.1875
4
# ACTIVIDAD # --------- # 1.- Escribir un programa que pida al usuario dos números y muestret # por pantalla su división. Si el divisor es cero el programa debe # mostrar un error n = float(input('Introduce el dividendo: ')) m = float(input('Introduce el divisior: ')) if m == 0: print('¡Error! No se puede dividir por 0.') else: print(n/m) # 2.- Escribir un programa que pida al usuario un número entero y # muestre por pantalla si es par o impar n = int(input('Introduce un número entero: ')) if n % 2 == 0: print('El número ' + str(n) + ' es par') else: print('El número ' + str(n) + ' es impar')
false
b2f2f3f0e57dd0a23e8a55cbe46a847d895c0ce5
vinozy/data-structures-and-algorithms
/interviews/reverse-LL/linked_list.py
1,396
4.15625
4
from node import Node class LinkedList: """ create a linked list """ def __init__(self, iterable=[]): """Constructor for the LinkedList object""" self.head = None self._size = 0 if type(iterable) is not list: raise TypeError('Invalid iterable') for item in iterable: self.insert(item) def __repr__(self): return f'<head> is {self.head.val}' def __str__(self): return self.__repr__ def __len__(self): """Return the size of the linked list""" return self._size def insert(self, val): """Add a value to the head of the linked list""" self.head = Node(val, self.head) self._size += 1 def find(self, val): """Find an item in the linked list""" current = self.head while current: if current.val == val: return True current = current._next return False def append(self, val): """Append an item to the end of the linked list""" if self.head is None: self.insert(val) else: current = self.head while current: if current._next is None: current._next = Node(val) self._size += 1 break current = current._next
true
7fc2af4757d2fbce2d4281ce60fd73113963db01
vinozy/data-structures-and-algorithms
/interviews/reverse-LL/reverse_ll.py
666
4.125
4
from linked_list import LinkedList as LL from node import Node # def reverse_ll(list1): # """Reverse a singly linked list.""" # current = list1.head # list2 = LL() # while current is not None: # # list2.insert(current) # list2.head = Node(current.val, list2.head) # current = current._next # return list2.head.val def reverse_ll(sll): """In-place solution to reverse a singly linked list.""" previous = None current = sll.head while current: temp = current._next current._next = previous previous = current current = temp sll.head = previous return sll.head.val
true
1f355ae733498d81e81f2192451550b24b0427f8
vinozy/data-structures-and-algorithms
/data_structures/binary_search_tree/bst_binary_search.py
596
4.375
4
def bst_binary_search(tree, value): """Use binary search to find a value in a binary search tree. Return True if value in tree; return False if value not in tree.""" if not tree.root: return False current = tree.root while current: if current.val == value: return True elif value >= current.val: if current.right: current = current.right else: return False else: if current.left: current = current.left else: return False
true
27b78e6e7bd39d439dc0437aeb61205f157435dd
Karan-21/Database
/database.py
1,576
4.375
4
# name,address,phone # 1) add data 2) show data 3) delete data name = [] address = [] phone = [] while True: print("1. Add data\n2. Show data\n3. Delete data\n4. Exit") ch = int(input("Enter your choice:")) if ch == 1: # while n.isalpha() == False: n = input("Enter name:") while n.isalpha() != True: print("Invalid name!! Please try again") n = input("Enter name:") name.append(n) a = input("Enter address:") address.append(a) p = input("Enter phone number:") phone.append(p) print("-------------DATA STORED--------------") elif ch == 2: n = input("Enter name to display the data:") # karan if n in name: print("-----DATA FOUND------") index_num = name.index(n) print("Name:",name[index_num]) print("Address:",address[index_num]) print("Phone:",phone[index_num]) print("--------------------------------------") else: print("-----DATA NOT FOUND------") elif ch == 3: n = input("Enter name to delete the data:") if n in name: print("-----DATA FOUND------") index_num = name.index(n) name.pop(index_num) address.pop(index_num) phone.pop(index_num) print("------DATA DELETED------") else: print("-----DATA NOT FOUND------")
false
ffba3a558382e3802c9c3437b90df9d983f26bc3
Amazon-Lab206-Python/space_cowboy
/Fundamentals/fun.py
729
4.5
4
# Odd/Even: # Create a function called odd_even that counts from 1 to 2000. As your loop executes have your program print the number of that iteration and specify whether it's an odd or even number. def odd_even(x): for x in range(1,2001): if (x % 2 == 0): print "This is an even number." else: print "This is an odd number." odd_even() # Multiply: # Create a function called 'multiply' that iterates through each value in a list (e.g. a = [2, 4, 10, 16]) and returns a list where each value has been multiplied by 5. def multiply(arr, num): for x in range(0, len(arr)): arr[x] *= num return arr numbers_array = [3, 6, 8, 10, 67] print multiply(numbers_array, 5)
true