blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
3cee29d8ee596d508122d7e4d1349b6e226f148e
iampaavan/Pure_Python
/Exercise-95.py
260
4.21875
4
"""Write a Python program to convert a byte string to a list of integers.""" def byte_str_list_integers(string): """return list of integers.""" my_list = list(string) return my_list print(f"List of integers: {byte_str_list_integers(b'Abc')}")
true
1ae7da4a80ff13e6e38a6f1ef9ec8c092208002d
iampaavan/Pure_Python
/Exercise-15.py
494
4.3125
4
from datetime import date """Write a Python program to calculate number of days between two dates.""" first_date = date(2014, 7, 2) last_date = date(2014, 7, 11) delta = last_date - first_date print(f"First Date: {first_date}") print(f"Second Date: {last_date}") print(f'*****************************************************************') print(f"Difference between the two dates are: {delta.days} days.") print(f'*****************************************************************')
true
9b279f74643634d02aae4969267a3fee44e10a78
iampaavan/Pure_Python
/Exercise-4.py
372
4.3125
4
from math import pi """Write a Python program which accepts the radius of a circle from the user and compute the area.""" def radius(): """Calculate the radius""" r = int(input(f"Enter the radius of the circle:")) Area = pi * (r * r) return f"Area of the circle is: {Area}" c = radius() print(c) print(f'*******************************************')
true
c35a1b8ecdab55a9c6a3dcabc2bdbd241a5e93f5
iampaavan/Pure_Python
/Exercise-28.py
291
4.21875
4
"""Write a Python program to concatenate all elements in a list into a string and return it.""" def concatenate(my_list): """Return a string.""" output = '' for i in my_list: string = str(i) output += string return output print(concatenate([1, 2, 3, 4, 5]))
true
d8b11d176fb47a44390c72b979370931cf9f6ce8
mtrunkatova/Engeton-projects
/Project2.py
2,521
4.25
4
def welcoming(): print("WELCOME TO TIC TAC TOE") print("GAME RULES:") print("Each player can place one mark (or stone) per turn on the 3x3 grid") print("The WINNER is who succeeds in placing three of their marks in a") print("* horizontal,\n* vertical or\n* diagonal row\nLet's start the game") def creating_board(): list1 = list(range(1,3**2+1)) list2 = [' ']*3**2 board = dict(zip(list1,list2)) return board def print_board(board): x = 6*'-' print(x) print(board[1] + '|' + board[2] + '|' + board[3]) print(x) print(board[4] + '|' + board[5] + '|' + board[6]) print(x) print(board[7] + '|' + board[8] + '|' + board[9]) print(x) def win_horizontal(board): we_have_winner = False if board[1] == board[2] == board[3] != ' ' \ or board[4] == board[5] == board[6] != ' ' \ or board[7] == board[8] == board[9] != ' ': we_have_winner = True return we_have_winner def win_vertical(board): we_have_winner = False if board[1] == board[4] == board[7] != ' '\ or board[2] == board[5] == board[8] != ' '\ or board[3] == board[6] == board[9] != ' ': we_have_winner = True return we_have_winner def win_cross(board): we_have_winner = False if board[1] == board[5] == board[9] != ' '\ or board[3] == board[5] == board[7] != ' ': we_have_winner = True return we_have_winner def switch_players(whose_turn): if whose_turn == "O": whose_turn = "X" else: whose_turn = "O" return whose_turn def no_winner(board): if ' ' not in board.values(): return True else: return False def main(): welcoming() board = creating_board() print_board(board) print("========================================") end = False whose_turn = "O" while not end: # pojedou maximalne 9 kol game = int(input("Player {} Please enter your move number: ".format(whose_turn))) if board[game] == ' ': board[game] = whose_turn else: continue print_board(board) x = win_horizontal(board) y = win_vertical(board) z = win_cross(board) w = no_winner(board) if x or y or z: print("Congratulations, the player {} WON!".format(whose_turn)) end = True elif w: break else: whose_turn = switch_players(whose_turn) if __name__ == "__main__": main()
true
e53fe6f2b910c285b7851783b61c4d7939638b71
manoznp/LearnPython-Challenge
/DAY3/list.py
1,519
4.34375
4
#list names = ['raju', 'manoj'] length_names = len(names) print("Length of the array name is {}".format(length_names)) names.append("saroj") length_names = len(names) print("Length of the array name is {}".format(length_names)) print(names) names.insert(1, "sudeep") print("After inserting sudeep at position second: {}".format(names)) for name in names: print(name) # extending the list other_names = ['dipesh', 'pankaj', 'prmaod'] names.extend(other_names) print(names) # Dictionary student = {'name':'manoz', 'time':'1.5 hrs', 'course': 'Data Science', 'fee': 25000, 'hasVeichle': False } # print the value of the dictionary with key print(student['course']) student_all_key = student.keys() print(student_all_key) student_all_value = student.values() print(student_all_value) # iterate in the dictionary for key in student.keys(): print("{} : {}".format(key, student[key])) # change the value of the dictionary student['course'] = 'Advanced Java' print(student) # lets add the key that doesnot exist in the dictionary student student['gender'] = "male" print("after adding gender") print(student) # delete the key course del(student['course']) # after deleting the key course print(student) # convert the student to list student = list(student) # after converting to the list print(student) # check the key is exist in the dictionary or not isCourseExists = "courses" in student print("course exists in student : {} ". format(isCourseExists))
true
6db5f977cc64e90e243d62f3b882c7d77371a86f
Williano/Python-Scripts
/turtle_user_shape/turtle_user_shape.py
2,734
4.1875
4
import turtle window = turtle.Screen() window.setup() window.title("Draw User Shape") window.bgcolor("purple") mat = turtle.Turtle() mat.shape("turtle") mat.color("black") mat.pensize(3) mat.speed(12) drawing = True while drawing: mat.penup() SQUARE = 1 TRIANGLE = 2 QUIT = 0 shape_choice = int(input("What do you want me to draw? (1 = square, 2 = triangle, 0 = quit):")) if shape_choice == SQUARE: side_length = int(input("How long do you want the sides of your square to be?" "Please enter the number of pixels (e.g. 100):")) mat.pendown() x_pos = int(mat.xcor()) y_pos = int(mat.ycor()) heading = int(mat.heading()) print("My 1st corner is at: {}, {} and my heading is {}".format(x_pos, y_pos, heading)) mat.forward(side_length) x_pos = int(mat.xcor()) y_pos = int(mat.ycor()) heading = int(mat.heading()) print("My 2nd corner is at: {}, {} and my heading is {}".format(x_pos, y_pos, heading)) mat.left(90) mat.forward(side_length) x_pos = int(mat.xcor()) y_pos = int(mat.ycor()) heading = int(mat.heading()) print("My 3rd corner is at: {}, {} and my heading is {}".format(x_pos, y_pos, heading)) mat.left(90) mat.forward(side_length) x_pos = int(mat.xcor()) y_pos = int(mat.ycor()) heading = int(mat.heading()) print("My 4th corner is at: {}, {} and my heading is {}".format(x_pos, y_pos, heading)) mat.left(90) mat.forward(side_length) elif shape_choice == TRIANGLE: print("I will draw an equilateral triangle.") side_length = int(input("How long do you want the sides of your triangle to be?" "Please enter the number of pixels (e.g. 100): ")) mat.pendown() x_pos = int(mat.xcor()) y_pos = int(mat.ycor()) heading = int(mat.heading()) print("My 1st corner is at: {}, {} and my heading is {}".format(x_pos, y_pos, heading)) mat.forward(side_length) x_pos = int(mat.xcor()) y_pos = int(mat.ycor()) heading = int(mat.heading()) print("My 2nd corner is at: {}, {} and my heading is {}".format(x_pos, y_pos, heading)) mat.left(120) mat.forward(side_length) x_pos = int(mat.xcor()) y_pos = int(mat.ycor()) heading = int(mat.heading()) print("My 3rd corner is at: {}, {} and my heading is {}".format(x_pos, y_pos, heading)) mat.left(120) mat.forward(side_length) mat.left(120) else: drawing = False else: print("Thank you for playing")
true
532f8be7df48120a466f060ae0b80ebb6b2a7dfa
p3dr051lva/hanoi-s_tower.py
/hanoi.py
1,293
4.1875
4
print('Ola, este eh o jogo, torre de hanoi, o jogo tem o objetivo de voce transferir \ os numero da tore um para a torre 3, sem que numeros maiores fiquem em cima de numeros menores, voce\ so pode mover o disco do "topo", e uma por vez, a primeira torre de baixo para cima eh a t1, a segunda a\ t2, e a terceira a t3, para move-los use o seguinte metodo:t1>t2. para movimentar o disco do "topo" da t1 para o "topo" da t2, bom jogo meu paladino') def hanoi(): t1= [3,2,1] t2= [] t3= [] torres = [t1, t2, t3] aux = 0 print(t1) print(t2) print(t3) while len(torres[-1]) < 3: y1, y2 = [int(i[-1]) - 1 for i in input('digite a origem>destino: ').split('>')] while len(torres[y1]) == 0 or (len(torres[y2]) > 0 and torres[y1][-1] > torres[y2][-1]): print('jogada invalida') print(t1) print(t2) print(t3) y1, y2 = [int(i[-1]) - 1 for i in input('digite a origem>destino: ').split('>')] else: torres[y2].append(torres[y1].pop()) aux += 1 print(t1) print(t2) print(t3) else: print('parabens voce completou o quebra-cabeca em %d movimentos' %(aux)) hanoi()
false
830802e627fe7aaed1057d4ed66ccadf532bf357
tanpv/awesome-blockchain
/algorithm_python/move_zeros_to_end.py
378
4.25
4
""" Write an algorithm that takes an array and moves all of the zeros to the end, preserving the order of the other elements. move_zeros([false, 1, 0, 1, 2, 0, 1, 3, "a"]) returns => [false, 1, 1, 2, 1, 3, "a", 0, 0] The time complexity of the below algorithm is O(n). """ input_list = [false, 1, 0, 1, 2, 0, 1, 3, "a"] def move_zeros(self, input_list):
true
eda4f62ffe3d1771eb868d4325d8310348d521c7
Jayson22341/CS362HW3
/LeapYearProg.py
493
4.21875
4
def leap(n): if n % 4 == 0: if n % 100 == 0: if n % 400 == 0: print(n, 'is a leap year') return print(n, 'is not a leap year') return print(n, 'is a leap year') return print(n, 'is not a leap year') return import time print("This program will determine whether a year you enter is a leap year or not") value = int(input("Enter in a year number: ")) leap(value) time.sleep(5)
false
048ab8c2e21afc334d5cd093b47e7633f3530520
ravenusmc/algorithms
/HackerRank/algorithms/diagonal_diff.py
938
4.1875
4
# Given a square matrix, calculate the absolute difference between the sums of its diagonals. # For example, the square matrix arr is shown below: # URL https://www.hackerrank.com/challenges/diagonal-difference/problem?h_r=next-challenge&h_v=zen # Rank: 1,670,172 arr = [ [1, 2, 3], [4, 5, 6], [9, 8, 9] ] # arr = [ # [1, 2, 3, 4], # [4, 5, 6, 7], # [9, 8, 9, 6], # [4, 5, 6, 7], # ] def diagonalDifference(arr): left_to_right_sum = 0 count_left = 0 while count_left < len(arr): left_to_right_sum = arr[count_left][count_left] + left_to_right_sum count_left += 1 right_to_left_sum = 0 count_up = 0 count_right = len(arr) - 1 while count_right >= 0: right_to_left_sum = arr[count_up][count_right] + right_to_left_sum count_up += 1 count_right -= 1 absolute_difference = abs(left_to_right_sum - right_to_left_sum) return absolute_difference absolute_difference = diagonalDifference(arr) print(absolute_difference)
true
c4bbc4e04d3ab14ecb92baad254d46959fc4329e
Sandeep0001/PythonTraining
/PythonPractice/SetConcept.py
2,742
4.34375
4
#Set: is not order based #it stores different type of data like list and tuple #it performs different mathematical operations #does not store duplicate elements #define a set: use {} s1 = {100, "Tom", 12.33, True} s2 = {1,1,2,2,3,3,} print(s2) #Output: {1, 2, 3} print(s1) #Output: {True, 100, 'Tom', 12.33} #set() function: s3 = set("python") print(s3) #Output: {'t', 'n', 'h', 'y', 'o', 'p'} s4 = set([10,20,30,40]) #storing list in set function print(s4) #output: {40, 10, 20, 30} s5 = set((10,20,30,50)) #storing tuple in set function print(s5) #output: {10, 20, 50, 30} #while creating a set object, you can store only Numbers, strings, tuple #list and dictionary objects are not allowed set1 = {(10,20), 30, 40} print(set1) #output: {40, (10, 20), 30} # set2 = {[10,20], 30} # print(set2) #output: TypeError: unhashable type: 'list' #set operations: #union: use | operator OR union() p1 = {1,2,3,4,5} p2 = {5,6,7,8,9} print(p1|p2) #output: {1, 2, 3, 4, 5, 6, 7, 8, 9} print(p1.union(p2)) #output: {1, 2, 3, 4, 5, 6, 7, 8, 9} print(p2.union(p1)) #output: {1, 2, 3, 4, 5, 6, 7, 8, 9} #intersection: use & operator OR intersection() p3 = {1,2,3,4,5} p4 = {5,6,7,8,9} print(p3&p4) #output: {5} print(p3.intersection(p4)) #output: {5} #difference of sets: - operator OR difference() p5 = {1,2,3,4,5} p6 = {5,6,7,8,9} print(p5-p6) #output: {1, 2, 3, 4} print(p6-p5) #output: {8, 9, 6, 7} print(p6.difference(p5)) #output: {8, 9, 6, 7} #symmetric difference: ^ p7 = {1,2,3,4,5} p8 = {5,6,7,8,9} print(p7^p8) #output: {1, 2, 3, 4, 6, 7, 8, 9} print(p7.symmetric_difference(p8)) #output: {1, 2, 3, 4, 6, 7, 8, 9} #set - In built methods: #1. add(): s1 = {"Java", "Python", "C"} s1.add("Perl") print(s1) #output: {'Perl', 'C', 'Python', 'Java'} #2.update(): s2 = {"Java", "Python", "C"} s2.update(["perl", "ruby"]) #updating using list print(s2) #output: {'C', 'Java', 'ruby', 'Python', 'perl'} s2.update(("JS", "C++")) #updating using tuple print(s2) #output: {'perl', 'ruby', 'Java', 'C', 'Python', 'C++', 'JS'} #3. clear(): s2.clear() print(s2) #output: set() #4. copy(): lang = {"Java", "Python", "C"} lang1 = lang.copy() print(lang1) #ouptut: {'Java', 'C', 'Python'} #5. discard(): lang = {"Java", "Python", "C"} lang.discard("C") print(lang) #ouptput: {'Python', 'Java'} lang.discard("Sandeep") print(lang) #ouptput: {'Python', 'Java'} #6. remove(): student = {"Tom", "steve", "Peter"} student.remove("Tom") print(student) #output: {'steve', 'Peter'} # student.remove("Symond") # print(student) #output: KeyError: 'Symond'
true
e6270e723cfdb8d2895bb82a66b9fce05f3dfecc
soyolee/someLer
/euler/euler_009_Special_Pythagorean_triplet.py
1,729
4.15625
4
__author__ = "chlee" import sys import math ''' #Problem 9 A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a^2 + b^2 = c^2 For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. ''' try: if __name__ == "__main__": a = 1 b = 1 c = 1 biggest = 0 temp_a, temp_b, temp_c = 0, 0, 0 # print math.pow(2, 2) while a + b + c <= 1000: print "a :", a a = a + 1 for i in xrange(a, 1000): if biggest > (math.pow(a, 2) + math.pow(i, 2)): pass else: for j in xrange(a + b, 1000): if a + i + j == 1000: if math.pow(j, 2) > biggest: if math.pow(a, 2) + math.pow(i, 2) == math.pow(j, 2): print "\t\t%s + %s = %s" % (a, i, j) print "\t\t\t%s + %s = %s" % (math.pow(a, 2), math.pow(i, 2), math.pow(j, 2)) temp_a = a temp_b = i temp_c = j b = i c = j biggest = (math.pow(j, 2)) print "%s + %s + %s = %s" % (temp_a, temp_b, temp_c, (temp_a + temp_b + temp_c)) print "%s + %s = %s" % (math.pow(a, 2), math.pow(b, 2), math.pow(a + b, 2)) print "biggest : %s" % biggest print "abc = %s" %(temp_a * temp_b * temp_c) except Exception, details: print details
false
c4bd3a327087bdc0795e06d4c4125f93ed315255
chaita18/Python
/Programms/check_multiply_by_16.py
233
4.1875
4
#!C:/Users/R4J/AppData/Local/Programs/Python/Python37-32 num = eval(input("Enter number to check if it is multiply by 16 : ")) if (num&15)==0 : print("The number is multiple of 16") else : print("The number is not multiple of 16")
true
bc8069602e13e364e7ad656ed67b04f81f45f9ab
chaita18/Python
/Programms/check_multiple_by_any_number.py
298
4.1875
4
#!C:/Users/R4J/AppData/Local/Programs/Python/Python37-32 num = eval(input("Enter number : ")) multiplier = eval(input("Enter multiplier : ")) if (num&multiplier-1)==0 : print("The number %d is multiple of %d"%(num,multiplier)) else : print("The number %d is not multiple of %d"%(num,multiplier))
true
6e4c88b8ac4cbcfeb167765e6aae299067db8b24
TomchenEDG/LeetCode
/12.232. Implement Queue using Stacks.py
1,553
4.40625
4
#!/usr/bin/env python # -*- coding:utf-8 -*- class MyQueue: def __init__(self): """ defInitialize your data structure here. """ # 初始化两个列表,当作栈来使用 self.stack_in = [] self.stack_out = [] def push(self, x): """ Push element x to the back of queue. """ # 队列的push操作 self.stack_in.append(x) def pop(self): """ Removes the element from in front of queue and returns that element. """ # 队列的pop操作 if self.stack_out: return self.stack_out.pop() else: # 将stack-in的数据全部push进stack-out中,然后stack_out的顺序和队列pop的顺序一致 while self.stack_in: self.stack_out.append(self.stack_in.pop()) return self.stack_out.pop() def peek(self): """ Get the front element. """ if self.stack_out: return self.stack_out[-1] else: while self.stack_in: self.stack_out.append(self.stack_in.pop()) return self.stack_out[-1] def empty(self): """ Returns whether the queue si empty. """ return not self.stack_in and not self.stack_out def main(): queue = MyQueue() queue.push(1) queue.push(2) queue.peek() queue.pop() queue.empty() if __name__ == '__main__':main()
false
c626414f3ea6fd8a358b8be7d66f8c3c6a9bb387
moyinmi/beginner-project-solution
/triplechecker.py
381
4.375
4
def triple_checker(): while True: a = int(input("Enter a side: ")) b = int(input("Enter a side: ")) c = int(input("Enter a side: ")) h = max(a, b, c) if (a**2) + (b**2) == (h**2): print("Triangle is a pythagorean triple") else: print("triangle is not a pythagorean tripple") triple_checker()
false
a20e4cd321b23d2b35abbe8233fca1c1e52cc410
TechnologyTherapist/BasicPython
/02_var_datatype.py
396
4.15625
4
# innilize a value of data types a=10 b='''hi am akash iam good boy''' c=44.4 d=True e=None # Now print the varaible value print(a) print(b) print(c) print(d) print(e) #now using type function to find data type of varaible print(type(a)) print(type(b)) print(type(c)) print(type(d)) print(type(e)) #now i use how to find a lenght data type so i can use len function to find lenght print(len(b))
true
18281b137fad3eae028f4888a19b066627403125
axeMaltesse/Python-related
/Learning-Python/anti_vowel_v2.py
395
4.15625
4
#definition def anti_vowel(text): #value to hold new string b = '' #for loop to chceck single letter for a in range(len(text)): #if the letter is in that string, do nothing; continue if (text[a] in "aeiouAEIOU"): continue #add to the string else: b += text[a] return b print anti_vowel("Asado qwe Oirjan qw eanf tuc")
true
0156518036d2d08de0d6a6635c3a9ecf5146bf6d
lovit/text_embedding
/text_embedding/.ipynb_checkpoints/fasttext-checkpoint.py
688
4.125
4
def subword_tokenizer(term, min_n=3, max_n=6): """ :param term: str String to be tokenized :param min_n: int Minimum length of subword. Default is min_n = 3 :param max_n: int Minimum length of subword. Default is max_n = 6 It returns subwords: list of str It contains subword of "<term>". '<' and '>' are special symbol that represent begin and end of term. First element is '<' and '>' attached term """ term_ = '<%s>' % term len_ = len(term_) subwords = [term_[b:b+n] for n in range(min_n, max_n + 1) for b in range(len_ - n + 1)] subwords.insert(0, term_) return subwords
true
af90f9d14f0800526910d3c2c3fbb9356f3f564b
RaphaelPereira88/weather-report
/weather.py
2,445
4.125
4
import requests API_ROOT = 'https://www.metaweather.com' API_LOCATION = '/api/location/search/?query=' API_WEATHER = '/api/location/' # + woeid def fetch_location(query): return requests.get(API_ROOT + API_LOCATION + query).json() # convert data from json text to python dictionary accordint to user input. def fetch_weather(woeid): return requests.get(API_ROOT + API_WEATHER + str(woeid)).json() # ask city name to get WOEID and use it to get weather data def disambiguate_locations(locations): # help find city if city name not fully typed print("Ambiguous location! Did you mean:") for loc in locations: print(f"\t* {loc['title']}") def display_weather(weather): # function that displays the weather for the 6 coming days, loop print(f"Weather for {weather['title']}:") for entry in weather['consolidated_weather']: date = entry['applicable_date'] high = entry['max_temp'] low = entry['min_temp'] state = entry['weather_state_name'] print(f"{date}\t{state}\thigh {high:2.1f}°C\tlow {low:2.1f}°C") def weather_dialog(): try: # try except to avoid system crash, a tell the user the user the reason. where = '' while not where: where = input("Where in the world are you? ") # ask user what city they are in . input locations = fetch_location(where) # help find city if city name not fully typed if len(locations) == 0: print("I don't know where that is.") elif len(locations) > 1: disambiguate_locations(locations) else: woeid = locations[0]['woeid'] #use Woeid to get weather data display_weather(fetch_weather(woeid)) # display the weather except requests.exceptions.ConnectionError: # to avoir system crash si server not responding per example. here we use try ... except print("Couldn't connect to server! Is the network up?") if __name__ == '__main__': while True: weather_dialog()
true
1f31d271aac9c0d58683fd3b6401b1d37a706fb6
tooreest/ppkrmn_gbu_pdf
/python_algorithm/l01/examples/times_compare/task_1.py
964
4.3125
4
""" Вычисление суммы первых n целых чисел """ def get_sum_1(n): """ В основе идеи алгоритма - переменная-счетчик, инициализируемая нулем и к которой в процессе решения задачи прибавляются числа, перебираемые в цикле :param n: :return: """ res = 0 for i in range(1, n + 1): res = res + i return res print(get_sum_1(10)) def get_sum_2(obj): """ Текущее решение является неудачным из-за избыточного присваивания, а также неудачного выбора имен переменных :param obj: :return: """ var = 0 for part in range(1, obj + 1): dec = part var = var + dec return var print(get_sum_2(10))
false
0edb1bcc113319362b8373404d583c9a278e935f
tooreest/ppkrmn_gbu_pdf
/pyhton_basic/q01l04/task_06.py
1,247
4.15625
4
#! ''' Geekbrains. Факультет python-разработки Четверть 1. Основы языка Python Урок 4. Функции Домашнее задание 6. Реализовать два небольших скрипта: а) бесконечный итератор, генерирующий целые числа, начиная с указанного, б) бесконечный итератор, повторяющий элементы некоторого списка, определенного заранее. Подсказка: использовать функцию count() и cycle() модуля itertools. ''' from itertools import count from itertools import cycle start = 3 end = 17 numlist = [] for i in count(start): if i < end: numlist.append(i) else: break result = [] num_of_element = len(numlist)*3 for i in cycle(numlist): if num_of_element > 0: result.append(i) num_of_element -= 1 else: break print(f'Список чисел, сгенерированный с помощью count():\n{numlist}') print(f'Список чисел, сгенерированный из первого с помощью cycle():\n{result}') print('Bye!!!')
false
1faac741cb2dc5e859673a87df828aed84eaa06f
tooreest/ppkrmn_gbu_pdf
/pyhton_basic/q01l04/task_02.py
801
4.125
4
#! ''' Geekbrains. Факультет python-разработки Четверть 1. Основы языка Python Урок 4. Функции Домашнее задание 2. Представлен список чисел. Необходимо вывести элементы исходного списка, значения которых больше предыдущего элемента. Подсказка: элементы, удовлетворяющие условию, оформить в виде списка. Для формирования списка использовать генератор. ''' numlist = [12, 125, 1548 , 1, -16, 23.156, -45.23, -3, 11] result = [numlist[i] for i in range(1, len(numlist)) if numlist[i] > numlist[i-1]] print(result) print('Bye!!!')
false
d9657392a98a7f268a2b61e130158a6825765adf
tooreest/ppkrmn_gbu_pdf
/python_algorithm/l01/examples/structures_examples/stack/task_12.py
1,601
4.15625
4
"""Пример создания стека через ООП""" class StackClass: def __init__(self): self.elems = [] def is_empty(self): return self.elems == [] def push_in(self, el): """Предполагаем, что верхний элемент стека находится в начале списка""" self.elems.insert(0, el) def pop_out(self): return self.elems.pop(0) def get_val(self): return self.elems[0] def stack_size(self): return len(self.elems) SC_OBJ = StackClass() print(SC_OBJ.is_empty()) # -> стек пустой # наполняем стек SC_OBJ.push_in(10) SC_OBJ.push_in('code') SC_OBJ.push_in(False) SC_OBJ.push_in(5.5) # получаем значение первого элемента с вершины стека, но не удаляем сам элемент из стека print(SC_OBJ.get_val()) # -> 5.5 # узнаем размер стека print(SC_OBJ.stack_size()) # -> 4 print(SC_OBJ.is_empty()) # -> стек уже непустой # кладем еще один элемент в стек SC_OBJ.push_in(4.4) # убираем элемент с вершины стека и возвращаем его значение print(SC_OBJ.pop_out()) # -> 4.4 # снова убираем элемент с вершины стека и возвращаем его значение print(SC_OBJ.pop_out()) # -> 5.5 # вновь узнаем размер стека print(SC_OBJ.stack_size()) # -> 3
false
b84ab2f45e8a33db98518c3b888f6447ac46040a
goosegoosegoosegoose/springboard
/python-ds-practice/33_sum_range/sum_range.py
922
4.125
4
def sum_range(nums, start=0, end=None): """Return sum of numbers from start...end. - start: where to start (if not provided, start at list start) - end: where to stop (include this index) (if not provided, go through end) >>> nums = [1, 2, 3, 4] >>> sum_range(nums) 10 >>> sum_range(nums, 1) 9 >>> sum_range(nums, end=2) 6 >>> sum_range(nums, 1, 3) 9 If end is after end of list, just go to end of list: >>> sum_range(nums, 1, 99) 9 """ if end == None: lst = nums[start:] elif end != None: lst = nums[start:end+1] sum = 0 for num in lst: sum = sum + num return sum # definitely feel like theres a shorter way to see if end is None or not # maybe not # can use is instead of == # can't seem to use not instead of != when pertaining to None though
true
c8eff632a0146b35ed1c97c43501956c63ae8046
goosegoosegoosegoose/springboard
/python-syntax/in_range.py
572
4.34375
4
def in_range(nums, lowest, highest): """Print numbers inside range. - nums: list of numbers - lowest: lowest number to print - highest: highest number to print For example: in_range([10, 20, 30, 40], 15, 30) should print: 20 fits 30 fits """ nums.sort() nums_range = range(nums[0], nums[-1]) low_msg = f"{lowest} fits" if lowest in nums_range else "" high_msg = f"{highest} fits" if highest in nums_range else "" print(low_msg) print(high_msg) in_range([10, 20, 30, 40, 50], 15, 30)
true
912382a53ecbdf760a14c7b372c14df45d558f42
ly989264/Python_COMP9021
/Week2/lab_1_1_Temperature_conversion_tables.py
418
4.28125
4
''' Prints out a conversion table of temperatures from Celsius to Fahrenheit degrees, the former ranging from 0 to 100 in steps of 10. ''' # Insert your code here start_celsius=0 end_celsius=100 step=10 print('Celsius\tFahrenheit') for item in range(start_celsius,end_celsius+step,step): celsius=item fahrenheit=int(celsius*1.8+32) #print('%7d\t%10d' %(celsius,fahrenheit)) print(f'{celsius:7}\t{fahrenheit:10}')
true
4ece48f5629219360d3cd195c0242f4e67805104
imscs21/myuniv
/1학기/programming/basic/파이썬/파이썬 과제/11/slidingpuzzle.py
2,053
4.125
4
# Sliding Puzzle import random import math def get_number(size): num = input("Type the number you want to move (Type 0 to quit): ") while not (num.isdigit() and 0 <= int(num) <= size * size - 1): num = input("Type the number you want to move (Type 0 to quit): ") return int(num) def create_board(numbers): size = int(math.sqrt(len(numbers))) board = [] for i in range(size): k = i * size board.append(numbers[k : k+size]) return board def create_init_board(size): numbers = list(range(size * size)) random.shuffle(numbers) return create_board(numbers) def create_goal_board(size): numbers = list(range(size * size)) numbers = numbers[1:] numbers.append(0) return create_board(numbers) def print_board(board): for row in board: for item in row: if item == 0: print(" ", end=" ") else: print(str(item).rjust(2), end=" ") print() def find_position(num, board): for i in range(len(board)): for j in range(len(board)): if num == board[i][j]: return (i, j) def move(pos, empty, board): (i, j) = pos if empty == (i-1, j) or empty == (i+1, j) or \ empty == (i, j-1) or empty == (i, j+1): board[empty[0]][empty[1]] = board[i][j] board[i][j] = 0 return (pos, board) else: print("Can't move! Try again.") return (empty, board) def sliding_puzzle(size): board = create_init_board(size) goal = create_goal_board(size) empty = find_position(0, board) while True: print_board(board) if board == goal: print("Congratulations!") break num = get_number(size) if num == 0: break pos = find_position(num, board) (empty, board) = move(pos, empty, board) print("Please come again.") def main(): import sys size = sys.argv[1] if size.isdigit() and int(size) > 1: sliding_puzzle(int(size)) else: print("Not a proper system argument.") main()
true
a41d8b1e58f7c92013a67d53fdf9aee4c169c07d
foqiao/A01027086_1510
/lab_09/factorial.py
1,301
4.15625
4
import time """ timer function store the procedures needed for time consumes during factorial calculations happened on two different methods. """ def timer(func): def wrapper_timer(*args, **kwargs): start_time = time.perf_counter() value = func(*args, **kwargs) end_time = time.perf_counter() run_time = end_time - start_time answer = f"{func.__name__!r} in {run_time:.4f}s" filename = 'result.txt' with open(filename, 'w') as project: project.write(answer) return wrapper_timer @timer def factorial_iterative(value): """ plain loop to calculate the factorial :param value: input value from main function :return: result returned after calculations finished """ global product for i in range(1, value + 1, 2): if i < value: product = i * (i + 1) result = product ** (value / 2) return result def factorial_recursive(value): """ recursive way to calculate factorial :param value: value from main function :return: result return after calculation finished """ def main(): value = int(input("Please enter a positive number from 1 to 100: ")) factorial_iterative(value) factorial_recursive(value) if __name__ == '__main__': main()
true
ecb18199f9d45503e9585a723350d3d8c01c1d03
foqiao/A01027086_1510
/midterm_review/most_vowels.py
899
4.21875
4
def most_vowels(tuple): vowel_in_tuple = [] vowel_rank = set() vowel_amount = 0 tuple_of_string = range(0, len(tuple)) for i in tuple_of_string: if tuple[i] == ',': vowel_in_tuple.append(" ") if tuple[i] == 'a': vowel_in_tuple.append(tuple[i]) if tuple[i] == 'e': vowel_in_tuple.append(tuple[i]) if tuple[i] == 'i': vowel_in_tuple.append(tuple[i]) if tuple[i] == 'o': vowel_in_tuple.append(tuple[i]) if tuple[i] == 'u': vowel_in_tuple.append(tuple[i]) for j in range(0, len(vowel_in_tuple)): if vowel_in_tuple[j] != " ": vowel_amount += 1 if vowel_in_tuple[j] == " ": vowel_rank.add(vowel_amount) tuple_input = tuple(input("Please enter a combination of strings(must separated by comma): ")) most_vowels(tuple_input)
false
b8dc36c78448c0e58abcf2fffd77cb20dee69d2f
CINick72/project_euler
/pe9.py
548
4.21875
4
""" A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a^2 + b^2 = c^2 For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc """ done = False for a in range(500): for b in range(500): c = 2 * a * b - 2 * a * 1000 - 2 * b * 1000 + 1000 * 1000 if c == 0: done = True break if done: break c = 1000 - a - b print(a) print(b) print(c) print(a * a + b * b - c * c) print(a * b * c)
false
3166baaa4c08d4d7eca67acd85aa03d7dd6b253c
amshekar/python-mania
/day2/Classself.py
812
4.15625
4
students = [] class Student: school_name="UPS" #constructor self is equal to this in other languages def __init__(self,name,student_id=332): self.name=name self.student_id=student_id students.append(self) # constructor to get rid of returning student object memory reference when we print below will overide that and return custom one def __str__(self): return "Student " +self.name def get_name_capitalized(self): return self.name.capitalize() def get_school_name(self): return self.school_name #creating instance and accessing shekar=Student("gadamoni",48) print(shekar) print(shekar.get_school_name()) print(shekar.get_name_capitalized()) #class variable accessing without creating instance print(Student.school_name) print(students)
true
0f0b07648567d31d44f309d19661c8c7a4f191f0
xuting1108/Programas-de-estudo
/pdf_Bia/lista12_Bia/4.py
758
4.125
4
# Crie uma função que recebe uma lista de strings e # a. retorne o elemento com mais caracteres # b. retorne a média de vogais nos elementos (  no de vogais de cada elemento/no de # elementos) # c. retorne o número de ocorrências do primeiro elemento da lista # d. retorne a palavra lexicograficamente maior # e. conte o número de ocorrências de palavras compostas # f. retorne a quantidade de vizinhos iguais # DESAFIO: exiba todas as sublistas de 2 elementos possíveis #def recebe_lista(): lista = [] cont = 1 maior = 0 elementos = int(input('insira quantos elementos terão na lista: ')) while cont <= elementos: x = input(f'insira o {cont}º elemento da lista: ') if len(x) > maior: maior = x lista.append(x) cont+=1
false
defcb65c2bf687a8b6fc60b34bad34ae87884771
xuting1108/Programas-de-estudo
/exercicios-pythonBrasil/estrutura-de-repeticao/ex3.py
1,343
4.15625
4
# Faça um programa que leia e valide as seguintes informações: # Nome: maior que 3 caracteres; # Idade: entre 0 e 150; # Salário: maior que zero; # Sexo: 'f' ou 'm'; # Estado Civil: 's', 'c', 'v', 'd'; nome = '' idade = 0 salario = 0 sexo = '' relacionamento = '' while True: nome = input('informe seu nome: ') idade = int(input('informe sua idade: ')) salario = float(input('informe seu salario: ')) sexo = input('informe qual seu sexo--> M-Masculino ou F-Feminino: ') relacionamento = input('informe seu estado civil--> S-Solteiro(a), C-Casado(a), V-Viuva(a), D-Divorciado(a): ') if len(nome)<=3: print('informe um nome com mais de 3 caracteres') break elif idade < 0 or idade > 150: print('a idade tem que ser maior que 0 e menor que 150') elif salario <= 0: print('o salario tem que ser maior que 0') elif sexo.lower() != 'm' and sexo.lower() != 'f': print('M-Masculino ou F-Feminino') elif relacionamento.lower() != 's' and relacionamento.lower() != 'c' and relacionamento.lower() !='v' and relacionamento.lower() !='d': print('estado civil--> S-Solteiro(a), C-Casado(a), V-Viuva(a), D-Divorciado(a)') else: break print(f'Nome: {nome.upper()}') print(f'Idade: {idade}') print(f'Salario: {salario}') print(f'Sexo: {sexo.upper()}') print(f'Estado-civil: {relacionamento.upper()}')
false
2dcc4ae4feeaebade03f571ec4d09b7ce5b5d9fe
xuting1108/Programas-de-estudo
/exercicios-pythonBrasil/estrutura-de-decisao/ex8.py
416
4.15625
4
# Faça um programa que pergunte o preço de três produtos e informe qual produto você deve comprar, sabendo que a decisão é sempre pelo mais barato. p1 = float(input('informe o preço do primeiro produto: ')) p2 = float(input('informe o preço do segundo produto: ')) p3 = float(input('informe o preço do terceiro produto: ')) lista = [p1,p2,p3] print(f'Voce deve comprar o produto que custa {min(lista)} ')
false
8abfcad9dd32c44cdca5763e06c682bddb67cb04
xuting1108/Programas-de-estudo
/python-para-zumbis/lista1/exercicio7.py
251
4.25
4
#Converta uma temperatura digitada em Celsius para Fahrenheit. F = 9*C/5 + 32 graus_celsius = float(input('Informe a temperatura em graus Celsius: ')) fahrenheit = (9 * graus_celsius) / 5 + 32 print(f'A temperatura em fahrenheit é: {fahrenheit}')
false
70d92acdff6f98f03cd5fab21d7ca7a3bdbfa335
xuting1108/Programas-de-estudo
/exercicios-pythonBrasil/estrutura-de-decisao/ex5.py
611
4.125
4
#Faça um programa para a leitura de duas notas parciais de um aluno. O programa deve calcular a média alcançada por aluno e apresentar: # A mensagem "Aprovado", se a média alcançada for maior ou igual a sete; # A mensagem "Reprovado", se a média for menor do que sete; # A mensagem "Aprovado com Distinção", se a média for igual a dez. n1 = float(input('informe a primeira nota: ')) n2 = float(input('informe a segunda nota: ')) media = (n1 + n2) / 2 if media < 7: print('REPROVADO') elif media >= 7 and media < 10: print('Aprovado') else: print('*****APROVADO COM DISINCAO*****')
false
09494afbe608c3b8d1f67a86fba3e6ab2f800d63
xuting1108/Programas-de-estudo
/exercicios-pythonBrasil/Listas/11.py
454
4.125
4
#Altere o programa anterior, intercalando 3 vetores de 10 elementos cada. l1 = ['fernanda', 'roberta', 'lucas', 'elzi', 'filipe', 'igor', 'katia', 'pedro', 'thiago', 'bia'] l2 = [1,6, 9, 15, 16, 12, 18, 25, 62, 84] l3 = ['Macaco', 'Galo', 'Cão', 'Porco', 'Rato', 'Boi', 'Tigre', 'Coelho', 'Dragão', 'Serpente'] # l3.append(zip(l1,l2)) # print(l3) l4 = [] for x in zip(l1,l2,l3): l4.append(x[0]) l4.append(x[1]) l4.append(x[2]) print(l4)
false
427bef40fca68167da9a854640161e0078177702
yung-pietro/learn-python-the-hard-way
/EXERCISES/ex40.py
2,301
4.71875
5
# You can think of a module as a specialized dictionary, where I can store code # and access it with the . operator # Similarly, a Class is a way of taking a grouping of functions and data and place # them in a similar container so as to access with the . (dot) operator # The difference being, a module is used once, and a class is used to make many things, # including other classes or sub-classes. #If a class is like a mini-module, there has to be a concept similar to 'import' # That concept is called Instantiate - an obnoxious way of saying 'create' # When you Instantiate a class, you get an Object. You Instantiate / create a class # by calling the class like it's a function. class MyStuff(object): """docstring for MyStuff.""" def __init__(self): self.tangerine = "And now a thousand years between!" #Sets the tangerine instance variable def apple(self): print("I AM CLASSY APPLES!") #This is an apple function. What it does, I have no idea. # And then to instantiate the class, we call it like a function thing = MyStuff() thing.apple() print(thing.tangerine) # Python looks for MyStuff and sees it's a class we're definining # Python crafts an empty object with all the functions I've specified in the class using def # Python looks to see if we've used the magic __init__ function, and if so, calls the function to iniitialize the newly created Object # In the MyStuff function __init__, I get this extra variable, self - which is the # empty object that python made, and I can set variables on it, just like I would with a module, dictionary, or other Object # In this case, I set self .tangerine to a song lyric, and then I've initialized the Object # Now python can take this newly minted object and assign it to the thing variable to work with. #Remember that this is NOT giving us the class, but instead, using the class as a blueprint for building a copy of that type of thing. """" • Classes are like blueprints or definitions for creating new mini-modules. • Instantiation is how you make one of these mini-modules and import it at the same time. ”In- stantiate” just means to create an object from the class. • Theresultingcreatedmini-moduleiscalledanobject,andyouthenassignittoavariabletowork with it. ``` """"
true
b62110eca69bd06a29dac605b378d4a26e527f02
0x0584/cp
/nizar-and-grades.py
724
4.125
4
# File: nizar-and-grades.py # Author: Anas # # Created: <2019-07-10 Wed 09:08:32> # Updated: <2019-07-11 Thu 22:01:51> # # Thoughts: I was wrong! the idea is to give a count of how many grades # are between min and max # # D. #247588 def find_best(grades): unique = list(set(sorted(grades))) unique.remove(max(unique)) if len(unique) == 0: return 0 unique.remove(min(unique)) return len(unique) # print find_best([0, 3, 4, 1, 5, 1, 2, 5]) # print find_best([1, 2, 3, 4, 5]) n_tests = int(input()) tests = [] for t in range(n_tests): tests.append([int(input()), map(int, raw_input().split())]) for t in tests: print find_best(t[1])
true
44dd93465f283d91d89d3a02b12a0c9dae91bb9f
irrlicht-anders/learning_python
/number_posneg.py
419
4.5625
5
# Program checks wether the number is negative # or not and displays an approbiate message # ------------------------------------------------ # added additional line whicht checks wether the # input is zero OR negative num = input("Please enter a postive or negative number! ") a = int(num) #convert from string to int if a > 0: print("Postive or Zero") elif num == 0: print("Zero") else: print("Negative number")
true
a4ca15cb046c26c2c539eadf741c63aa44eb43c8
rubenhortas/shows_manager
/application/utils/time_handler.py
647
4.375
4
def print_time(seconds): """ __print_time(num_secs) Prints the time taken by the program to complete the moving task. Arguments: seconds: (int) Time taken by the program in seconds.s """ string_time = "" hours = int(seconds / 3600) if hours > 0: seconds = seconds(3600 * hours) string_time = "{0}h".format(hours) minutes = int(seconds / 60) if minutes > 0: seconds = seconds(60 * minutes) string_time = "{0} {1}m".format(string_time, minutes) string_time = "{0} {1:.2f}s".format(string_time, seconds) print("\n\n{0}\n".format(string_time.strip()))
true
aa72775b408ea78214f4e9f7f3e85c6bde6a397e
bobmitch/pythonrt
/polynomials.py
1,095
4.125
4
# Newton's method for polynomials import copy def poly_diff(poly): """ Differentiate a polynomial. """ newlist = copy.deepcopy(poly) for term in newlist: term[0] *= term[1] term[1] -= 1 return newlist def poly_apply(poly, x): """ Apply a value to a polynomial. """ sum = 0.0 # force float for term in poly: sum += term[0] * (x ** term[1]) return sum def poly_root(poly, start, n, r_i): """ Returns a root of the polynomial, with a starting value. To get both roots in a quadratic, try using with n = 1 and n = -1.""" poly_d = poly_diff(poly) x = start counter = 0 while True: if (n >= 0) and (n < 1): break x_n = x - (float(poly_apply(poly, x)) / poly_apply(poly_d, x)) if x_n == x: break x = x_n n -= 1 counter += 1 if r_i: return [x, counter] else: return x
true
c1c1cff04003b75dc832d56511c0b3a467ecc59d
kiransy015/PythonProjectFlipkart
/com/org/comp/Pgm45B.py
719
4.25
4
class circle: pie = 3.142 def __init__(self,r): self.radius = r def area_of_circle(self): area = circle.pie*self.radius*self.radius print("Area of a circle is",area) def circ_of_circle(self): circ = 2*circle.pie*self.radius print("Crc of circle is",circ) def diameter_of_circle(self): diameter = 2*self.radius print("Diameter of circle is",diameter) print("---------------------------") c1 = circle(3.5) c1.area_of_circle() c1.circ_of_circle() c1.diameter_of_circle() c2 = circle(4.5) c2.area_of_circle() c2.circ_of_circle() c2.diameter_of_circle() c3 = circle(5.5) c3.area_of_circle() c3.circ_of_circle() c3.diameter_of_circle()
false
1433cab8476daf733f6a9ce32e499302bae5ecdb
Md-Hiccup/python-DS
/Linked-List/delete.py
1,216
4.15625
4
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node def printList(self): temp = self.head while(temp): print(temp.data, end=" => ") temp = temp.next def deleteNode(self, key): temp = self.head if(temp is not None): if(temp.data == key): self.head = temp.next temp = None return while(temp is not None): if( temp.data == key): break prev = temp temp = temp.next if(temp == None): return prev.next = temp.next if __name__ == '__main__': llist = LinkedList() llist.push(6) llist.push(3) llist.push(4) llist.push(1) # It print the 1 => 4 => 3 => 6 print("List before deletion: ") llist.printList() llist.deleteNode(3) # Deleting node 3 print("\nList after deleting 3") llist.printList()
false
9f12127bc115ea0c20b9cfb26eac5bb26eda4a7b
Steveno95/Whiteboard-Pairing-Problems
/Balanced Binary Tree/balancedBinaryTree.py
1,350
4.34375
4
# write a function that checks to see if a given binary tree is perfectly balanced, meaning all leaf nodes are located at the same depth. # Your function should return true if the tree is perfectly balanced and false otherwise. def checkBalance(root): # An empty tree is balanced by default if root == None: return True # recursive helper function to help check the min depth of the tree def minDepth(node): if node == None: return 0 return 1 + min(minDepth(node.left), minDepth(node.right)) # recursive helper function to help check the max depth of the three def maxDepth(node): if node == None: return 0 return 1 + max(maxDepth(node.left), maxDepth(node.right)) return maxDepth(root) - minDepth(root) == 0 class BinaryTreeNode: def __init__(self, value): self.value = value self.left = None self.right = None def insertLeft(self, value): self.left = BinaryTreeNode(value) return self.left def insertRight(self, value): self.right = BinaryTreeNode(value) return self.right root = BinaryTreeNode(5) print(checkBalance(root)) # should print true root.insertLeft(10) print(checkBalance(root)) # should print false root.insertRight(11) print(checkBalance(root)) # should print true
true
b16d2082327d3845fdfe46955c71c4620e1f2711
khushali19/Py-assign1
/A6.py
297
4.125
4
list1 = [] list2 = [] list3 = [] for n in range(1,21): list1.append(n) print("Main list ",list1) for i in list1: if (i % 2 == 0): list2.append(i) else: list3.append(i) print("Even list ", list2) print("Odd list ", list3)
false
5fab35331ecd4a0319d3391f4a90639b900b3894
Jimam-Tamimi/Basic-Python-Programs
/rock_sizer_paper_game.py
1,834
4.5
4
import random # print(randNo) # For comp 1 is rock 2 is Scissor and 3 is paper # The computer is choosing randNo = random.randint(1,3) if randNo == 1: comp = 'rock' elif randNo == 2: comp = 'Scissor' elif randNo == 3: comp = 'paper' # print(comp) # Function for player # 1 = rock 2 = Scissor, 3 = paper def player(play): if play == 'r' and comp == 'rock': play= 'Rock' return 0 elif play == 's' and comp == 'Scissor': play = 'Scissor' return 0 elif play == 'p' and comp == 'paper': play = 'Paper' return 0 elif play == 'r' and comp == 'Scissor': play == 'Rock' return 1 elif play == 'r' and comp == 'paper': play == 'Rock' return -1 elif play == 's' and comp == 'rock': play = 'Scissor' return -1 elif play == 's' and comp == 'paper': play = 'Scissor' return 1 elif play == 'p' and comp == 'rock': play = 'Paper' return 1 elif play == 'p' and comp == 'Scissor': play = 'Paper' return -1 else: return None # Taking and Making the name beautiful inp = input("Enter 'r' (Rock) or 's' (Scissor) or 'p' (Paper): ") play = player(inp) if inp == 'r': input_by_the_user = 'Rock' elif inp == 's': input_by_the_user = 'Scissor' elif inp == 'p': input_by_the_user = 'Paper' input_by_the_computer = comp.capitalize() # Printing the result... if play == 0: print(f'Computer choose {input_by_the_computer} and you choose {input_by_the_user}. Game draw') elif play == 1: print(f'Computer choose {input_by_the_computer} and you choose {input_by_the_user}. You won') elif play == -1: print(f'Computer choose {input_by_the_computer} and you choose {input_by_the_user}. You loose') else: print("Invlaid Input!!! ")
false
85573993f237c888ad1f7e84e1a641c0ad7771d6
aritse/practice
/Unique Paths II.py
1,771
4.1875
4
# A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). # The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). # Now consider if some obstacles are added to the grids. How many unique paths would there be? class Solution(object): def uniquePathsWithObstacles(self, obstacleGrid): """ Observation: swapping the start and end points should yield the same number of unique paths. 1. Initialize the first row such that if there is an obstacle on it, then the cells before the obstacle are initialized with 1 and the cells after the obstacle (including the obstacle) are initialized with None. 2. Initialize the first column in the same manner as above. """ # Initialization rows, cols = len(obstacleGrid), len(obstacleGrid[0]) obstacle = False for i in range(cols): if obstacleGrid[0][i]: obstacle = True if obstacle: obstacleGrid[0][i] = 1 obstacle = False for i in range(rows): if obstacleGrid[i][0]: obstacle = True if obstacle: obstacleGrid[i][0] = 1 for i in range(rows): for j in range(cols): obstacleGrid[i][j] = 0 if obstacleGrid[i][j] else 1 # bottom-up for i in range(1, rows): for j in range(1, cols): if obstacleGrid[i][j]: obstacleGrid[i][j] = obstacleGrid[i][j-1] + \ obstacleGrid[i-1][j] return obstacleGrid[rows-1][cols-1]
true
2af620754b574963a8a7375553d0897e40c4827c
wenqianli150/hello-world
/palindrome.py
753
4.1875
4
""" Name: Wenqian Li UWNetId: wli6 TimeComplexity = O(n) """ """ Evaluates a given string and determines whether or not it is a palindrome. :param the_string: The string to evaluate. :returns: True when the string is a palindrome, False otherwise. """ def is_palindrome(the_string): # Run loop from 0 to len/2 the_string = the_string.replace(' ', "") for i in range(0, int(len(the_string) / 2)): if the_string[i].lower() != the_string[len(the_string) - i - 1].lower(): return False return True # main function while True: s = input('Your string is: ') if s == 'quit': break answer = is_palindrome(s) if answer: print("Ture") else: print("False")
true
f7fd9c14a1461203b376746528c2a1b0b365d3b7
souvikhaldar/Data-Structures-in-Python-and-Go
/recursion/printFromNto1.py
603
4.28125
4
# Write a recursive function to print all numbers from N to 1 for a given number N. # tail recursion def printN(N): if N == 0: return print(N) printN(N-1) # Write a recursive function to print all numbers from 1 to N for a given number N. #head recursion def print_one_to_n(N): if N == 0: return print_one_to_n(N-1) print(N) #tail recursion def tailPrint(n,i=1): if n == 0: return print(i) tailPrint(n-1,i+1) N = int(input("Enter N:")) t = int(input("1. N to 1 or 2. 1 to N (1/2): ")) if t == 1: printN(N) else: tailPrint(N)
false
77617485ca3d6b3e799c5b242fc7154673ef2691
yuriyberezskyy/python-code-challege-loops
/code.py
1,843
4.375
4
# Create a function named exponents() that takes two lists as parameters named bases and powers. Return a new list containing every number in bases raised to every number in powers. # For example, consider th # Write your function here def exponents(lst1, lst2): new_list = [] for num1 in lst1: for num2 in lst2: new_list.append(num1**num2) return new_list # Uncomment the line below when your function is done print(exponents([2, 3, 4], [1, 2, 3])) # Create a function named larger_sum() that takes two lists of numbers as parameters named lst1 and lst2. # The function should return the list whose elements sum to the greater number. If the sum of the elements of each list are equal, return lst1. def larger_sum(lst1, lst2): sum1 = 0 sum2 = 0 for number in lst1: sum1 += number for number in lst2: sum2 += number if sum1 >= sum2: return lst1 else: return lst2 # Uncomment the line below when your function is done print(larger_sum([1, 9, 5], [2, 3, 7])) # Create a function named over_nine_thousand() that takes a list of numbers named lst as a parameter. # The function should sum the elements of the list until the sum is greater than 9000. When this happens, the function should return the sum. If the sum of all of the elements is never greater than 9000, the function should return total sum of all the elements. If the list is empty, the function should return 0. # For example, if lst was [8000, 900, 120, 5000], then the function should return 9020. # Write your function here def over_nine_thousand(lst): sum = 0 for number in lst: sum += number if (sum > 9000): break return sum # Uncomment the line below when your function is done print(over_nine_thousand([8000, 900, 120, 5000]))
true
05af06eabaf6395710df33a673938041e0e99ec3
Piinks/CSI_Python
/Exercises/Exercise17.py
1,399
4.1875
4
# Exercise 17 # Kate Archer # Program Description: This program reads a file name and the file’s contents # and determines the following: # 1) The number of alphabetic (upper and lower case) letters in the file # 2) The number of digits in the file # 3) The number of lines in the file # CSCI 1170-08 # November 12, 2015 def main(): fileName = get_File_Name() inFile = open(fileName, 'r') lineCount = 0; alphaCount = 0; digitCount = 0 for line in inFile: lineCount += 1 line = line.rstrip() for i in range (len(line)): if is_Alpha(line[i]): alphaCount += 1 if is_Digit(line[i]): digitCount += 1 inFile.close() print() print('The number of alphabetic characters is', alphaCount) print('The number of digits is', digitCount) print('The number of lines is', lineCount) def get_File_Name(): fileName = input('Enter the name of the file to open for read: ') try: open(fileName, 'r') return fileName except: print('An error occured.') get_File_Name() def is_Alpha(i): try: i = int(i) return False except: if i =='' or i==' ' or i== '.': return False else: return True def is_Digit(i): try: i = int(i) return True except: return False main()
true
407e1805d35d802fc9c319f454a215848c2a8731
Rokiis/Chat-Bot
/login_system.py
2,228
4.25
4
usernames = ['teacher','mentor','tutor','technican'] #storing usernames that (in theory) only uni staff has access to passwords = ['SecurePassword','password123','safepass','12345'] #storing passwords that (in theory) only uni staff has access to status = "" #set status to nill def login_menu(): #login function that checks if user is a student or teacher status = input("Are you a staff member(y/n)? ") #variable takes user input if status == "y": #if statements to check whether use is a student or a staff member (i.e. has login information) userTeacher() elif status == "n": userStudent() else: login_menu() #ensures that if an invalid character is entered the function will keep looping until right conditon is met def userStudent(): #takes user (student's) name and prints a welcome message student_name = input("\nWhat's your name?: ") print("Nice to meet you " + student_name) def userTeacher(): #asks user (teacher) to enter login details username = input("Enter your login name: ") password = input("Enter your passowrd: ") while username in usernames and password in passwords: #while statement checks if both conditions are met login_status = True print("Successfully logged in as a " + username) return login_status break #stops the infinite loop - since the statement is true, we need to brake after we send 'logged in successfully' message else: #if the while condition is false, sends to loginCheck function print("\nWrong password or username ") loginCheck() def loginCheck(): #asks user if he is a staff member login_check = input("Are you sure you are a staff member(y/n)?") if login_check == "y": #takes the user back to enter login details userTeacher() elif login_check == "n": #asks user for name userStudent() else: #if an invalid character is enterened, loops back the funtion until it satisfies one of the other 2 conditions print("That's not an option") loginCheck() login_menu() # this runs the login menu starting the login process
true
996be87ec1c34eafac76dd401dc6248b15b7d847
PrashantRBhargude/Python
/Dictionary.py
1,842
4.21875
4
#Dictionary allows us to work with key value pairs similar to hash maps in other prog languages #The values in the dictionary can be of any datatype Lead_Details={'Name':'Nikunj','Role':'ETL','Associates':['Prashant','Dixita']} print(Lead_Details['Associates']) #print(Lead_Details['Phone']) -- gives a key error print(Lead_Details.get('Phone')) #This will handle if an incorrect key is entered by giving an output as none, # but if second paramter is passed to the get function, then it will be displayed in output. See below print(Lead_Details.get('Phone','Incorrect Key')) #To add a key value pair to the exiting dictionary Lead_Details['Designation']='Consultant' print(Lead_Details) #To update the value of an exiting key Lead_Details['Associates']=['Prashant','Dixita','Prajakta'] print(Lead_Details) #Updating values using update function #useful to update multiple values in one shot Lead_Details.update({'Name':'Nikunj Shah','Role':'ETL Consultant'}) print(Lead_Details) #Deleting key and its value Lead_Details['NoOfReportings']=3 print(Lead_Details) del Lead_Details['NoOfReportings'] print(Lead_Details) #Another way to delete is using pop method, The deleted key value pair can be stored in a variable with pop method Deleted=Lead_Details.pop('Designation') print('Popped value from the dictionary') print(Deleted) #Looping through keys and values print('Length of the dictionary:' + str(len(Lead_Details))) print('Keys in the dictionary:' + str(Lead_Details.keys())) print('Values in the dictionary:' + str(Lead_Details.values())) print('Key and its value in pairs:' +str(Lead_Details.items())) print('Display all the keys in the dictionary:') for keys in Lead_Details: print(keys) print('Display all the keys and its value in the dictionary:') for keys,value in Lead_Details.items(): print(keys,value)
true
189d2878517aca5a838d14c0d72ef2fd120fb605
DJ-Watson/ICS3U-Unit3-01-Python
/adding.py
429
4.15625
4
#!/usr/bin/env python3 # Created by: DJ Watson # Created on: September 2019 # This program adds two numbers together def main(): # input number1 = int(input("type first number (integer): ")) number2 = int(input("type second number (integer): ")) # process answer = number1 + number2 # output print("") print("{} + {} = {}".format(number1, number2, answer)) if __name__ == "__main__": main()
true
aab6031fc2c812af2a147e574c1e8e748fb38e6a
BazzaOomph/Templates
/python/fundamentals/01_beginner/01_print.py
1,648
4.8125
5
#A basic print statement, which will print out the text string "Hello, World!" #The expected output to the console is "Hello, World!" and includes a New Line character at the end print("Hello, World!") #Printing using two separate arguments #The expected outcome is "Hello how are you?" with a new line character at the end. print("Hello", "how are you?") #Printing from variables #expected outcome is "apple banana cherry" with a new line character at the end. x = "apple" y = "banana" z = "cherry" print(x,y,z) #Printing from variables using a different separator. Normally the separator is " " #but we have changed this to be "***" instead. #expected outcome is "apple***banana***cherry" with a new line character at the end followed #by a second line of the same. (This aids with what's coming next) x = "apple" y = "banana" z = "cherry" print(x,y,z, sep="***") print(x,y,z, sep="***") #Printing from variables using a different separator AND removing the "end" character (so there is no new line) #expected outcome is "apple***banana***cherryapple***banana***cherry" x = "apple" y = "banana" z = "cherry" print(x,y,z, sep="***", end='') print(x,y,z, sep="***", end='') #Just printing an empty string so it puts in a new line character, that way the next bit of code #doesn't output onto the same line as the previous bit of code. print("") #Printing from variables using a different separator AND changing the "end" character (so there is no new line) #expected outcome is "apple***banana***cherry!apple***banana***cherry!" x = "apple" y = "banana" z = "cherry" print(x,y,z, sep="***", end='!') print(x,y,z, sep="***", end='!')
true
a0a02a0b72762241bf5a5a32cb7e59e696529ccb
code-lighthouse/tests
/sushi_store.py
587
4.125
4
#! /usr/bin/env python # Creating a list to hold the name of the itens shopping = ['fugu', 'ramen', 'sake', 'shiitake mushrooms', 'soy sauce', 'wasabi'] # Creating a dictionary to hold the price of the itens prices = {'fugu': 100.0, 'ramen': 5.0, 'sake': 45.0, 'shiitake mushrooms': 3.5, 'soy sauce': 7.50, 'wasabi': 10.0} # Loop 'for' to check the total # and list the products total = 0.00 for item in shopping: total += prices[item] for table in prices: print(table) print(("." * 37 + str(prices[table]))) print (('\t\t\tTotal = ' + str(total)))
true
3e8cf44f0c882fe70c5e83dc655108d109cc4b81
ssgantayat/cleaning-data-in-python
/1-exploring-your-data/06-visualizing-multiple-variables-with-boxplots.py
1,109
4.1875
4
''' Visualizing multiple variables with boxplots Histograms are great ways of visualizing single variables. To visualize multiple variables, boxplots are useful, especially when one of the variables is categorical. In this exercise, your job is to use a boxplot to compare the 'initial_cost' across the different values of the 'Borough' column. The pandas .boxplot() method is a quick way to do this, in which you have to specify the column and by parameters. Here, you want to visualize how 'initial_cost' varies by 'Borough'. pandas and matplotlib.pyplot have been imported for you as pd and plt, respectively, and the DataFrame has been pre-loaded as df. INSTRUCTIONS 100XP -Using the .boxplot() method of df, create a boxplot of 'initial_cost' across the different values of 'Borough'. -Display the plot. ''' # Import necessary modules import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv('../_datasets/dob_job_application_filings_subset.csv') # Create the boxplot df.boxplot(column='initial_cost', by='Borough', rot=90) # Display the plot plt.show()
true
9c0e414567cb96f9942edbfbbb6688fd8b28185a
arnabs542/DS-AlgoPrac
/twoPointers/countSubarrays.py
1,344
4.1875
4
"""Count Subarrays Problem Description Misha likes finding all Subarrays of an Array. Now she gives you an array A of N elements and told you to find the number of subarrays of A, that have unique elements. Since the number of subarrays could be large, return value % 109 +7. Problem Constraints 1 <= N <= 105 1 <= A[i] <= 106 Input Format The only argument given is an Array A, having N integers. Output Format Return the number of subarrays of A, that have unique elements. Example Input A = [1, 1, 3] Example Output 4 Example Explanation Subarrays of A that have unique elements only: [1], [1], [1, 3], [3] """ def solve(A): def helper(a,b): first = a*(a+1)//2 second = b*(b+1)//2 return first-second if len(A) <= 1: return len(A) dict_ = {} n = len(A) ans, i, index_, j = 0, 0, 0, 1 dict_[A[0]] = 0 while j < n: if A[j] not in dict_: dict_[A[j]] = j j += 1 elif dict_[A[j]] < index_: dict_[A[j]] = j j += 1 else: ans += helper(j-index_,i-index_) index_ = dict_[A[j]]+1 dict_[A[j]] = j i = j j += 1 ans += helper(j-index_,i-index_) return ans%(10**9+7)
true
d6c0ce60d39c532224a44cf1c423bffe359f5f44
eriktja/SEogT-oblig
/Leap_year/project/leap_year/main.py
270
4.40625
4
from is_leap_year import * print("This program will tell if you if a year is a leap year") year = int(input("Enter the year do you want to check: ")) if is_leap_year(year): print(str(year) + " is a leap year") else: print(str(year) + " is not a leap year")
true
70d71ef0d03cf708ec70da31211d8664833bffa2
hbreauxv/shared_projects
/simple_tests/whatsTheWord.py
201
4.21875
4
while True: word = input('Whats the word?') word = word.lower() if word != ('the bird'): continue else: print('The Bird Bird Bird, The Bird is the Word') break
true
542f107e72693592bbf1e253b06627f682a9ba73
MDCGP105-1718/portfolio-MichaelRDavis
/Python/Week 2/ex5.py
709
4.125
4
#Loop for number of bottles and print number of bottles for n in range(99, -1, -1): print("99 bottles of beer on the wall, 99 bottles of beer.") print(f"Take one down, pass it around, {n} bottles of beer on the wall…\n") #If number bottles equal to 1 print this message if(n == 1): print("1 bottle of beer on the wall, 1 bottle of beer!") print("So take it down, pass it around, no more bottles of beer on the") print("wall!") #If number bottles less than zero print this message elif(n == 0): print("No more bottles of beer on the wall, no more bottles of beer.") print("Go to the store and buy some more, 99 bottles of beer on the wall…")
true
e83794970b07265039880ed2d45869872ec25a7d
lbrindze/excercises
/ex6.py
1,691
4.1875
4
import math #ex 6.1 def compare(x,y): if x > y: return 1 elif x == y: return 0 else: return -1 #test functions print(compare(4,6)) print(compare(6,6)) print(compare(4,3)) #ex 6.2 (this is an exercise in incremental development. what you see is the final product) def hypotenuse(x,y): temp = math.sqrt(x**2 + y**2) return temp print(hypotenuse(3,4)) #6.7 def fibonacci (n): elif n == 0: return 0 elif n == 1: return 1 else: return n + fibonacci (n-1) #ex 6.5 def ack (m,n): if m == 0: return n + 1 if n == 0: return ack(m-1,1) return ack(m-1, ack(m,n-1)) print (ack(3,4)) #ex 6.6 def first(word): return word[0] def last(word): return word[-1] def middle(word): return word [1:-1] def is_palindrome(word): if len(word) <=1: return True if first(word) != last(word): return False return is_palindrome(middle(word)) print(is_palindrome('poop')) print(is_palindrome('alien')) print(is_palindrome('racecar')) print(is_palindrome('park')) #ex 6.7 def is_power(a,b): if a == b: return True elif a%b == 0: return is_power(a/b, b) else: return False print (is_power(3,5)) print (is_power(9,3)) print (is_power(9,2)) #ex 6.8 def gcd(a,b): if a < b: #makes sure input is in the right order gcd(b,a) if b == 0: #base case to eliminate devision by zero return a else: #recursion step. a%b happens after base to avoid division by zero r = a%b return gcd(b,r) print(gcd(16,12)) print(gcd(13,26)) print(gcd(10,27))
false
7a1d06f477560144059bcb1211c1eb5b02e31555
lbrindze/excercises
/ex5.py
1,027
4.1875
4
from math import * #ex 3 print('a?\n') a = int(userInput) except ValueError: print("That's not an int!") print('b?\n') b = int(userInput) except ValueError: print("That's not an int!") print('c?\n') c = int(userInput) except ValueError: print("That's not an int!") print('n?\n') n = int(userInput) except ValueError: print("That's not an int!") def check_fermat(a,b,c,n): if a**n + b**n == c**n: print ("nope that doesn't work.") else: print ('Holy smokes, Fermat was wrong!') check_fermat(a,b,c,n) """ #ex 4 x = input ('a?\n') y = input ('b?\n') z = input ('c?\n') def is_greater(e,f,g): if e > f and e > g: GREATER=e OTHERS=f+g if GREATER < OTHERS: print ('Yes') else: print ('No') else: l = e m = f n = g is_greater (m, n, l) def is_triangle(d,e,f): a = int(d) b = int(e) c = int(f) is_greater(a,b,c) is_triangle(x,y,z) """
false
b1d2f5b4d2e58d8cfe800602766b217ddf4be757
johnerick-py/PythonExercicios
/ex018.py
474
4.15625
4
# faça um programa que leia um angulo qualquer e mostre na tela o valor do seno,cosseno,tangente desse angulo import math angulo = float(input('Digite o angulo:')) seno = math.sin(math.radians(angulo)) cos = math.cos(math.radians(angulo)) tan = math.tan(math.radians(angulo)) print('O angulo {} tem o SENO de {:.2f}'.format(angulo,seno)) print('O angulo de {} tem o COSSENO de {:.2f}'.format(angulo,cos)) print('O angulo de {} tem a TANGENTE de {:.2f}'.format(angulo,tan))
false
328a3dcb5ac2524b33cd18f8a5c7b60db4e12e2b
AhmedEissa30/SIC202
/Python week/Day 2/Checker.py
1,777
4.3125
4
def displayInstruction(): #display function to show the user instructions print("\nChoose your operation: ") print("Press (8) to check Palindrome. Press (1) to check if the number PRIME. \n") print(" Press (0) to EXIT... :(") return True def primeChecker(): #function that takes integer from the user & checks whether it's prime p = int(input("\nPlease enter the number to check...:")) if p > 1: for i in range(2, p): if (p % i) == 0: print(p, "is not a prime number.") break else: print(p, "is a prime number") else: #if input number is less than or equal to 1, it is not prime print(p, "is not a prime number.") return True def palindromeChecker(): #function that takes a string from the user then checks whether it's palindrom or not s = input("\nEnter the word needed to check...:") if s == s[::-1]: print(" It's a PALINDROME.\n") else: print(" Not a PALINDROME...\n") return True while True: #an open loop displayInstruction() #displays instruction to the user Num = int(input("...:")) #takes the choice from the user if Num != 1 and Num != 8 and Num != 0: #condition to check the validity of the input print("Invalid input...\nTry again.") elif Num == 8: #condition of the palindrome palindromeChecker() elif Num == 1: #condition of the oddEvenChecker primeChecker() elif Num == 0: #condition to exit exit()
true
da923a5f7797d953aee3209f9da071d1b387f529
effyhuihui/leetcode
/sort/merge_two_sorted_array.py
2,333
4.28125
4
# -*- coding: utf-8 -*- def merge(A, m, B, n): ''' Given two sorted integer arrays A and B, merge B into A as one sorted array. Note: You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. The number of elements initialized in A and B are m and n respectively. Catch: The catch here is to manage the operation in O(M+N) time, since "insert" will take O(M*N) time, and to make the merge IN PLACE. Thoughts: 其实很简单,要避免insert的话,一般就是从后往前进行插入。 这里既然A已经是一个很大的array了, 而且B和A的occupied的长度都知道(分别是m,n),那么最后merge完以后的array长度也就是已知的m+n。 所以只需要把AB的current last element来进行比较,把其中较大的放到A列的current末尾即可。 要是两个数列 不是同时sort完,再把最后剩下的数组的的0 到 current last 的所有元素依次放入A数组的0:current last即可。 注意: 1. 这里所有带有“current”的变量都是需要maintain的。 2. 其实就是不停的在replace A数组的第N个元素,直到其中一个数组终结。 ''' # compare from the end element of the two arraies pos_b, pos_a = n, m ## cur starts at the end of the future sorted array cur = m+n- 1 while pos_b and pos_a: if A[pos_a-1] >= B[pos_b-1]: A[cur] = A[pos_a-1] pos_a -= 1 else: A[cur] = B[pos_b-1] pos_b -= 1 cur -= 1 if pos_b: A[:cur+1] = B[:cur+1] return A[:m+n] class Solution_secondround: # @param {integer[]} nums1 # @param {integer} m # @param {integer[]} nums2 # @param {integer} n # @return {void} Do not return anything, modify nums1 in-place instead. def merge(self, nums1, m, nums2, n): nums1 += [0 for i in range(n)] cur1, cur2 = m-1, n-1 curnew = m+n-1 while cur1 >=0 and cur2 >=0: if nums1[cur1] >= nums2[cur2]: nums1[curnew] = nums1[cur1] cur1 -= 1 else: nums1[curnew] = nums2[cur2] cur2 -= 1 curnew -= 1 while cur2>=0: nums1[:curnew+1] = nums2[:cur2+1] return nums1 A = [1,5,7,9,11, 0,0,0,0,0,0,0,0,0] B = [2,4,7,9,12,14] x = merge(A, 5, B, 6) print x
false
58b9f2c8704396d6302bfcb8223e034781a104fb
effyhuihui/leetcode
/uncategoried/rotateArray.py
2,407
4.25
4
__author__ = 'effy' #-*- coding: utf-8 -*- ''' Rotate an array of n elements to the right by k steps. For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4]. Note: Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem. hint: 看起来好多rotate的问题都可以转化成局部reverse的问题。 ''' ''' with extra space ''' class Solution: # @param {integer[]} nums # @param {integer} k # @return {void} Do not return anything, modify nums in-place instead. def rotate(self, nums, k): l = len(nums) copy = [i for i in nums] new_index= l-k old_index = 0 while old_index<l: if new_index>=l: new_index = 0 nums[old_index] = copy[new_index] old_index += 1 new_index += 1 x = Solution() a = [1,2,3,4,5,6,7] x.rotate(a,3) ''' no extra space 以n - k为界,分别对数组的左右两边执行一次逆置;然后对整个数组执行逆置。 例如:n=7,k=3 [1,2,3,4,5,6,7] 先对[1,2,3,4] [5,6,7]分别reverse [4,3,2,1,7,6,5] 再reverse整个list [5,6,7,1,2,3,4] ''' class Solution_opt: # @param {integer[]} nums # @param {integer} k # @return {void} Do not return anything, modify nums in-place instead. def rotate(self, nums, k): def reverse(start,end): mid = (start+end)//2 i,j = start,end while i<=mid: tmp = nums[i] nums[i] = nums[j] nums[j] = tmp i+=1 j-=1 n = len(nums) k = k%n reverse(n-k,n-1) reverse(0,n-k-1) reverse(0,n-1) x = Solution_opt() a = [1,2,3,4,5,6] x.rotate(a,11) ''' 将数组元素依次循环向右平移k个单位 ''' class Solution: # @param nums, a list of integer # @param k, num of steps # @return nothing, please modify the nums list in-place. def rotate(self, nums, k): n = len(nums) idx = 0 distance = 0 cur = nums[0] for x in range(n): next = (idx + k) % n temp = nums[next] nums[next] = cur idx = next cur = temp distance = (distance + k) % n if distance == 0: idx = (idx + 1) % n cur = nums[idx]
true
6e754d747744f574a26e56f861e828e2f49602e6
GoYMS/localhost_python
/爬虫/案例/v20.py
969
4.1875
4
""" python中正则模块是re 使用大致步骤 ; 1.compile函数将正则表达式的字符串变为一个Pattern对象 2.通过Pattern对象的一些列方法对文本进行匹配,匹配结果是一个Match对象 3.用Match对象的方法,对结果进行模拟 """ import re #\d表示数字,后边+表示这个数字可以出现一次或者多次 #r表示后边的是原生字符串,后边不需要转义 s=r"\d+" #返回Pattern对象 pattern = re.compile(s) m = pattern.match("one123two13213") #默认匹配从头部开始,返回一个match的值 print(m) #后边两个数字表示查找的范围 m = pattern.match("one123two13213",3,8) print(m) #group表示直接将match打印出来 print(m.group()) #表示从那个位置开始 print(m.start(0)) #表示从那个位置结束 print(m.end(0)) #表示所取出来的结果在字符串中的范围,(自我理解,包左不包右) print(m.span(0))
false
162f59fb97253adce1ff39b40fa641ddd1cfcf24
jcbrockschmidt/project_euler
/p010/solution.py
697
4.125
4
#!/usr/bin/env python3 from time import time def sum_primes_below(n): """ Calculates the sum of all primes below `n`. """ primes = [2, 3] num = primes[-1] + 2 while num < n: is_prime = True limit = int(num**0.5) for p in primes: if p > limit: break if num % p == 0: is_prime = False break if is_prime: primes.append(num) num += 2 return sum(primes) if __name__ == '__main__': start = time() solu = sum_primes_below(2e6) elapse = time() - start print('Solution: {}'.format(solu)) print('Solution found in {:.8f}s'.format(elapse))
true
132ed1d71d5f8406474b25de8de3f55dad2def45
tebannz/pruebadedesarrollopy
/Prueba.py
2,834
4.15625
4
# Deberán crear un programa, el cual deberá recibir un parámetro n ingresado por el usuario, y mostrar los primeros n pares. def obtenerNumero(): return int(input("Ingrese un número: ")); # Ahora deberán crear el programa, donde no se considere el cero. Si , la salida del programa deberá ser: def mostrarPares(numero): for i in range(numero*2, ++2): #aqui se recorre la primera función desde 0 print(i); #aqui estará mostrando de 2 en 2 # Crea programa donde se sumen todos los valores impares desde 0 hasta n, donde n es ingresado por el usuario. def mostrarParesSinCero(numero): for i in range(2, (numero*2)+2, ++2): print(i); # Crear programa, donde el usuario ingresa dos valores, el límite inferior (min) y superior(max) del intervalo para realizar la suma de los impares. def mostrarSumaImpares(numero): resultado = 0; for i in range(numero): if(i%2 != 0): resultado += i; print(resultado); # Función que suma los valores impares desde 0 hasta n, donde n es el valor ingresado por usuario. def mostrarSumaImparesLimites(inferior, superior): resultado = 0; for i in range(inferior, superior): if(i%2 != 0): resultado += i; print(resultado); # Función que calcula el Fibonacci de n elementos. def fibonacci(elementos): if elementos < 2: return elementos; else: return fibonacci(elementos-1) + fibonacci(elementos-2); # Función que muestra la sucesión de fibonacci n veces. def mostrarFibonacci(ocurrencias): for i in range(ocurrencias+1): print(fibonacci(i)); # Función que ejecuta los programas. Basicamente lo que hice en ésta prueba de admisión fué #crear funciones que retornaran en distintas funciones de los programas requeridos , traté de hacerlo lo más "atómico" posible def ejecutarProgramas(): print("Solo pares, Parte 1:"); n = obtenerNumero(); #aqui se guarda el numero que ingresó el usuario por parámetro para luego ser llamado a la funcion del ejercicio 1 mostrarPares(n); #aqui mostraran todos los numeros print("Solo pares, Parte 2:"); mostrarParesSinCero(n); #esta vez empezará desde el 2 y no del 0 print("Suma impares, Parte 1:"); n2 = obtenerNumero(); mostrarSumaImpares(n2); #se pasa el n2 por parametro print("Suma impares, Parte 2:"); #aqui esta la suma de impares parte 2 inferior = obtenerNumero(); superior = obtenerNumero(); mostrarSumaImparesLimites(inferior, superior); print("Secuencia de Fibonacci"); elementosFibonacci = obtenerNumero(); #elementos de Fibonacci mostrarFibonacci(elementosFibonacci); ejecutarProgramas();
false
c289fec7d585d06c696bd94d9c0b8590cfa30110
ibbocus/oop_polymorphism
/polymorphism.py
839
4.65625
5
""" This is the parent/base/super class """ class Planet: def __init__(self, mass, spin, magnetic_field): self.mass = mass self.spin = spin self.magnetic_field = magnetic_field # this is a subclass of planets, which includes the parent class attributes as well as attributes specific to the child class class Goldilocks(Planet): def __init__(self, mass, spin, magnetic_field, life): # By using super, we don't need to explicitly initialize the parent class attributes super().__init__(mass, spin, magnetic_field) self.life = True # Creation of our objects, first object refers to the parent class and the second object # refers to the child class mars = Planet(200, 50000, 15) earth = Goldilocks(300, 25000, 500, True) print(mars.mass) print(earth.mass) print(earth.life)
true
3d658085a747514cdadebcbf57479e6a57901d81
SperZ/PythonFirstPractice
/array.py
372
4.25
4
arr1 = [1,2,3,4,5] arr2 = [4,5,6,7,8] # combines to arrays together to create one array with all elements of both arrays arr3 = arr1 + arr2; print(arr3); # arr_repeat = []; arr_repeat.append("eat"); arr_repeat.append("sleep"); arr_repeat.append("repeat"); arr_repeat.pop();# removes the item from the array/list at the give index print(arr_repeat); #print(popped);
true
d9e075e78cf95649c0a1b2fc7df2febff46b2e2b
grayey/hackerrank-playful-py
/recursion.py
520
4.21875
4
#!/bin/python3 """ Task Write a factorial function that takes a positive integer, N as a parameter and prints the result of N!(N factorial). """ import math import os import random import re import sys # Complete the factorial function below. def factorial(n): new_n = n-1; return 1 if new_n == 0 else n * factorial(new_n) if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input()) result = factorial(n) fptr.write(str(result) + '\n') fptr.close()
true
5012f094648baf39d78856f1ce9906c1e45d9f8e
wmontanaro/AdventOfCode2017
/day3.py
2,436
4.34375
4
def is_down(k): n = 0 while ((2*n + 1)**2 - n) < k: n += 1 if (2*n + 1)**2 - n == k: return n return False def is_right(k): n = 0 while ((2*n - 1)**2 + n) < k: n += 1 if (2*n - 1)**2 + n == k: return n return False def is_left(k): n = 0 while ((2*n)**2 + (n+1)) < k: n += 1 if (2*n)**2 + (n+1) == k: return n return False def is_up(k): n = 0 while (2*n)**2 - (n-1) < k: n += 1 if (2*n)**2 - (n-1) == k: return n return False def is_plus(k): if k == 1: return 0 if is_down(k): return is_down(k) if is_right(k): return is_right(k) if is_left(k): return is_left(k) if is_up(k): return is_up(k) return False '''figure out if up or down, move opposite to plus''' '''how to figure out if up or down? can figure out its octant by starting with the floor of its square root e.g. 18 lies between upper left diag (n=2) and left plus e.g. 47 -> 6, n=3; so UL is 37, L is 40, LL is 43, D is 46, D+1 is 47 so to summarize up/down: floor sqrt // 2 -> n (368078 -> 303) this is the ring the number is on if (2n)**2 + 1 <= num < (2n)**2 + 1 + n, then it is up if (2n)**2 + 1 + n < num < (2n)**2''' import math def check_square(k): v = math.sqrt(k) if int(v) == v: #v perfect square return(int(v)-1) return False def get_vert(k): #if check_square(k): #return "square" v = math.sqrt(k) if math.floor(v) % 2 == 1: lower_square = math.floor(v) upper_square = math.floor(v)+2 else: lower_square = math.floor(v)-1 upper_square = math.floor(v)+1 #print("lower_square: " + str(lower_square)) #print("upper_square: " + str(upper_square)) n = (lower_square + 1) // 2 #print("n: " + str(n)) left = 4*(n**2) + 1 + n #print("left: " + str(left)) right = 4*(n**2) + 1 - (3*n) #print("right: " + str(right)) if right < k < left: return "above 1" return "below 1" def step_down(k): pass def tfunc(k): if is_plus(k): return is_plus(k) vert = get_vert(k) steps = 0 if vert == "above 1": while not is_plus(k): k = step_down(k) steps += 1 return steps + is_plus(k) if vert == "below 1": while not is_plus(k): k = step_up(k) steps += 1
false
592648f17627d10b2154f94c3dc20cc8136722d9
Nick2253/project-euler
/Python/euler007/euler007.py
1,233
4.15625
4
import math def isPrime(num): '''Determines if num is prime input: numList = list of ints maxNum = int output: sumTotal = int sum of all multiples of numbers in numList less than maxNum ''' isPrime = True i = 2 #We don't care if num is divisible by 1 if num <= 1: return False while (i < (1 + math.sqrt(num)) and i != num): #We add 1 to the sqrt to preclude rounding issues if num%i == 0: isPrime = False break i += 1 return isPrime def nPrime(maxIndex): '''Determines the maxIndexth prime input: maxIndex = int output: prime at maxIndex ''' i = 0 num = 0 while i < maxIndex: num += 1 if isPrime(num): i += 1 return num if __name__ == "__main__": print "isPrime(1) = " + str(isPrime(1)) print "isPrime(2) = " + str(isPrime(2)) print "isPrime(10) = " + str(isPrime(10)) print "isPrime(23) = " + str(isPrime(23)) print "nPrime(6) = " + str(nPrime(6)) print "nPrime(10001) = " + str(nPrime(10001))
true
98796dc9365babd222ddd97216558daac34d7c9d
FlyingJ/kaggle-learn-python
/roulette_probabilites.py
1,901
4.1875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jan 7 17:44:46 2019 @author: jason """ def conditional_roulette_probs(history): """Given a history of roulette spins (as list of integer values) return a dictionary where the keys are numbers on the roulette wheel, and the values are dictionaries mapping numbers on the wheel to probabilities, such that `d[n1][n2]` is an estimate of the probability that the next spin will land on n2, given that the previous spin landed on n1. Example: conditional_roulette_probs([1, 3, 1, 5, 1]) > {1: {3: 0.5, 5: 0.5}, 3: {1: 1.0}, 5: {1: 1.0} } """ pass def next_spins(history): '''Given a history of roulette spins, return a dictionary where the keys are spins and the values are lists of spins immediately following. Example: print(next_spins([1, 3, 1, 5, 1])) > {1: [3, 5], 3: [1], 5: [1]} ''' next_spins = {} for index, spin in enumerate(history[:-1]): # initialize list of next spins if not exist if spin not in list(next_spins): next_spins[spin] = [] next_spins[spin].append(history[index + 1]) return next_spins def next_spin_probabilities(next_spins): '''Given a dictionary where keys are spins and values are lists of spins immediately following, return a dictionary where keys are spins and values are dictionaries of next spins and their probabilities. Example: print(next_spin_probabilites({1: [3, 5], 3: [1], 5: [1]})) > {1: {3: 0.5, 5: 0.5}, 3: {1: 1.0}, 5: {1: 1.0}} ''' next_spin_probabilities = {} for spin in list(next_spins): total_events = len(next_spins[spin]) spin_probabilites = {} for next_spin in next_spins[spin]: if next_spin not in list(spin_probabilities): spin_probabilities
true
c353caa38ab6021b987657320054050a65a7e365
Nobodylesszb/python_module
/Algorithms/itertools/itertools_accumulate.py
427
4.34375
4
#该accumulate()函数处理输入iterable, # 将第n和第n + 1项传递给函数并生成返回值而不是任何一个输入。 # 用于组合这两个值的默认函数会将它们相加, # 因此accumulate()可用于生成一系列数字输入的累积和 from itertools import * print(list(accumulate(range(5)))) print(list(accumulate('abcde'))) """ output: [0, 1, 3, 6, 10] ['a', 'ab', 'abc', 'abcd', 'abcde'] """
false
a88ee14815298cea657eb0de403a77b6a3d2569a
Nobodylesszb/python_module
/Algorithms/itertools/itertools_product_repeat.py
860
4.21875
4
from itertools import * #要计算序列与自身的乘积,请指定输入应重复的次数 def show(iterable): for i, item in enumerate(iterable, 1): print(item, end=' ') if (i % 3) == 0: print() print() print('Repeat 2:\n') print(list(product(range(3), repeat=2))) show(list(product(range(3), repeat=2))) print('Repeat 3:\n') show(list(product(range(3), repeat=3))) """ Repeat 2: [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)] (0, 0) (0, 1) (0, 2) (1, 0) (1, 1) (1, 2) (2, 0) (2, 1) (2, 2) Repeat 3: (0, 0, 0) (0, 0, 1) (0, 0, 2) (0, 1, 0) (0, 1, 1) (0, 1, 2) (0, 2, 0) (0, 2, 1) (0, 2, 2) (1, 0, 0) (1, 0, 1) (1, 0, 2) (1, 1, 0) (1, 1, 1) (1, 1, 2) (1, 2, 0) (1, 2, 1) (1, 2, 2) (2, 0, 0) (2, 0, 1) (2, 0, 2) (2, 1, 0) (2, 1, 1) (2, 1, 2) (2, 2, 0) (2, 2, 1) (2, 2, 2) """
false
b934a8fa0d994cc3ae00ab2fe7a8e7d867db7dd8
zayzayzayzay/Introduction_python
/Comrehension_part2.py
757
4.28125
4
#Dictionary comprehension word = "letters" letter_count = {letter: word.count(letter) for letter in word} print(letter_count) letter_counts = {letter: word.count(letter) for letter in set(word)} print(letter_counts) #Set Comprehensions a_set = {number for number in range(1,6) if number % 3 == 1} print(a_set) #generator comprehension (there is no tuple comprehension) number_thing = (number for number in range(1,7)) print(type(number_thing)) #way of iterate over generator for number in number_thing: print(number) #list way number_things = (number for number in range(1,7)) number_list= list(number_things) print(number_list) #a generator doesn't keep its value in memory #it can be run only once number_list= list(number_things) print(number_list)
true
b6d148a52d674bad4b4561b26d26deaebd5d9e9b
zayzayzayzay/Introduction_python
/class2.py
1,829
4.125
4
#name mangling for privacy class Duck(): #class definition def __init__(self,input_name): #constructor self.__name = input_name @property #getter def name(self): print('inside the getter') return self.__name @name.setter #setter def name(self,input_name): print('inside the setter') self.__name = input_name fowl = Duck('howard') print(fowl.name) fowl.name = 'donald' print(fowl.name) # you can’t access the __name attribute #print(fowl.__name) # you can access the __name attribute print(fowl._Duck__name) #method types class A(): count = 0 def __init__(self): A.count += 1 def exclaim(self): print("I'am an A!") @classmethod #class method def kids(cls): print("A has ",cls.count, " little objects.") easy_a = A() breezy_a = A() wheezy_a = A() A.kids() #staticmethod class CoyoteWeapon(): @staticmethod def commercial(): print('This CoyoteWeapon has been brought to you by Acme') CoyoteWeapon.commercial() #Duck Typing class Quote(): def __init__(self, person, words): self.person = person self.words = words def who(self): return self.person def says(self): return self.words + '.' class QuestionQuote(Quote): def says(self): return self.words+ '?' class ExclamationQuote(Quote): def says(self): return self.words + '!' hunter = Quote('Elmer Fudd', "I'm hunting wabbits") print(hunter.who(), 'says:', hunter.says()) hunted1 = QuestionQuote('Bugs Bunny', "What's up, doc") print(hunted1.who(), 'says:', hunted1.says()) hunted2 = ExclamationQuote('Daffy Duck', "It's rabbit season") print(hunted2.who(), 'says:', hunted2.says()) #a class having no relation with the previous one class BabblingBrook(): def who(self): return 'Brook' def says(self): return 'Babble' brook = BabblingBrook() def who_says(obj): print(obj.who(), 'says', obj.says()) who_says(hunter) who_says(brook)
false
c6e9e1f1724312e6ec7213807ae5533a78a3da8a
cs-fullstack-2019-fall/python-classobject-b-cw-marcus110379
/cw.py
2,534
4.125
4
def main(): problem1() problem2() problem3() # Create a class Dog. Make sure it has the attributes name, breed, color, gender. Create a function that will print all attributes of the class. Create an object of Dog in your problem1 function and print all of it's attributes. class Dog: def __init__(self, name, breed, color, gender): self.name = name self.breed = breed self.color = color self.gender = gender def printAll(self): print(f"{self.name}, {self.breed},{self.color},{self.gender}") # !! : use string formatting to take advantage of f strings def problem1(): myDog = Dog("Rocky", "poodle", "black","male") myDog.printAll() # Problem 2: # We will keep having this problem until EVERYONE gets it right without help # Create a function that has a loop that quits with the equal sign. If the user doesn't enter the equal sign, ask them to input another string. def user(): userInput = input("enter a string") while userInput != "=": userInput = input("enter another string") def problem2(): user() # Problem 3: # Create a class Product that represents a product sold online. A product has a name, price, and quantity. # The class should have several functions: # a) One function that can change the name of the product. # b) Another function that can change the name and price of the product. # c) A last function that can change the name, price, and quantity of the product. # Create an object of Product and print all of it's attributes. class Product: def __init__(self, name, price, quantity): self.name = name self.price = price self.quantity = quantity def funcA(self, name): # !! : this is a bad function name self.name = name def funcB(self, name, quantity): # !! : this is a bad function name AND change the name and price of the product self.name = name self.quantity= quantity def funcC(self, name, price, quantity): # !! : this is a bad function name self.name = name self.price = price self.quantity = quantity def problem3(): product1 = Product("genie", "$25", "1") print(product1.name, product1.price, product1.quantity) product1.funcA("test1a") print(product1.name, product1.price, product1.quantity) product1.funcB("test2a", "test2b") print(product1.name, product1.price, product1.quantity) product1.funcC("test3a", "test3b", "test3c") print(product1.name, product1.price, product1.quantity) main()
true
9a60a94ac5ddd89bf5aab0c03d5a5bada2d0dc8f
Rastwoz/python101
/3. Data Structures/Challenges and Solutions/Dictionaries/homework2.py
921
4.53125
5
#create dictionary with Hello in each language translator = {"French":"Bonjour", "Spanish":"Hola", "Italian":"Ciao", "German": "Guten Tag", "Indian": "Namaste" } #if user enters a language in dictionary, translate the word. Otherwise, let them add it #if user enters quit, exit program while True: selection = input("Select your language? ").title() if selection == "Quit": break elif selection in translator: print(translator.get(selection)) elif selection not in translator: print("Thats a new language. Lets add it") new_language = input(f"What does 'Hello' mean in {selection}: ") translator[selection] = new_language #alternative way of adding a language #translator.update({selection:new_language})
true
5bb5f7ed6d3aa6f4cbf0d311543506363dc6f589
yoontrue/Python_work
/python_day03/day03ex102_class.py
784
4.125
4
# 앞에서 사용한 딕셔너리 구조를 class로 변경 # 클래스 선언은 class 키워드를 이용한다. ''' class 클래스명(상속) : 생성자메소드 멤버메소드 멤버필드 ''' class People: # 생성자 메소드 선언, 생성자와 멤버메소드는 self 매개변수가 선언 되어야한다. def __init__(self, name): self.name = name def setName(self, name): self.name = name def getName(self): return self.name def greeting(self): return self.name + '님 안녕!' # 객체 생성 시 자바처럼 new 사용하지 않는다 kim = People('kim') pList = [kim, People('lee'), People('park')] pList[0].setName('hong') for person in pList: print('인사 >>> ', person.greeting())
false
0df5dc3aeeb90af857f68060156591461bbdb2eb
hugoreyes83/scripts
/fibonacci.py
268
4.28125
4
def fibonacci(n): '''function returns fibonacci sequence up to provided number''' fibonacci_list = [0,1,1] for i in range(3,n+1): fibonacci_list.insert(i,fibonacci_list[i-1]+fibonacci_list[i-2]) return fibonacci_list[n-1] print(fibonacci(10))
false
8905adda00560a3cf143b8faba96d4f17b4429af
priestd09/project_euler
/e_16.py
497
4.125
4
#!/usr/bin/env python """ ##--- # jlengrand #Created on : Fri Jan 13 15:24:59 CET 2012 # # DESCRIPTION : Solves problem 16 of Project Euler 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 2^1000? ##--- """ def sum_power_2(value): """ Returns the sum of the digits of 2^value """ return sum([int(el) for el in list(str(pow(2, value)))]) if __name__ == '__main__': print "Answer : %d" % (sum_power_2(1000))
true
d0a181c79d71fa82a8fdc193768ebc54ace30937
priestd09/project_euler
/e_4.py
979
4.25
4
#!/usr/bin/env python """ #--- Julien Lengrand-Lambert Created on : Wed Jan 11 14:42:54 CET 2012 DESCRIPTION : Solves problem 4 of Project Euler A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 99. Find the largest palindrome made from the product of two 3-digit numbers. #--- """ def largest_palindrom(): """ Returns the largest palindrom made from the product of two 3-digits number """ three_digits = range(100, 1000) largest = 0 for digit_1 in three_digits: for digit_2 in three_digits: val = digit_1 * digit_2 if is_palindrom(val): if largest < val: largest = val return largest def is_palindrom(number): """ returns True if a number is a palindrom, False otherwise """ return str(number)[::-1] == str(number) if __name__ == '__main__': print "Answer : %d " % (largest_palindrom())
true
38f49214e119612b127236bd230f2b11bba088ee
priestd09/project_euler
/e_6.py
924
4.125
4
#!/usr/bin/env python """ #--- Julien Lengrand-Lambert Created on : Wed Jan 11 14:42:54 CET 2012 DESCRIPTION : Solves problem 6 of Project Euler Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. #--- """ def diff_sum_squares(value): """ Returns the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. """ return squares_sum(value) - sum_squares(value) def sum_squares(value): """ Returns the sum of the square of elements from 1 to value """ vals = range(1, value + 1) return sum([pow(val, 2) for val in vals]) def squares_sum(value): """ Returns the square of the sum of elements from 1 to value """ return pow(sum(range(1, value + 1)), 2) if __name__ == '__main__': val = 100 print "Answer : %d " % (diff_sum_squares(val))
true
75bbb63e6278cca0465f5ff4b1d7aebc10ce77ee
ChenlingJ/cj
/hackerrank/lists.py
1,663
4.125
4
# Consider a list (list = []). You can perform the following commands: # # insert i e: Insert integer e at position i. # print: Print the list. # remove e: Delete the first occurrence of integer e. # append e: Insert integer e at the end of the list. # sort: Sort the list. # pop: Pop the last element from the list. # reverse: Reverse the list. # # Initialize your list and read in the value of n followed by n lines of commands where each command will be of the 7 # types listed above. Iterate through each command in order and perform the corresponding operation on your list. def read_lines(n: int) -> list[str]: """ Read and return `n` lines of input. """ return [input() for _ in range(n)] def parse_commands(lines: list[str]) -> list[tuple[str, list[int]]]: """ Process a list of `lines` and turn into command tuples `(command, args)`. """ result = [] for line in lines: command, *args = line.split() args = list(map(int, args)) result.append((command, args)) return result def run_commands(commands: list[tuple[str, list[int]]]) -> list[str]: arr = [] output = [] methods = { "insert": arr.insert, "remove": arr.remove, "append": arr.append, "sort": arr.sort, "pop": arr.pop, "reverse": arr.reverse, } for command, args in commands: if command == "print": # print is not a method of arr. output.append(str(arr)) else: methods[command](*args) return output if __name__ == "__main__": N = int(input()) print("\n".join(run_commands(parse_commands(read_lines(N)))))
true
6c82dd1a17cb90a870d009e5ea8ac40772dafcf0
GeekGoutham/Python-Interactive-Challenges
/Unique_String.py
1,122
4.15625
4
#Author = Vignesh Goutham def check_unique_dict(string_input): #Implmented using dict -- Poor performance as you need to check if there is more than one entry char_dict = {} #Still O(n) but dict takes more space then list for character in string_input: if character in char_dict.keys(): flag = False return False else: char_dict[character] = 1 # print(char_dict) return True def check_unique_list(string_input): #Better than dict implementation : Still O(n) complexity string_check_list=[] for character in string_input: if character in string_check_list: return False else: string_check_list.append(character) return True def check_unique_set(string_input): #O(n) as well -- better algorithm using set() -- set does not allow duplicates. return len(set(string_input)) == len(string_input) if __name__ == '__main__': string_input = input("Enter the string needed to be checked : ") result = check_unique_list(string_input) print(str(result))
true
25bf8924786bb17333d9425a722c74755e8c5768
GeekGoutham/Python-Interactive-Challenges
/String_reverse_inplace.py
1,306
4.28125
4
#Author = Vignesh Goutham def string_reverse(charlist): if charlist == None: #strings are immutable in python, we cant do a strict in-place string reverse print("No character array sent") #In-place algo = where the input is changed to output and a new memory/variable for o/p is not created return False #in-place is distructive as it destroys the input current = 0 far_current = len(charlist)-1 while(current != far_current): charlist[current],charlist[far_current] = charlist[far_current], charlist[current] current += 1 far_current -= 1 print(charlist) def string_reverse_v2(string1): #Pythonic way to do with strings (Not in-place) if string1 == None: print("No string to reverse") return False else: print(string1[::-1]) def string_reverse_v3(string1): #Using reversed method -- (Not in-place) if string1 == None: print("No string to return") else: rev = reversed(string1) print("".join(rev)) if __name__ == "__main__": charlist = ['v','i','g','n','e','s','h'] print(charlist) string_reverse(charlist) print("=====================") string_reverse_v2("Vignesh") string_reverse_v3("vignesh")
true
943e612b6887ec0ad85c23fd2a2c7f4383b8c29a
napte/python-learn
/08_list_for_each.py
578
4.1875
4
def main(): a = [1, 2, 3] print 'List a = ' + str(a) print 'Doing for-each loop and printing numbers and their squares\n' for num in a: print '\n------\n' print 'num = ' + str(num) print str(num) + '^2 = ' + str(num**2) print '\n------\n' a = [1, 2, 3, 4, 5, 6, 7, 8] even = [] print 'List a => ' + str(a) print 'List even (empty right now) => ' + str(even) for num in a: if num%2 == 0: even.append(num) print 'even => ' + str(even) # Standard boilerplate code that calls the main function if __name__ == '__main__': main()
true
030fee26786b2675ffa42a974a308af70cacc2c8
minji-o-j/Python
/대학원 파이썬 수업/수업/1027/city.py
272
4.15625
4
city = ['DC','NY','Seoul', 'Tokyo','Paris'] print("what is the capital of S.Korea?") for i in range(len(city)): print('{}. {}'.format(i+1,city[i])) answer = int(input('choose an answer: ')) if answer == 3: print('correct') else: print('incorrect')
false
ec6cd149c7835a225125b541c44d6e33d1e69765
richardcinca/CursuriPY
/ex4.py
573
4.28125
4
iterator=0 reversed_word="" word = input("Insert word: ") print("Your word is '{}'".format(word)) length=len(word) print("The length of the word is {} letters".format(length)) for var in word: #print("Var is {}".format(var)) #print(word[iterator]) #iterator+=1 #reversed_word=var+reversed_word #print(reversed_word) #print("......") print("{} must be equal to {}".format(word[iterator],var)) iterator = iterator+1 reversed_word=var+reversed_word print("Reversed word is:{}".format(reversed_word)) input("\n\n P <enter> to exit.")
true
63f722f1667e843eb0a0d42e2030b215fe65913f
jayadams011/KalPython
/bmi claculator.py
464
4.21875
4
weight = eval(input("Enter weight in pounds: ")) height = eval(input("enter height in inches: ")) KILOGRAMS_PER_POUND = 0.45359237 METERS_PER_INCH = 0.0254 weightInKg = weight * KILOGRAMS_PER_POUND heightInMt = height * METERS_PER_INCH bmi = weightInKg / (heightInMt ** 2) print ("BMI is" , format(bmi, ".2f")) if bmi < 18.5: print ("Underweight") elif bmi < 25: print ("Normal") elif bmi < 30: print ("Overweight") else: print ("obese")
false
72d3ee8cb18777b39a4d19f8c9ff1338b121681f
jayadams011/KalPython
/2_4_poundsToKilograms.py
628
4.1875
4
""" (Convert pounds into kilograms) Write a program that converts pounds into kilograms. The program prompts the user to enter a value in pounds, converts it to kilograms, and displays the result. One pound is 0.454 kilograms. Here is a sample run: Enter a value in pounds: 55.5 55.5 pounds is 25.197 kilograms """ #user inputs number of pounds to convert to Kgs #create a var that requires input from the user pounds = eval(input( "Enter the number of pounds you would like to convert to kilograms. -->")) # convert pounds to kilograms kilograms = pounds * 0.454 #print output print( pounds, " is ",kilograms, " kilograms.")
true
e4bf2decd4a1b5c8c246d5a50908abbd9e7b9f89
stevenb92/PythonShizzle
/numchar.py
310
4.34375
4
#Prompts for an input string and then returns the input string #along with the number of charcters in the string inputString = "" length = 0 while length == 0: print ("Enter an input string:") inputString = str(input()) length = len(inputString) print ("{} has {} characters".format(inputString,length))
true
3864a6a4ed3038f46d45dd19ab2b41a930b2a8fd
JoshOrndorff/LearnPythonByExample
/Unit6-2DLists/lesson2-WheresWaldo.py
1,737
4.21875
4
# Let's make a 2D list that contains a bunch of people. Since all these strings # are different lengths it would be easy for this table to look messy. Using # white space effectively can help the data look more organized. people = [["Jack", "Abagail", "Waleed" ], ["Rebeca", "Obi", "Orndorff"], ["Simon", "Waldo", "Jamie" ]] # Our goal is to figure out where in the grid the name "Waldo" appears, and # print its coordinates. Algorithm-wise that means looking through each row, # and within each row looking through each name until we see Waldo. rowCounter = 0 for row in people: colCounter = 0 for item in row: if item == "Waldo": print("Found him at location {}, {}".format(rowCounter, colCounter)) colCounter += 1 rowCounter += 1 # ---------------- Exercises ----------------- # 1. Change the search so that it will find "waldo", "WALDO", and "walDO" as # Well as just "waldo". # 2. Change the for loops to while loops. What looping condition should we use # to make sure we don't miss any rows or items in those rows? # 3. Modify lines 6 and 7 to add a fourth row of people to the list. Does your # code still find waldo correctly? What if Waldo is in the bottom row? # 5. What happens if waldo appears more tha once in this grid? # 4. ADVANCED: Convert this program to use a function called wheres_waldo that # takes a grid as an argument, and returns the coordinates. What happens # if Waldo appears more than once in this grid? What happens if Waldo isn't # in the grid at all? # # Hint: your return line line should look something like: # # return rowCounter, colCounter # # That line returns a tuple which we haven't formally seen... yet.
true