blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
33fd8f151e3a06f6b304f6ec74003efa7afaf8e5
AngelPerezV/python
/Condicionales.py
1,419
4.125
4
""" Condicionales (pt. I) Los condicionales los utilizaremos para validar si se cumple una o más condiciones para ejecutar cierto bloque de código, en esencia nos ayuda a tomar decisiones sobre el flujo de nuestro código. """ """ Sintaxis: if condition: # Block of code elif other_condition: # Another block of code else: # Final block of code """ edad=24 print(edad) edad=input("Escribe tu edad: ") edad = int(edad)#casting if edad >= 18 and edad <= 100: print("Eres Mayor de edad: ") elif edad > 100: print("ya te petataste. ") elif edad < 0: print("tu edad no tiene sentido.") else: print("Eres menor de edad xd. ") richard = 27 rodo = 17 rafa = 22 edad_total = richard + rodo + rafa print(edad_total) print(richard) print(rodo) print(rafa) if richard >= 18 and rodo >= 18 and rafa >= 18: print("Todos son mayores.") else: print("Alguien es menor. ✖️") #If anidados animal = "caballo" color = "blanco" if animal == "caballo": if color == "negro": print("Ah, es el caballo de Juan.") else: print("No sé de quién sea.") else: print("No sé qué animal es.") if color == "negro": print("Ah, es el caballo de Juan.") else: print("No sé de quién sea.") color = "negro" "Ah, es el caballo de Juan." if color == "negro" else "No sé de quién sea." z = 2 + 3j print(z.__dir__()) print(z.real, z.imag) print(z.conjugate())
false
ebf0a9c88f3db9b20577e9bbeceab4d0cd243d26
longjiazhen/learn-python-the-hard-way
/ex11.py
1,241
4.3125
4
#coding:utf-8 #print语句的后面有逗号的话,输出这句话以后就不会换行,而是在同一行等待输入 #print语句的后面没有逗号的话,输出以后就会换行,到下一行去等待输入 print "How old are you?", age = raw_input() age11 = raw_input("How old are you??\n") #这样输入How tall are you? 6'22" print "How tall are you?", height = raw_input() print "How much do you weigh?", weight = raw_input() print "So,you are %r old, %r tall and %r heavy." % (age, height, weight) #然后输出的结果So,you are '35' old, '6\'22"' tall and '180lbs' heavy. #注意'6\'22"'这里,6'22",自动在6后面的单引号前面加转义字符,避免将这认为是字符串的结束标志 #python 2.x用的是raw_input,随便输入都是字符串 #所以这里可以输入 zhangsan 7 name_raw = raw_input('输入姓名:') age_raw = raw_input('输入年龄:') #python 3用的是input,是字符串就得加上'' #这里要输入 'zhangsan' 7 name_in = input('输入姓名(要加引号):') age_in = input('输入年龄:') #使用raw_input,将输入的字符串转换成数字 print "输入x:", x = int(raw_input()) print "输入y:", y = int(raw_input()) print "x + y = %d " % (x + y)
false
35b8cae406fb052b17ac400bbd22d93af679999a
Mohanishgunwant/Home_Tasks
/problem2.py
455
4.375
4
#Create a program that asks the user for a number and then prints out a list of all the divisors of that number. # (If you don’t know what a divisor is, it is a number that divides evenly into another number. For example, 13 is a divisor of 26 because 26 / 13 has no remainder.) def list_divisor(x): lis = [] for i in range(1,x+1): if x % i == 0: lis.append(i) print(lis) list_divisor(int(input("Enter the number\n")))
true
e67c0dcb9c17cabd20f9896fe33d1f236b6e02ad
sharonzz/Programming-For-Everybody.coursera
/assignment7.2.py
796
4.28125
4
#7.2 Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form: X-DSPAM-Confidence: 0.8475 #Count these lines and extract the floating point values from each of the lines and compute the average of those values and produce an output as shown below. #You can download the sample data at http://www.pythonlearn.com/code/mbox-short.txt when you are testing below enter mbox-short.txt as the file name fname = raw_input("Enter file name: ") fh = open(fname) l = [] for line in fh: if not line.startswith("X-DSPAM-Confidence:") : continue ll = line.split() for i in ll: try: u = float(i) l.append(u) except: pass print "Average spam confidence:",sum(l)/len(l)
true
bed359932d354615b7849676da7d04476dd72132
jswetnam/exercises
/ctci/ch9/robot.py
1,395
4.15625
4
# CTCI 9.2: # Imagine a robot sitting in the upper left corner of an X by Y grid. # The robot can only move in two directions: right and down. How many # possible paths are there for the robot to go from (0, 0) to (X, Y)? # Imagine that certain spots are off-limits. Design an algorithm for the # robot to go from the top left to the bottom right. IMPASSIBLE = -1 def FindPath(M, x, y): """Return string representation of the path from 0, 0 to x, y in the 2D matrix M to the list path. Impassable cells have the value -1. Returns None if no paths exist to 0, 0 from this point.""" if (x, y) == (0, 0): return "S" else: if x - 1 >= 0 and M[x - 1][y] != IMPASSIBLE: path_left = FindPath(M, x - 1, y) if path_left: return path_left + "R" if y - 1 >= 0 and M[x][y - 1] != IMPASSIBLE: path_up = FindPath(M, x, y - 1) if path_up: return path_up + "D" # M = [0][0] # [0][0] # FindPath(M, 1, 1 "") # FindPath(M, 0, 1 "") # FindPath(M, 0, 0 "") # D # R def PrintMatrix(M): for j in range(len(M)): row = "" for i in range(len(M[0])): row += "[%d] " % M[i][j] print row def main(): x, y = 5,5 matrix = [[0 for _ in range(x)] for _ in range(y)] matrix[0][4] = IMPASSIBLE matrix[1][3] = IMPASSIBLE PrintMatrix(matrix) # import pdb; pdb.set_trace() print FindPath(matrix, 4, 4) if __name__ == "__main__": main()
true
bdd706b18ce4a36e14e6e69253fae329f14696c9
m0hanram/ACADEMICS
/clg/sem4/PYTHONLAB/psbasics_1/assignment 1/ps1basic_7.py
324
4.15625
4
def panagram_func(sentence): alphabet = "abcdefghijklmnopqrstuvwxyz" for i in alphabet: if i not in sentence.lower(): return "false" return "true" sen = input("enter the sentence : ") if (panagram_func(sen) == "true"): print("it is a panagram") else: print("it is not a panagram")
true
3bf9847235620c0ad7663bb9e1b8f205e62801d0
SelvaLakshmiSV/Registration-form-using-Tinker
/form.py
2,701
4.53125
5
#how to create simple GUI registration form. #importing tkinter module for GUI application from tkinter import * #Creating object 'root' of Tk() root = Tk() #Providing Geometry to the form root.geometry("500x500") #Providing title to the form root.title('Registration form') #this creates 'Label' widget for Registration Form and uses place() method. label_0 =Label(root,text="Registration form", width=20,font=("bold",20)) #place method in tkinter is geometry manager it is used to organize widgets by placing them in specific position label_0.place(x=90,y=60) #this creates 'Label' widget for Fullname and uses place() method. label_1 =Label(root,text="FullName", width=20,font=("bold",10)) label_1.place(x=80,y=130) #this will accept the input string text from the user. entry_1=Entry(root) entry_1.place(x=240,y=130) #this creates 'Label' widget for Email and uses place() method. label_3 =Label(root,text="Email", width=20,font=("bold",10)) label_3.place(x=68,y=180) entry_3=Entry(root) entry_3.place(x=240,y=180) #this creates 'Label' widget for Gender and uses place() method. label_4 =Label(root,text="Gender", width=20,font=("bold",10)) label_4.place(x=70,y=230) #the variable 'var' mentioned here holds Integer Value, by deault 0 var=IntVar() #this creates 'Radio button' widget and uses place() method Radiobutton(root,text="Male",padx= 5, variable= var, value=1).place(x=235,y=230) Radiobutton(root,text="Female",padx= 20, variable= var, value=2).place(x=290,y=230) ##this creates 'Label' widget for country and uses place() method. label_5=Label(root,text="Country",width=20,font=("bold",10)) label_5.place(x=70,y=280) #this creates list of countries available in the dropdownlist. list_of_country=[ 'India' ,'US' , 'UK' ,'Germany' ,'Austria'] #the variable 'c' mentioned here holds String Value, by default "" c=StringVar() droplist=OptionMenu(root,c, *list_of_country) droplist.config(width=15) c.set('Select your Country') droplist.place(x=240,y=280) ##this creates 'Label' widget for Language and uses place() method. label_6=Label(root,text="Language",width=20,font=('bold',10)) label_6.place(x=75,y=330) #the variable 'var1' mentioned here holds Integer Value, by default 0 var1=IntVar() #this creates Checkbutton widget and uses place() method. Checkbutton(root,text="English", variable=var1).place(x=230,y=330) #the variable 'var2' mentioned here holds Integer Value, by default 0 var2=IntVar() Checkbutton(root,text="German", variable=var2).place(x=290,y=330) #this creates button for submitting the details provides by the user Button(root, text='Submit' , width=20,bg="black",fg='white').place(x=180,y=380) #this will run the mainloop. root.mainloop()
true
b727ed52184529f3bb0735f536986e244a21d4dd
kangliewbei128/sturdy-siamese
/caesar cipher.py
2,471
4.75
5
import pyperclip import string #This asks the user for what message they want to be encrypted inputedmessage=input('enter a message to be translated:') #converts the message that the user inputed into lowercase letters. optional. If you want it converted, add .lower() at the end of inputedmessage message=inputedmessage #How far up the alphabet do you want the letter to change into (e.g A will go up 13 letters in the alphabet to M) key=13 #DO you want to decrypt or encrypt the message? mode='encrypt' #THe symbols that you can convert the message into SYMBOLS='QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm123456789!?,.' #translated will be an empty string that values can be added to later translated='' #for each symbol in the message that you want to be translated for symbol in message: #if the symbol is in SYMBOLS so that it can be encrypted if symbol in SYMBOLS: #.find(symbol) finds which position in numerics the symbol in message is in SYMBOLS (e.g A is t position 11 in SYMBOLS) #.find function will return a number symbolIndex=SYMBOLS.find(symbol) if mode=='encrypt': #This shifts the letter in the message up the alphabet. key is 13, so the letter will go up 13 letters. #TranslatedIndex is the new position in which the letter is. (e.g after A gone up 13 alphabets to M, M is in position 26. translatedIndex=26) translatedIndex=symbolIndex+key elif mode=='decrypt': #since encrypt moves the letter up, to decrypt move the letter down. translatedIndex=symbolIndex-key if translatedIndex >= len(SYMBOLS): #if the position ends up going to more than 65, go back to the start,1 translatedIndex=translatedIndex-len(SYMBOLS) elif translatedIndex<=0: #THis happens in the case of decrypt. SO it will be go back to the end of SYMBOLS. translatedIndex=translatedIndex+len(SYMBOLS) #New translated message = what is in the translated variable now + the symbol in the position. THe square brackets are the index, so like for #helloworld[6] is 'O' translated=translated+SYMBOLS[translatedIndex] else: #If any of the symbols that the user try to put in is not in SYMBOLS, just dont encrypt that particular symbol and add it to what you can translate translated=translated+symbol print(translated) #This translated pyperclip.copy(translated)
true
b432afe745e13a897a4ad44ea51f6105440d39c8
petrenkonikita112263/Python_Professional_Portfolio_Projects
/Tic Tac Toe/tic_tac.py
2,171
4.28125
4
class TicTacToeGame: def __init__(self, board) -> None: """Class constructor""" self.board = board def display_board(self) -> None: """Function that sets up the board as the list""" print(f""" ------------------------- |\t{self.board[1]}\t|\t{self.board[2]}\t|\t{self.board[3]}\t| ------------------------- |\t{self.board[4]}\t|\t{self.board[5]}\t|\t{self.board[6]}\t| ------------------------- |\t{self.board[7]}\t|\t{self.board[8]}\t|\t{self.board[9]}\t| ------------------------- """) def place_marker(self, marker: str, position: int) -> None: """Function that places player's marker on board with specific position""" self.board[position] = marker def have_winning_position(self, mark) -> bool: """Method that checks every possible way to win the game""" return ((self.board[1] == mark and self.board[2] == mark and self.board[3] == mark) or # across the top (self.board[4] == mark and self.board[5] == mark and self.board[6] == mark) or # across the middle (self.board[7] == mark and self.board[8] == mark and self.board[9] == mark) or # across the bottom (self.board[1] == mark and self.board[4] == mark and self.board[7] == mark) or # left top to down (self.board[2] == mark and self.board[5] == mark and self.board[8] == mark) or # middle top to down (self.board[3] == mark and self.board[6] == mark and self.board[9] == mark) or # right top to down (self.board[1] == mark and self.board[5] == mark and self.board[9] == mark) or # diagonal-1 (self.board[7] == mark and self.board[5] == mark and self.board[3] == mark)) # diagonal-2 def check_the_cell(self, position: int) -> bool: """Check the specific cell on the board for emptiness""" return self.board[position] == " " def check_the_board(self): """Check if the board is full covered""" for i in range(1, 10): if self.check_the_cell(i): return False return True
true
39a4aee8be08db5c2e90b874a862ecbff87c1389
k1ll3rzamb0n1/Code_backup
/Undergrad/2012/Fall 2012/comp sim/plants-and-animals/plants and animals/plotter.py
2,124
4.125
4
# COMP/EGMT 155 # # Program to create a graphical plot of functions # stored as points read from a text file. # # This program will plot the output from the # plants_and_animals.py program. from graphics import * from string import * #--------------------------------------------------- # Function to transform a point in the # function's coordinate system to a point # in the graphics window's coordinate system. def transformPoint(p, x_min, y_min, x_max, y_max): x = p.getX() y = p.getY() if (x_max==x_min): x = 1 else: x = (x-x_min)/(x_max-x_min) if (y_max==y_min): y = 1 else: y = (y-y_min)/(y_max-y_min) x = x*win_x_size y = (1.0 - y)*win_y_size return Point(x,y) #--------------------------------------------------- # Function to plot a graph from points stored # in a text file. def plot(filename, color): # open the text file and read the number of points infile = open(filename, "r") s = split(infile.readline(), ",") x_min = float(s[0]) y_min = float(s[1]) x_max = float(s[2]) y_max = float(s[3]) num_points = int(infile.readline()) # for each point: for i in range(num_points): # read line of text containing point and # parse it into x and y values s = infile.readline() (s1, s2) = split(s, ",") x = float(s1) y = float(s2) # transform the point into the graphics # window coordinates p = transformPoint(Point(x,y), x_min, y_min, x_max, y_max) # Draw a circle to represent a transformed point c = Circle(p, 2) c.setFill(color) c.setOutline(color) c.draw(win) #--------------------------------------------------- # main program # define global parameters win_x_size = 600.0 win_y_size = 300.0 # create a graphics window win = GraphWin("Plotter", win_x_size, win_y_size) # plot data from three text files in different colors plot("animals.txt", "red") plot("plants.txt", "green") plot("sun.txt", "blue") # wait for a mouse click and then close the graphics win.getMouse() win.close()
true
025b2f7ba336976f61136ebe46f7e9228a859568
bendaw19/EntornosDesarrollo
/Tema 2/Actividad 3 VisualStudioCode.py
774
4.25
4
# En este ejercicio pide al usuario dos numeros por teclado y una operación, suma, resta, multiplicación o división. # Se evaluará los errores que se puedan introducir. # Posteriormente mostrará el resultado de la operación. try: numero1 = float(input("Introduce primer numero: ")) numero2 = float(input("Introduce segundo numero: ")) operacion= input("Introducir operación: ") except ValueError: print ("Se ha introducido una letra") else: if operacion == '+': print (numero1+numero2) elif operacion == '-': print (numero1-numero2) elif operacion == '*': print (numero1*numero2) elif operacion == '/': print (numero1/numero2) else: print ("Error al introducir en la operación")
false
11a8b6b733cb8b55e32149da5b17ba576c7faea5
Hunter-Chambers/WTAMU-Assignments
/CS3305/Demos/demo1/Python/timer.py
1,262
4.34375
4
#!/usr/bin/env python3 '''This file contains the Timer class''' from time import time, sleep class Timer: '''A class to model a simple timer''' def __init__(self): '''default constructor ''' self.start_time = 0 self.stop_time = 0 # end __init__ def start(self): '''start launches the timer at the current time''' self.start_time = time() # end start def stop(self): '''stop stops the timer at the current time''' self.stop_time = time() # end stop def duration(self): '''duration returns the number of nanoseconds between the start time and the stop time''' if self.stop_time - self.start_time < 0: raise RuntimeError("stop() invoked before start()") return int(self.stop_time - self.start_time) # end duration def run_timer(self, seconds): '''set_timer allows user to start a timer for some number of seconds''' self.start() sleep(seconds) self.stop() print("Ding . . .") # end run_timer def __str__(self): '''returns a string rendering of the current timer duration''' return str(self.duration()) # end __str__ # end class timer
true
f6c6add641c75fece52810cdd31dedcc4170025f
valdot00/hola_python
/7 bucles y condiciones/37_ejercicio_1.py
643
4.125
4
#37 ejercicio 1 #crea un dicionario con los siguientes pares de valores #manzana apple #naranje orange #platano banana #limon lemon #muestra la traducion para la palabra "naranja" #añade un elemento nuevo "piña" y pineaple" # haz un bucle para mostrar todos los elementos del dicionario diccionario={"manzana":"apple","naranja":"orange","platano":"banana","limon":"lemon"} print(diccionario["naranja"]) print("-----------") diccionario["piña"]="pineapple" print(diccionario) print("-----------") for clave,valor in diccionario.items(): print("{} en ingles es {}".format(clave,valor)) print("---------------------")
false
59f4a3c574d7e2ca588c5c13f9fd7309ceebf29c
valdot00/hola_python
/4 cadenas de texto/16_ejercicio_2.py
783
4.34375
4
#ejercicio #crear una variable "cadena" que contiene el texto "esto es un texto de ejemplo" #crear una variable "longitud" que contiene la longitud (numero de caracteres) de la variable "cadena" #crear una variable "mayusculas" que contiene la variable(cadena) en mayusculas # crear un variable "resultado" que concatene la variable "mayusculas" y la variable "resultado" convertida a string # print("----------------------------") cadena="esto es un texto de ejemplo" print(cadena) longitud=len(cadena) print(longitud) mayusculas=cadena.upper() print(mayusculas) resultado=str(mayusculas) print(resultado) print("----------------------------") print(type(longitud)) print(type(cadena)) resultado=mayusculas+" tiene longitud de " + str(longitud) print(resultado)
false
e7ab690072141453c17ff58dca413b67a2385f6d
vadim-vj/wh
/syllabuses/cs/problems/merge-sort/_.py
809
4.1875
4
def merge_ordered_lists(list1, list2): result = [] while list1 or list2: if list1 and list2: # `<` is important lst = list1 if list1[0] < list2[0] else list2 elif list1: lst = list1 elif list2: lst = list2 result.append(lst.pop(0)) return result def merge_sort(arr): length = len(arr) if length == 1: return arr middle = length // 2 return merge_ordered_lists( merge_sort(arr[:middle]), merge_sort(arr[middle:]) ) # --- if __name__ == "__main__": data = ( [3, 7, 2], [3, 4, 5, 7, 2, 3, 41, 2], [0, 0, 0, 0], [1, 2, 3, 4, 5], [9, 8, 7, 6, 5, 4, 3, 2, 1, 0], ) for arr in data: print(merge_sort(arr))
false
f6dbb5cef74dea564a35491e61e991f5bb2a2259
fsahin/algorithms-qa
/Recursive/PhoneNumberPermutation.py
729
4.21875
4
""" For any phone number, the program should print out all the possible strings it represents. For example 2 can be replaced by 'a' or 'b' or 'c', 3 by 'd' 'e' 'f' etc. """ d = { '0':"0", '1':"1", '2': "ABC", '3': "DEF", '4': "GHI", '5': "JKL", '6': "MNO", '7': "PQRS", '8': "TUV", '9': "WXYZ", } def permutatePhoneNum(number): ''' Assuming that you simply output the value itself for 1 and 0, ''' result = [] if len(number) == 1: return [i for i in d[number]] restPerm = permutatePhoneNum(number[1:]) for chr in d[number[0]]: for rest in restPerm: result.append(chr + rest) return result print permutatePhoneNum("0704")
true
fed28e9c2affe058cfb233be1cfa1f918c0cff51
ukms/pyprogs
/factorial.py
293
4.40625
4
def findFactorial(num): if num == 1 or num == 0: return 1 else: factorial = num * findFactorial(num -1) return factorial num = input(" Enter the number to find the Factorial: ") if num < 0: print -1 else: print "The Factorial is: ",findFactorial(num)
true
04ea54eb96992d447e5b0bcd8754274223a8d5f3
PrinceWangR/pywork
/chart3.py
2,130
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #age = 3; #if age >= 18: # print('Your age is' , age) # print('adult') #else: # print('Your age is' , age) # print('teenager') #input返回的是字符串 #born = input("birth:") #born = int(born) #if born < 2000: # print("00前") #else: # print("00后") #体重属性判断“体重/身高的平方”” #如:我身高1.71,体重60kg # height = 1.71 # weight = 60 # p = weight/(height*height) # if p <= 18.5: # print("过轻") # elif p <= 25: # print("正常") # elif p <= 28: # print("过重") # elif p <= 32: # print("肥胖") # else: # print("严重过胖") #特殊的循环 # classmates = ["Prince", "Mic", "Jack"] # for name in classmates: # print(name) # k = [1,2,3,4,5,6,7,8,9,10] # sum = 0 # for x in k : # sum = sum + x # print('The sum of 1 to 10 is:' , sum) #range()函数生成整数序列 # sum = 0 # for x in list(range(101)): # sum = sum + x # print('The sum of 1 to 100 is:', sum) #while循环 # n = 99 # sum = 0 # while n > 0 : # sum = sum + n # n = n - 2 # print('The sum of odd number below 99 is :' , sum) #循环按格式输出 # L = ['B', 'Pe','Ada'] # for name in L : # print('Hello,%s!' % name) #dict # d = {'Mic':95,'pet':75,'Jack':85} # print(d) # print('Mic\'s score is:',d['Mic']) # Add elements # d['Prince'] = 86#默认放在首位 # print(d) # 'Prince' in d #判断key-'Prince'是否在d中 # Delete key # d.pop('pet')#删掉'pet' # print(d) #set # s = set([1,2,3]) # print(s ) # s1 = set(['a','b','b']) # print(s1) # Add key # s1.add(1) # print('s1 添加key 1之后:',s1) # Delete key # s1.remove('b') # print('s1 删除key b之后:',s1) # s & s1#交集 # print('s and s1的交集是',s & s1) # s | s1#并集 # print('s and s1的并集是',s | s1) #试着将list放入set中 会报错 #s = set([1,'a',[1,'abs']]) #关于可变与不可变对象:str不可变;list可变 #str # s2 = 'abc'#s2指向'abc' # print('s2 is',s2) # s2.replace('a','A') # print('s2 is still',s2) # s3 = s2.replace('a','A') # print('s3 is',s3) # list # l =['a','c','b'] # print('The original l is',l) # l.sort() # print('The new l is',l)
false
a49360504955debdc1f902b8970de4fd8cf4d2a7
tdcforonda/codewars-practice
/Python/valid_parentheses.py
544
4.1875
4
def valid_parentheses(string): # your code here checker = 0 if string == "": return True for char in string: if char == "(": checker += 1 if char == ")": checker -= 1 if checker < 0: return False if checker == 0: return True else: return False print(valid_parentheses(" (")) print(valid_parentheses(")test")) print(valid_parentheses("")) print(valid_parentheses("hi())(")) print(valid_parentheses("hi(hi)()"))
true
841fda7005cd87d5f3ac6e9008d926058e0db87b
SDSS-Computing-Studies/003-input-darrinGone101
/task1.py
325
4.5
4
#! python3 """ Ask the user for their name and their email address. You will need to use the .strip() method for this assignment. Be aware of your (2 points) Inputs: name email Sample output: Your name is Joe Lunchbox, and your email is joe@koolsandwiches.org. """ name = str( input("input name:")).stip() email = str( Input("input name:"))
true
fb0dc1d767dcf929911a524a9e6b0d73ace35e8e
yangwangkong/python-xuexi
/字符串下标.py
262
4.28125
4
""" 使用字符串中特定的数据 这些字符会按顺序从0开始分配一个编号 -- 使用这个编号就可以精确找到这个字符 -- 即为索引或者下标,索引值 str1[下标] """ str1 = 'abcdefg' print(str1) print(str1[0]) print(str1[2])
false
b36f458c94cb92ecd441c81465cbcf0c2f6aea7f
yangwangkong/python-xuexi
/if嵌套.py
419
4.125
4
""" 1.准备将来要做的判断的数据:钱和空座 2.判断是否有钱:有钱,上车;没钱,不能上车 3.上车了:判断是否能坐下,有空座位和没有空座位 """ money = 1 seat = 1 if money == 1: print("请上车") if seat == 1: print("有空座位,可以坐下了") else: print("没有空座,站着等...") else: print("朋友,忘记带钱了?")
false
4d7c969ae9b87fdd268819fa2732b0d3213aaaec
yangwangkong/python-xuexi
/认识数据类型.py
542
4.21875
4
''' 1. 按经验将不同的变量存储不同的数据 2. 验证这些数据到底是什么类型--检测数据类型--type(数据) ''' # int--整形 num1 = 1 print(type(num1)) # float--浮点型 num2 = 1.1 print(type(num2)) # str--字符串 a = 'Hello world!' print(type(a)) # bool--布尔值 b = True print(type(b)) # list--列表 c = [10, 20, 30] print(type(c)) # tuple--元组 d = (10, 20, 30) print(type(d)) # set--集合 e = {10, 20, 30} print(type(e)) # dict--字典--键值对 f = {'name': 'tom', 'age': 18} print(type(f))
false
66c58c5a4739510a1209147258355d2af2d0eb30
eightarcher/hackerrank
/SimpleArraySum.py
768
4.25
4
""" Given an array of integers, can you find the sum of its elements? Input Format The first line contains an integer, , denoting the size of the array. The second line contains space-separated integers representing the array's elements. Output Format Print the sum of the array's elements as a single integer. Sample Input 6 1 2 3 4 10 11 Sample Output 31 Explanation We print the sum of the array's elements, which is: .1+2+3+4+10+11 = 31 """ #sample code #!/bin/python3 import sys n = int(input().strip()) arr = [int(arr_temp) for arr_temp in input().strip().split(' ')] #a = str("2 3 4 5 6 98") def arrsum(ray): toats = 0 for num in ray: toats = toats + num #print(toats) #print(toats) print(toats) arrsum(arr)
true
4a0a227a309e7b976951b23d36d148af14384198
LucaCappelletti94/dict_hash
/dict_hash/hashable.py
1,322
4.1875
4
class Hashable: """The class Hashable has to be implemented by objects you want to hash. This abstract class requires the implementation of the method consistent_hash, that returns a consistent hash of the function. We do NOT want to use the native method __hash__ since that is willfully not consistent between python instances, while we want a consistent hash. A tipical implementation of the consistent_hash method could be the following one: ..code::python from dict_hash import Hashable, sha256 class MyObject(Hashable): def __init__(self, a:int): self._a = a self_time = time() def consistent_hash(self)->str: # The self._time variable here is ignored because we want this # object to match also with objects created at other times. return sha256({ "a":self._a }) """ def consistent_hash(self) -> str: """Return consistent hash of the current object. Returns ------------------ A consistent hash of the object. """ raise NotImplementedError( "The method consistent_hash must be implemented" " by the child classes of Hashable." )
true
13466cd075e3ed41d71b05df3bb0a9ac86e80a1f
dAIsySHEng1/CCC-Junior-Python-Solutions
/2004/J1.py
208
4.1875
4
def squares(): num_tiles = int(input()) i = 1 a = i**2 while a <= num_tiles: i+= 1 a = i**2 b = str(i-1) print('The largest square has side length',b+'.') squares()
true
7af34baadaed3d48da49a5632025bbd058d1d7c8
dAIsySHEng1/CCC-Junior-Python-Solutions
/2015/J1.py
282
4.46875
4
def is_feb_18(): month = input() day = int(input()) if month == '1' or (month == '2' and day < 18): print('Before') elif (month != '1' and month != '2') or (month == '2' and day > 18): print('After') else: print('Special') is_feb_18()
false
b8840a75e87046562283642f0e11be187d7a1cf9
jmhernan/code4fun
/quartiles.py
1,413
4.25
4
# Given an array, 'arr', of 'n' integers, calculate the respective first quartile (Q1), second quartile (Q2), # and third quartile (Q3). It is guaranteed that Q1, Q2, and Q3 are integers. # Steps # 1. Sort the array # 2. Find the lower, middle, and upper medians. # If the array is odd then the middle element in the middle median (Q2) # If the array is even then the median is the middle_element + (middle_element -1)/2 = (Q2) n = 9 arr = [3, 7, 8, 5, 12, 14, 21, 13,18] def mdn(sorted_array): n_s = len(sorted_array) if n_s%2 != 0: median = sorted_array[int(n_s/2)] else: middle_1 = sorted_array[int(n_s/2)] middle_2 = sorted_array[int(n_s/2) - 1] median = (middle_1 + middle_2) / 2 return median # sort the input sorted_list = sorted(arr) int(len(sorted_list)/2) def qrt(number_list): sorted_list = sorted(number_list) lower = sorted_list[:int(len(sorted_list)/2)] upper = sorted_list[int(len(sorted_list)/2)+1:len(sorted_list)] Q2 = mdn(sorted_list) Q1 = mdn(lower) Q3 = mdn(upper) return print(int(Q1), int(Q2), int(Q3)) def quartiles(n, number_list): sorted_list = sorted(number_list) lower = sorted_list[:int(n/2)] upper = sorted_list[int(n/2)+1:n] Q2 = mdn(sorted_list) Q1 = mdn(lower) Q3 = mdn(upper) return print('\n',int(Q1),'\n',int(Q2),'\n',int(Q3)) quartiles(n=9, number_list = arr)
true
591375be5bf0f32ee9b52b076560e52ec8d2d2c0
MouseCatchCat/pythonStudyNote
/venv/Include/classes.py
1,122
4.21875
4
students = [] class Student: school_name = 'School' # constructor to init an obj def __init__(self, name, student_id=1, student_grade=0): self.name = name self.student_id = student_id self.student_grade = student_grade # override the print function basically, if I print the new created obj, it will return from this function # instead of a string of memory def __str__(self): return "student name: " + self.name + '\n' + "student id:" + str( self.student_id) + '\n' + "student grade: " + str(self.student_grade) def get_student_name_capitalized(self): return self.name.capitalize() def get_school_name(self): return self.school_name class HighSchool(Student): school_name = "The second high school" def get_student_name_capitalized(self): original_value = super().get_student_name_capitalized() return original_value + 'is in the school called: ' + self.get_school_name() john = HighSchool(name='john', student_id=4, student_grade=99) print(john) print(john.get_student_name_capitalized())
true
37a29bb134960c34710dd94d56c8f4410cf4d5e3
Yahya-Elrahim/Python
/Matplotlib/Scatter Plot/scatter.py
1,001
4.1875
4
# ------------------------------------------------------------- # ----------------------- Scatter ----------------------------- # Scatter plots are used to observe relationship between variables and uses dots to represent the relationship # between them. The scatter() method in the matplotlib library is used to draw a scatter plot. Scatter plots are # widely used to represent relation among variables and how change in one affects the other. import pandas as pd from matplotlib import pyplot as plt plt.style.use('seaborn') x = [5, 7, 8, 5, 6, 7, 9, 2, 3, 4, 4, 4, 2, 6, 3, 6, 8, 6, 4, 1] y = [7, 4, 3, 9, 1, 3, 2, 5, 2, 4, 8, 7, 1, 6, 4, 9, 7, 7, 5, 1] colors = [7, 5, 9, 7, 5, 7, 2, 5, 3, 7, 1, 2, 8, 1, 9, 2, 5, 6, 7, 5] sizes = [209, 486, 381, 255, 191, 315, 185, 228, 174,538, 239, 394, 399, 153, 273, 293, 436, 501, 397, 539] plt.scatter(x, y, s=sizes, c=colors, marker='o', cmap='Greens', edgecolors='black', alpha=0.9) bar = plt.colorbar() bar.set_label('Color Bar') plt.show()
true
58862e58468698bbe77a5405b78df4f948e48e33
CindyTham/Favorite-Meal-
/main.py
693
4.125
4
print('Hello, What is your name?') name = input('') print('Hello ' + name +', Let me get to know you a little better, Tell me about your Favourite meal?') respond = input ('') print ('Great, what is your favourite starter?') starter = input('') print('And your favourite main course?') main_course = input('') print('Great, lastly what about dessert?') dessert = input('') print('what is your fourite go to drink?') drink = input('') print('Let me repeat your favourite meal. Your starter would be ' + starter + ' your main course would be ' + main_course + ' and your favourite dessert is ' + dessert + ' and finally your go to drink is a ' + drink) print('Now that sounds delish!!')
true
e2c06777f29b4f3308029c54bb2e83b060627dc4
dbconfession78/holbertonschool-webstack_basics
/0x01-python_basics/15-square.py
1,296
4.25
4
#!/usr/bin/python3 """ Module 15-square """ class Square: """ class definition for 'Square' """ def __init__(self, size=0): """ Square class initialization """ self.__size = size def __repr__(self): """ __repr__ for the Square class """ return self def __str__(self): """ __str__ for the Square class """ retval = "" for i in range(self.__size): s = "" if i < self.__size-1: s = "\n" retval += "{}{}".format(("#" * self.__size), s) return retval @property def size(self): """ size: getter """ return self.__size @size.setter def size(self, value): """ size setter :value: size to set """ if type(value) != int: raise TypeError("size must be an integer") if value < 0: raise ValueError("size must be >= 0") self.__size = value def area(self): """ returns the current square area """ return self.__size**2 def my_print(self): """" prints in stdout the squre with the character # """ print(str(self))
false
0a8a2e3035a8329e9da15b572fb51398ea291289
erikkvale/algorithms-py
/sort/selection_sort.py
740
4.34375
4
def find_smallest(_list): """ Finds the smallest integer in an array >>> demo_list = [4, 5 , 2, 6] >>> find_smallest(demo_list) 2 """ smallest = _list[0] smallest_idx = 0 for idx, num in enumerate(_list): if num < smallest: smallest = num smallest_idx = idx return smallest_idx def selection_sort(_list): """ Uses helper function to sort list >>> demo_list = [4, 5, 2, 6] >>> selection_sort(demo_list) [2, 4, 5, 6] """ new_list = [] for i in range(len(_list)): smallest = find_smallest(_list) new_list.append(_list.pop(smallest)) return new_list if __name__=='__main__': import doctest doctest.testmod()
true
29e6efc7ed814dd9228ea9da15dc42cff8ca14a0
coderrps/Python-beginners
/newcode_11.py
206
4.40625
4
#exponents (2**3) used as 2^3 def raise_to_power(base_num, pow_num): result = 1 for index in range(pow_num): result = result * base_num return result print(raise_to_power(4,2))
true
187e9470b42a049edd81f56ff46e443570e69a3e
danjgreene/python
/Coursera - Python 1 & 2/coursera_intro_py_pt2/wk5/wk5A_lsn1_practice1.py
823
4.3125
4
# Echo mouse click in console ################################################### # Student should enter code below # Examples of mouse input import simplegui import math # intialize globals WIDTH = 450 HEIGHT = 300 # define event handler for mouse click, draw def click(pos): print "Mouse click at " + str(pos) # create frame frame = simplegui.create_frame("Mouse selection", WIDTH, HEIGHT) frame.set_canvas_background("White") # register event handler frame.set_mouseclick_handler(click) # start frame frame.start() ################################################### # Sample output #Mouse click at (104, 105) #Mouse click at (169, 175) #Mouse click at (197, 135) #Mouse click at (176, 111) #Mouse click at (121, 101) #Mouse click at (166, 208) #Mouse click at (257, 235) #Mouse click at (255, 235)
true
c3ce682b36d98cb5b2c331694392411c6781d001
c0d1f1c4d0r/tryinggit
/exercicios_curso_em_video/exerc006.py
282
4.125
4
# Exercício Python 006: Crie um algoritmo que leia um número e mostre o seu dobro, triplo e raiz quadrada. n = float(input('Insira um número: ')) print('O número inserido foi {} seu dobro é {} seu triplo é {} e sua raiz quadrada é {}'.format(n, (n*2), (n*3), (n ** (1/2))))
false
edbde5c1980e9947ed07222c875f7f42f864efcb
sushantchandanwar/Assignment_01
/42_CheckSubstringInString&LengthOfString.py
969
4.15625
4
# Method1: Using user defined function. # function to check if small string is # there in big string def check(string, sub_str): if (string.find(sub_str) == -1): print("NO") else: print("YES") # driver code string = "geeks for geeks" sub_str = "geek" check(string, sub_str) # method-2 def check(s2, s1): if (s2.count(s1) > 0): print("YES") else: print("NO") s2 = "A geek in need is a geek indeed" s1 = "geek" check(s2, s1) # method-3 # When you have imported the re module, you can start using regular expressions. import re # Take input from users MyString1 = "A geek in need is a geek indeed" MyString2 ="geek" # re.search() returns a Match object if there is a match anywhere in the string if re.search( MyString2, MyString1 ): print("YES,string '{0}' is present in string '{1}' " .format(MyString2,MyString1)) else: print("NO,string '{0}' is not present in string {1} " .format(MyString2, MyString1) )
true
204c3817555e95c26eb82523001a7d92c6cd5677
sushantchandanwar/Assignment_01
/30_PositveNoList.py
328
4.375
4
# Python program to print positive Numbers in a List # method-1 list1 = [11, -21, 0, 45, 66, -93] for num in list1: if num >= 0: print(num, end=" ") # method-2 # list1 = [-10, -21, -4, 45, -66, 93] # # # using list comprehension # n = [x for x in list1 if x >= 0] # # print("Positive numbers in the list: ", *n)
true
843a3fd9dee6d2a37b81b91c982baef4b7edc43d
clayboone/project-euler
/src/problem003/solution.py
668
4.15625
4
import math def lpf(n: int) -> int: """Return the largest prime factor of a number `n`""" # Algorithm found online. Comments are for my understanding. assert n > 1 max_prime = None # where n is 110, primes are [2, 5, 11] # Strip the number of 2s that divide n while n % 2 == 0: max_prime = 2 n >>= 1 # n /= 2 # n is odd now (55), primes are [5, 11] for i in range(3, int(math.sqrt(n)) + 1, 2): # range(3, 8, 2) = [3, 5, 7] while n % i == 0: max_prime = i n //= i # n (11) is still > 2 and must be prime if n > 2: max_prime = n return int(max_prime)
false
951bf4357da6caeea01211d980fd694036518bb7
joeryan/100days
/cybrary.py
1,114
4.25
4
# cybrary1.py # exercise 1: practical applications in python # adapted and expanded from cybrary.it video course # Python for Security Professionals at www.cybrary.it/course/python # used to improve pytest understanding and overall python knowledge import platform import numbers # 1. determine if the input is odd or even def check_even(num): if num % 2 == 0: return True else: return False # 2. return the sum of two input values def sum_numbers(nums): accum = 0 for num in nums: accum += num return accum # 3. given a list of integers, determine how many are even def count_even_numbers(nums): count = 0 for num in nums: if num % 2 ==0: count += 1 return count # 4. answer the input string backwards def reverse_string(input_string): if len(input_string) > 0: input_string = ''.join(reversed(input_string)) return input_string # 5. determine if input string is a palindrome def is_palindrome(input_string): return input_string.lower() == reverse_string(input_string.lower()) if __name__ == '__main__': print("designed to be run with cybrary_menu.py")
true
488899ba082277204541e5227250ba3ee0571684
khurath-8/SDP-python
/assignment1_areaoftriangle_58_khurath.py
234
4.21875
4
#PROGRAM TO FIND AREA OF TRIANGLE height=float(input("enter the height of triangle:")) base=float(input("enter the base of the triangle:")) aot=(height*base)/2 print("area of triangle is :",aot)
true
c54432a3b333ab2ba233568328f7971f60e63f61
joneskys7/pi
/NESTED IF.py
714
4.1875
4
while True: a=(raw_input("please enter value of A")) b=(raw_input("please enter value of B")) if a>b: print "A is greater" c=(raw_input("please enter value of c")) d=(raw_input("please enter value of d")) if c>d: print "c is greater" if c<d: print "d is greater" else: print "equal" if b>a: print "B is greater" e=(raw_input("please enter value of e")) f=(raw_input("please enter value of f")) if e>f: print "e is greater" if e<f: print "f is greater" else: print "equal" else: print "both are equal"
true
68f5968fd6b077983bee5ffee8ea059d65a08b3f
joneskys7/pi
/IF GREATER.py
246
4.1875
4
while True: a=(int(input("please enter value of A"))) b=(int(input("please enter value of B"))) if a>b: print "A is greater" if b>a: print "B is greater" if a==b: print"Both are equal"
true
9c94768e58be59b312f7c37dc578bec5395e21f1
Baobao211195/python-tutorial
/data_structure/tuple.py
558
4.28125
4
print(""" + tap hop cac element phan tach nhau bang giau phay + tuple is immutable object + if element of type is mutable object, we can modify these mutable objects + Thuc hien packing and unpacking """) tp = 23, 32, 54, "oanh" print("type of tp : ", type(tp)) print(tp) tp = tp, ([1,2,1]) print ("new tp ", tp) print("old value of mutable object (list) ", tp[1][1]) tp[1][1] = 323 print("new value after change ", tp) x= 12 y = 23 z = "dfd" t = () t = x, y, z # packing tuple print(t) a, b, c = t # unpacking tuple print(a) print(b) print(c)
false
75b49068bfa72485b42356d3d2b533635ad8d515
leerobertsprojects/Python-Mastery
/Advanced Python Concepts/Functional Programming/Common_Functions.py
830
4.21875
4
from functools import reduce # map, filter, zip & reduce #map def multiply_by2(item): return item*2 print(list(map(multiply_by2, [1,2,3]))) mylist = [2,3,4] def multiply_by3(item): return item*3 def check_odd(item): return item % 2 != 0 print(list(map(multiply_by3, mylist))) print(mylist) # filter print(list(filter(check_odd, mylist))) # it will filter out the what the function asked to check for # zip new_list = 'hello' my_list = 'james' new_list1 = [1,2,3] my_list1 = [10,20,30] print(list(zip(my_list, new_list))) print(list(zip(my_list1, new_list1))) #works with any iterable including strings # reduce new_list2 = [1,2,3] def accumulator(acc, item): print(acc, item) return acc + item print(reduce(accumulator, new_list2, 0)) #reduce reduces multiple values down to a sinlge value
true
620694b8fb9e64c13116b42e7856c515e62927ff
vaibhavnaughty/Fibonachi-series
/series.py
249
4.21875
4
# Using Loop # Vaibhav Verma # Print nth series n = int(input("Enter the value of 'n': ")) n1 = 0 n2 = 1 sum = 0 count = 1 print("Fibonacci Series: ", end = " ") while(count <= n): print(sum, end = " ") count += 1 n1 = n2 n2 = sum sum = n1 + n2
false
2ef17d1392c4b6bbefdd46d9903710856d660d44
bradmann/projectEuler
/problem002.py
386
4.125
4
from math import sqrt import sys def fibonacci(value): rho = (1 + sqrt(5)) / 2 return int((rho**value - (-1/rho)**value) / sqrt(5)) if __name__ == "__main__": upperBound = int(sys.argv[1]) i = 3 fibValue = fibonacci(i) fibSum = 0 while fibValue <= upperBound: fibSum += fibValue i += 3 fibValue = fibonacci(i) print(fibSum)
false
6a486c3807ab428f11ceae22c4996ce363855670
heyese/hackerrank
/2d array.py
1,189
4.125
4
#https://www.hackerrank.com/challenges/2d-array/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=arrays def hour_glass_sum(x,y, arr): """ arr is a list of lists. 0,0 is top left element in arr (x,y) -> x is the column, y is the row. (3,2) is 4th element in 3rd row (x,y) is used to identify the top left point of the hourglass. :return: sum of the 'hourglass', as defined in the question, or None if an hourglass doesn't exist at point (x,y) """ sum = 0 for i in range(3): for j in range(3): if x + i < len(arr[y]) and y + j < len(arr): if not (j == 1 and i in {0, 2}): sum += arr[y+j][x+i] else: return None return sum def max_hour_glass_sum(arr): max_sum = None for x in range(len(arr[0])-2): for y in range(len(arr)-2): max_sum = hour_glass_sum(x, y, arr) if max_sum is None else max(max_sum, hour_glass_sum(x, y, arr)) return max_sum arr = [] arr.append([1,2,3,4,5]) arr.append([1,2,3,4,5]) arr.append([1,2,3,4,5]) arr.append([1,2,3,4,5]) print(max_hour_glass_sum(arr))
true
cc6d22f51a9967266106aae9a8840984b031a824
khizra-ali/Python-Practice
/result.py
724
4.1875
4
English=int(input("enter obtained marks in English: ")) Pak_Studies=int(input("enter obtained marks in Pakistan Studies: ")) Sindhi=int(input("enter obtained marks in Sindhi: ")) Chemistry=int(input("enter obtained marks in Chemistry: ")) Biology=int(input("enter obtained marks in Biology: ")) obtained_marks=English+Pak_Studies+Sindhi+Chemistry+Biology print(obtained_marks) total_marks=int(input("enter total marks: ")) percentage=(obtained_marks/total_marks)*100 print(percentage) if percentage >= 80: print("Grade is A+") elif percentage >= 70: print("Grade is A") elif percentage >= 60: print("Grade is B") elif percentage >= 50: print("Grade is D") else: print("Fail")
false
b2382a0966607257a1e18123c9b1061aeae1590c
khizra-ali/Python-Practice
/list.py
830
4.15625
4
#list employee_list = ["umair", "ali", "amir", "danish", "hamza", 5,7,8] employee_age = [22,33,23,26,28] print(employee_list) print("employee name is: "+str(employee_list[6])) print("employee name is: "+str(employee_list[7])) print("employee name is: "+str(employee_list[1]) +"employee age is: "+ str(employee_age[1])) employee_data = ["umair", 22 , "karachi"] employee_data.append("Pakistan") #add value in last print(employee_data) employee_data[2] = "Lahore" #edit 2nd index value print(employee_data) employee_data.insert(1, "khan") #insert value at 1st index print(employee_data) employee_data.pop() #remove last index value print(employee_data) del employee_data[1] #delete value of mentioned index print(employee_data) employee_list.remove("ali") #removve any value you mention print(employee_list)
false
c3881a0b59adb0fd8d3ab4b8717c5fd9a9f725db
puglisac/hackerrank-practice
/arrays_ds.py
370
4.46875
4
""" Function Description Complete the function reverseArray in the editor below. reverseArray has the following parameter(s): int A[n]: the array to reverse Returns int[n]: the reversed array >>> reverse_array([1, 2, 3]) [3, 2, 1] """ def reverse_array(arr): reversed=[] for i in range(0,len(arr)): reversed.append(arr.pop()) return reversed
true
d6d0bcb2dbb50a00693bc1a56103da506ebfb75f
dzzgnr/colloquium
/3.py
1,249
4.15625
4
''' 3. Створіть масив з п'яти прізвищ і виведіть їх на екран стовпчиком, починаючи з останнього ''' arr = [] #инициализация массива print('enter 5 surnames : ') for i in range(5): el = input() #ввод фамилии arr.append(el) #добавление в массив print('\narr :', arr, '\n') for i in range(5): print(arr[4 - i]) #вывод фамилий с конца ''' 4. Створіть масив з п'яти прізвищ і виведіть на екран ті з них, які починаються з певної букви, яка вводиться з клавіатури. ''' arr = [] #инициализация массива print('enter 5 surnames : ') for i in range(5): el = input() #ввод фамилии arr.append(el) #добавление в массив print('\narr :', arr) print('\nenter the letter for which surname will be displayed : ') letter = input() #ввод буквы print('\n') for i in range(5): if (arr[i])[0] == letter: #если первая буква фамилии совпадает с вводом - выводим фамилию print(arr[i])
false
0f887fd140fe691a2a8d69dc70feb7c035f04ddf
Sourav692/100-Days-of-Python-Code
/Day 1/1. array_longest_non_repeat_solution.py
1,117
4.3125
4
# --------------------------------------------------------------- # python best courses https://courses.tanpham.org/ # --------------------------------------------------------------- # Challenge # # Given a string, find the length of the longest substring # without repeating characters. # Examples: # Given "abcabcbb", the answer is "abc", which the length is 3. # Given "bbbbb", the answer is "b", with the length of 1. # Given "pwwkew", the answer is "wke", with the length of 3. # --------------------------------------------------------------- def longest_non_repeat(str): # init start position and max length i=0 max_length = 1 lis1 = list(str) for i in range(0,len(lis1)-1): sub_str=[] # continue increase sub string if did not repeat character while (i < len(str)) and (str[i] not in sub_str): sub_str.append(str[i]) i = i + 1 # update the max length if len(sub_str) > max_length: max_length = len(sub_str) print(sub_str) return max_length str1 = "abcabcbb" print(longest_non_repeat(str1))
true
da7b84bdc7883e02407b47f49c2c8fbeb0dbe24d
tanu312000/pyChapter
/linksnode.py
2,609
4.125
4
class Node: def __init__(self, val, next_ref): self.val = val; self.next = next_ref; # Global variable for header and tail pointer in singly linked list. head = tail = None; # appends new node at the end in singly linked list. def append_node(val): global head, tail; node = Node(val, None); if head is None: head = node; else: tail.next = node; tail = node; # inserts new node at specific position in singly linked list. def insert_node(val, position): global head, tail; current_node = head; while (position > 1): position -= 1; current_node = current_node.next; temp_next = current_node.next; node = Node(val, temp_next); current_node.next = node; # prints singly linked list values. def print_list(): global head, tail; print("Single linked list"); current_node = head; print "head -->",; while (current_node is not None): print current_node.val, "-->",; current_node = current_node.next; print "End"; # removes matching first node for particular value in linked list. def remove_node(val): global head, tail; current_node = head; previous_node = None; while (current_node is not None): if current_node.val == val: if previous_node is not None: previous_node.next = current_node.next; else: head = current_node.next; previous_node = current_node; current_node = current_node.next; # reverses singly linked list values. def reverse_linked_list(): global head, tail; current_node = head; previous_node = None; while (current_node is not None): next_node = current_node.next; current_node.next = previous_node; previous_node = current_node; current_node = next_node; head = previous_node; # getting nodes count in singly linked list. def count(): global head, tail; current_node = head; counter = 0; while (current_node is not None): counter += 1; current_node = current_node.next; print "Single linked list node count:", counter; if __name__ == "__main__": append_node(20); append_node(13); append_node(24); append_node(56); print_list(); insert_node(45, 2); print "After insert node at 2"; print_list(); remove_node(13); print "After removal of node 13"; print_list(); reverse_linked_list(); print "After reversing singly linked list"; print_list(); count();
true
84277dde39dc9b9ba32d48ee811154c9ca1bf363
kelraf/ifelif
/learn python 3/ifelif.py
872
4.3125
4
#The program asks the user to input an intager value #The program evaluates the value provided by the user and grades it accordingly #The values provided must be between 0 and 100 #caution!!! if you provide other values other than ints the program will provide errors marks=int(input("Please enter Students marks to Grade:")) if marks >= 0: if marks >= 0 and marks <=20: print('The grade is E') elif marks >= 21 and marks <= 45: print('The grade is D') elif marks >= 46 and marks <= 55: print('The grade is C') elif marks >= 56 and marks <= 80: print('The grade is B') elif marks >=81 and marks <=100: print('The grade is A') else: print('The value you entered is invalid') else: print('The value you entered is invalid') print('Done. Thank you')
true
907c2116937946b84cdd771730ca9d41576730d1
TroGenNiks/python_for_beginers
/basics/string.py
473
4.21875
4
str = "Welcome in my world ." print(str) print(str[:5]) # print upto 5 print(str[2:]) # print from 2 print(str[0::2]) # print by skipping 1 letter print(str[::-1]) # reverse the string # functions of string print(str.isalnum()) # checking string for alphanumeric or not print(str.lower()) # converting into lower print(str.upper()) # converting into upper print(str.find("in")) # finding inn string print(str.replace("in","nisarg in")) # replacing one letter in string.
true
76e6460bf21370cdf4262a3da40eae1f6f07798e
meksula/python-workspace
/bootcamp/section_3/strings.py
1,277
4.28125
4
# komendy linuxa możemy wywoływać za pomocą metod z przestrzeni `os` import os print('Python test') #output = os.system('ps aux') ############ # string w Pythonie można traktować jako niemutowalną tablicę znaków nameDisordered = 'alrok' name = nameDisordered[4] + nameDisordered[0] + nameDisordered[2] + nameDisordered[3] + nameDisordered[1]; print(name); # Możemy też liczyć znaki w stringu od tyłu: nameBottom = nameDisordered[-1] + nameDisordered[-5] + nameDisordered[-3] + nameDisordered[-2] + nameDisordered[-4]; print(nameBottom); print('Is both strings are equals?: ' + str(name == nameBottom)) # Możemy też wyznaczać zakres (jak substring() w javie) print('After slice: ', name[2:]) print(name[0:2] + nameBottom[2:]) print(name[1:3]) # Można też określić wartość 'kroku' co ile elementów w danym stringu będzie branych pod uwagę fullNames = name + ' Meksuła' print(fullNames[::2]) # Program przejdzie po stringu i wybierze co drugą literę # No i oczywiście możemy podać wszystkie 3 parametry: print(fullNames[1:5:2]) # od indexu nr. 1 do indexu nr. 5 co drugi znak # Zauważ, że możesz w ten sposób zrobić reverse() stringa, przechodząc przez index od tyłu: print(fullNames[::-1]) word = 'Hello World' result = word[-3]
false
c001dc7306530a377450ac57337cab0d7880e998
kgrozis/netconf
/bin/2.4 Matching and Searching for Text Patterns.py
2,343
4.375
4
''' Title - 2.4. Matching & Searching for Text Patterns Problem - Want to match or search text for a specific patterns Solution - If match is a simple literal can use basic string methods ''' text = 'yeah, but no, but yeah, but no, but yeah' # Exact match print('Exact Match:', text == 'yeah') # Match at start or end print('Starts with:', text.startswith('yeah')) print('Ends with:', text.endswith('no')) # Search for the location of the first occurence print('Find:', text.find('no')) # Use regular expressions and the re module for complicated matching text1 = '11/27/2012' text2 = 'Nov 27, 2012' import re # Simple matching: \d+ means match one or more digits if re.match(r'\d+/\d+/\d+', text1): print('yes') else: print('no') if re.match(r'\d+/\d+/\d+', text2): print('yes') else: print('no') # For lots of matching on the same pattern precomplie regular expression into a pattern obj datepat = re.compile(r'\d+/\d+/\d+') if datepat.match(text1): print('yes') else: print('no') if datepat.match(text2): print('yes') else: print('no') # findall() method finds all occurance of text text = 'Today is 11/27/2012. PyCon starts 3/12/2013.' print(datepat.findall(text)) # Create capture group by enclosing parts of the pattern in parentheses # The contents of each group can be extracted individually datepat = re.compile(r'(\d+)/(\d+)/(\d+)') m = datepat.match('11/27/2012') print('m:', m) # Extract the contents of each group print('m0', m.group(0)) print('m1', m.group(1)) print('m2', m.group(2)) print('m3', m.group(3)) print('m', m.groups()) month, day, year = m.groups() # Find all matches (notice splitting into tuples) # Finds all text matches and returns them as list print(text) print('findall:', datepat.findall(text)) for month, day, year in datepat.findall(text): print('{}-{}-{}'.format(year, month, day)) # find matches iteratively # returns as tuples for m in datepat.finditer(text): print(m.groups()) # match() only checks the beginning of a string m = datepat.match('11/27/2012abcdef') print(m) print(m.group()) # use end-maker ($) for an exact match datepat = re.compile(r'(\d+)/(\d+)/(\d+)$') print(datepat.match('11/27/2012abcdef')) print(datepat.match('11/27/2012')) # Skip compilation & use module level functiono in re module() print(re.findall(r'(\d+)/(\d+)/(\d+)', text))
true
2aa611cce77b26f6ec0eca14d32e703d7cc4cf36
emlam/CodingBat
/List-1/first_last6.py
469
4.125
4
def first_last6(nums): """ Given an array of ints, return True if 6 appears as either the first or last element in the array. The array will be length 1 or more. first_last6([1, 2, 6]) → True first_last6([6, 1, 2, 3]) → True first_last6([13, 6, 1, 2, 3]) → False """ if nums[0] == 6: return True elif nums[len(nums) - 1] == 6: return True else: return False first_last6([13, 6, 1, 2, 3])
true
f5f21b70304bc006ef8e67593ef13a257d318767
AChen24562/Python-QCC
/Week-1/VariableExamples_I/Ex7a_numbers_integers.py
754
4.25
4
# S. Trowbridge 2020 # Expression: 5+2 # + is the operator # 5 and 2 are operands # Expression: num = 5+2 # = is called assingment, this is an assignment operation # integers and basic maths print(5+2) # addition print(5-2) # subtraction print(5*2) # multiplication print("") print(5/2) # floating-point division (results in floating point answer) print(5//2) # integer or floor division (truncates the floating point information) print(5%2) # modulo division (returns the integer remainder of a division operation) print("") print(5**2) # exponentiation a**b is the same as a to the b power print("") # basic order of operations print( 5+5/2 ) # division happens before addition print( (5+5)/2 ) # addition happens before division print("")
true
48453ed9edda73bb3a756d220d98fe763774562c
AChen24562/Python-QCC
/Week-1/VariableExamples_I/Ex6_type_casting.py
424
4.28125
4
# Chap2 - Variables #type casting from float to integer x = int(2.8) print(x,type(x)) #type casting from string to integer x = int("3") print(x,type(x)) #type casting from integer to float y = float(1) print(y,type(y)) #type casting from string to float y = float("3.8") print(y,type(y)) #type casting from integer to string z = str(1) print(z,type(z)) #type casting from float to string z = str(1.0) print(z,type(z))
true
89516e62abc9a2e12dd14c65cb2750a4088b2ae7
AChen24562/Python-QCC
/Week-2-format-string/Week-2-Strings.py
292
4.1875
4
address = '5th Avenue' print('5th Avenue') print(address) print("This string has a 'quotation' in it") item1 = "apples" item2 = "pears" number = 574 message = f"I want to buy {number} {item1} and {item2}." print(message) message = f"Hi, do you want to buy {number} {item1}?" print(message)
true
a2e9857ca65fe8486937e6a632996f5347b7f724
AChen24562/Python-QCC
/Exam2/Q10.py
911
4.5625
5
'''a) Create a dictionary, people, and initialize it with the following data: 'Max': 15 'Ann': 53 'Kim': 65 'Bob': 20 'Joe': 5 'Tom': 37 b) Use a loop to print all items of the dictionary people as follows: name is a child (if the value is younger than 12). name is a teenager (if the value is younger than 20). name is an adult (if the value is younger than 65). name is a senior citizen (if the value is 65 or older). Example Output Max is a teenager. Ann is an adult. Kim is a senior citizen. Bob is an adult. Joe is a child. Tom is an adult.''' people = { "Max": 15, "Ann": 53, "Kim": 65, "Bob": 20, "Joe": 5, "Tom": 37} for names, age in people.items(): if age < 12: print(f"{names} is a child") elif age < 20: print(f"{names} is a teenager") elif age < 65: print(f"{names} is an adult") else: print(f"{names} is a senior citizen")
true
e7dac55232da561490983510b4d0ec74d289a2c4
AChen24562/Python-QCC
/Exam2-Review/Review2-input-if.py
212
4.3125
4
num = int(input("Enter an integer number: ")) # Determine if input is negtive, positive or zero if num < 0: print("Negative") else: if num == 0: print("Zero") else: print("Positive")
true
d63e95c3988f731fc95b7fb25d0b2219fe7fee23
ledbagholberton/holbertonschool-machine_learning
/pipeline/0x03-data_augmentation/2-rotate.py
348
4.15625
4
#!/usr/bin/env python3 """ Write a function that rotates an image by 90 degrees counter-clockwise: image is a 3D tf.Tensor containing the image to rotate Returns the rotated image """ import tensorflow as tf import numpy as np def rotate_image(image): """Rotate image""" flip_2 = tf.image.rot90(image, k=1, name=None) return flip_2
true
76ae676219453fdcbc8218dbc8a0ee6f98e8eee0
ledbagholberton/holbertonschool-machine_learning
/math/0x06-multivariate_prob/multinormal.py
2,625
4.25
4
#!/usr/bin/env python3 """ data is a numpy.ndarray of shape (d, n) containing the data set: n is the number of data points d is the number of dimensions in each data point If data is not a 2D numpy.ndarray, raise a TypeError with the message data must be a 2D numpy.ndarray If n is less than 2, raise a ValueError with the message data must contain multiple data points Set the public instance variables: mean - a numpy.ndarray of shape (d, 1) containing the mean of data cov - a numpy.ndarray of shape (d, d) containing the covariance matrix data You are not allowed to use the function numpy.cov""" import numpy as np class MultiNormal: """Class Multivariate Normal distribution""" def __init__(self, data): "Constructor" if not isinstance(data, np.ndarray): raise TypeError("data must be a 2D numpy.ndarray") elif len(data.shape) is not 2: raise TypeError("data must be a 2D numpy.ndarray") elif data.shape[1] < 2: raise ValueError("data must contain multiple data points") else: X = data.T d = data.shape[0] mean = np.sum(X, axis=0)/X.shape[0] self.mean = np.mean(data, axis=1).reshape(d, 1) a = X - mean b = a.T c = np.matmul(b, a) self.cov = c/(X.shape[0] - 1) def pdf(self, x): """Function calculate PDF Probability Density Function x is a numpy.ndarray of shape (d, 1) containing the data point whose PDF should be calculated d is the number of dimensions of the Multinomial instance If x is not a numpy.ndarray, raise a TypeError with the message x must by a numpy.ndarray If x is not of shape (d, 1), raise a ValueError with the message x mush have the shape ({d}, 1) Returns the value of the PDF""" if not(isinstance(x, np.ndarray)): raise TypeError("x must be a numpy.ndarray") cov = self.cov if (len(x.shape) is not 2 or x.shape[1] is not 1 or x.shape[0] is not cov.shape[0]): raise ValueError("x must have the shape ({}, 1)". format(cov.shape[0])) else: cov = self.cov inv_cov = np.linalg.inv(cov) mean = self.mean D = cov.shape[0] det_cov = np.linalg.det(cov) den = np.sqrt(np.power((2 * np.pi), D) * det_cov) y = np.matmul((x - mean).T, inv_cov) pdf = (1 / den) * np.exp(-1 * np.matmul(y, (x - mean)) / 2) return pdf.reshape(-1)[0]
true
32aa2a887039e511d35daf6768de28d9d301eda9
xzhou29/symbolic-fuzzer-1
/examples/check_triangle.py
1,373
4.25
4
def is_divisible_by_3_5(num: int, num2: int): num = 15 if num % 3 == 0: if num % 5 == 0: return True else: return False return False def is_divisible_by_3_5_without_constant(num: int, num2: int): if num % 3 == 0: if num % 5 == 0: return True else: return False return False def check_triangle(a: int, b: int, c: int): if a == b: if a == c: if b == c: return "Equilateral" else: return "Isosceles" else: return "Isosceles" else: if b != c: if a == c: return "Isosceles" else: return "Scalene" else: return "Isosceles" def check_triangle2(a: int, b: int, c: int): a = 10 if not is_divisible_by_3_5_without_constant(a, b): return 'Failed' if a == b: if a == c: if b == c: return "Equilateral" else: return "Isosceles" else: return "Isosceles" else: if b != c: if a == c: return "Isosceles" else: return "Scalene" else: return "Isosceles"
false
03f1cec6035b6e629fe729f17d157afd52779995
jrieraster/pildoras
/08_tuplas.py
642
4.1875
4
miTupla=("Juan",13,7,1995) print(miTupla) print(miTupla[2]) miLista=list(miTupla) #"List" Asigno a una lista la tupla print(miLista) #Notar que cambia los () por [] myList=["teto","Tito", False,5,18,21.9,18] myTuple=tuple(myList) # "Tuple" Para convertir una lista a una tupla print(myTuple) print("teto" in myTuple) print(myTuple.count(18)) # Cuenta cuanta vces esta el valor "18" print(len(myTuple)) tuplaUni=("Juan",) # Esto es oara definir unta tupla unitaria. Prestarle atención a la "," print(len(tuplaUni)) tuplaSin="pepo", 13, 8, 9.8 # Poner una tupla sin parentesis se denomina "empaquetado de tupla" print(tuplaSin)
false
18cb1709c41d781f819fd31dfa3e28da5b181be9
Fiskk/Project_Euler
/#1.py
1,505
4.3125
4
#Steffan Sampson #11-8-2017 #Project Euler Problem 1 def sum_of_multiples(): print("This function finds the sums of multiples of integers below an upper bound") print("This function takes in an upper bound") print("As well as the numbers to be used to find the multiples") #low_end = int(input("Please input your lower bound: ")) high_end = int(input("Please input your upper bound: ")) stop = False ints = [] print("Please input values > 0 to be used to find multiples below the bound, to stop inputting input '-1'") while stop is False: value = int(input("Value: ")) if value > 0 and value % 1 == 0: ints.append(value) elif value == -1: stop = True else: print("Input either an integer > 0 or -1") print(ints) print(str(high_end) + "\n") num_of_values = len(ints) - 1 list_of_multiples = [] n = 0 z = 1 while n <= num_of_values: multiple = ints[n] * z #print(multiple) if multiple < high_end: list_of_multiples.append(multiple) z += 1 else: n += 1 z = 1 print(list_of_multiples) num_of_multiples = len(list_of_multiples) - 1 #set_of_multiples = set(list_of_multiples) #unique_list_of_multiples = [set_of_multiples] total = 0 n = 0 while n <= num_of_multiples: total += list_of_multiples[n] n += 1 print(total) sum_of_multiples()
true
18ec76f38dd7a8e9405d351a4e2e3f6b794296b8
sainathprabhu/python-class
/Assertion.py
359
4.1875
4
#assert is a keyword to check values before performing the operations def multiplication(a,b): assert(a!=0), "cannot perform the operation" #makes sure that a is not zero assert(b!=0), "cannot perform the operation" #makes sure that b is not zero return(a*b) print(multiplication(3,0)) #print(multiplication(0,2)) #print(multiplication(3,32))
true
b6bd7b83c8d50a8dc499c6efccbf237f480df0f9
Debu381/Coding-battel
/2.py
1,609
4.15625
4
def pattern(number): li = list() # to store of lists num=1 # to initiate for i in range(1, number+1): x = list() # to create a temporary list for j in range(1 , i+1): x.append(str(num)) # append string form of number in list for join function num += 1 # number increment li.append(x) # append temporary lists in main list for i in li: print('*'.join(i)) # for upper half for i in reversed(li): print('*'.join(i)) # for lower half if __name__ == "__main__": try: number = int(input("Enter the number of rows:- ")) #input from user if number <= 0: # for input 0 and negative numbers print("Input should't be negative or zero. Please Enter positive number.") pattern(number) # execution of function except ValueError: # user define exeption handling; for strings input print("Input should not be string. Please Enter positive number.") finally: # to run after every execution print("Program ended..................................")
true
1a9c8c09b72a831f202c42f27f3647c9baeb26f5
Kertich/Algorithm-qns
/smallest_difference.py
786
4.15625
4
array_a = [-1, 5, 10, 20, 28, 3] array_b = [26, 134, 135, 15, 17] get = [] def smalldifference(array_a, array_b): ''' Prints a list of two values each from different array(array_a, array_b). The difference of the two values returns the smallest difference. Parameters: ---------- array_a(iterable), array_b(iterable): Takes in two lists of arrays Returns: ------- Returns a list of with two values each from a different array(array_a and array_b) ''' for i in array_a: for j in array_b: n = i - j m = j - i get.append(m) get.append(n) for k in get: if k == min(get): n =print([i, j]) return n smalldifference(array_a, array_b)
true
9c7baffba283344307ada04b57412dff6c52a2db
wildsrincon/holbertonschool-higher_level_programming
/0x06-python-classes/6-square.py
2,198
4.375
4
#!/usr/bin/python3 """6-square.py: Script to print tuples of square position""" class Square: """Creates Square type""" def __init__(self, size=0, position=(0, 0)): """Initializes the square with position and size""" self.size = size try: self.position = position except TypeError as typ: print(typ) @property def size(self): """Defines the size of square and returns its value""" return self.__size @size.setter def size(self, value): """Defines the value of size of square and checks if >= 0""" self.__size = value if type(value) is not int: raise TypeError('size must be an integer') if value < 0: raise ValueError('size must be >= 0') def area(self): """Defines the area of a square""" return self.__size * self.__size def my_print(self): """Prints square by position""" if self.position: if self.size > 0: print('\n' * self.position[1], end="") for a in range(self.__size): print(' ' * self.position[0], end="") print('#' * self.size) if self.__size == 0: print() @property def position(self): """Defines the position of the square""" return self.__position @position.setter def position(self, value): """Defines function to set the position of square""" if type(value) is not tuple: self.__position = None raise TypeError("position must be a tuple of 2 positive integers") elif len(value) != 2: self.__position = None raise TypeError("position must be a tuple of 2 positive integers") elif type(value[0]) is not int or type(value[1]) is not int: self.__position = None raise TypeError("position must be a tuple of 2 positive integers") elif value[0] < 0 or value[1] < 0: self.__position = None raise TypeError("position must be a tuple of 2 positive integers") else: self.__position = value
true
e737e7b18d4dec68ffea54b048e3c207320733c2
AlexSkrivseth/python_scripts
/python_scripts/ah.py
877
4.125
4
# In the formula below, temperature (T) is expressed in degrees Celsius, # relative humidity (rh) is expressed in %, # and e is the base of natural logarithms 2.71828 [raised to the power of the contents of the square brackets]: # # Absolute Humidity (grams/m3) = 6.112 × e^[(17.67 × T)/(T+243.5)] × rh × 18.02 / (273.15+T) × 100 × 0.08314 def absolute_humidity(t=None, rh=None): if t and rh: # t is farhenheit T = (t - 32) * 5/9 # T is celsius #T = t ah = 6.112 * 2.71828**((17.67 * T)/(T+243.5)) * rh * 2.1674 / (273.15+T) print("The absolute_humidity is {} grams/m3".format(ah)) return ah else: return "Please give two keyword arguments eg. (t=89,rh=67)" absolute_humidity(t=140, rh=.14) absolute_humidity(t=130, rh=.80) absolute_humidity(t=120, rh=.80) absolute_humidity(t=70, rh=.20)
true
18e3425cf8b6efa0d0d52d9ed458dffd98d25679
SaiPrathekGitam/DSPprograms
/simple_interest.py
223
4.15625
4
# Program to calculate simple interest p = int(input('Enter Initial Principal Balance : ')) r = int(input('Enter ANnual Interst Rate : ')) t = int(input('Enter Time(in years) : ')) print('Simple Interest Is', p*r*t)
false
12f98b8a6150acf567acc1e62de69e1ebdb012ad
ADARSHGUPTA111/pythonBasics
/python_basics(git)/dictionaries.py
1,331
4.21875
4
#dictionaries act as a key value pair ninja_belts={"crystal":"red","ryu":"black"} print(ninja_belts) print(ninja_belts['crystal']) #this returns the value associated with this key #how to check whether there exists a key in the given dictionary or not #use key in dict print('yoshi' in ninja_belts)#returns false print(ninja_belts.keys()) print(list(ninja_belts.keys())) #now see we can type cast into the list as per our wish print(ninja_belts.values()) print(list(ninja_belts.values())) #useful in cp as you can then convert the keys into a list and then work on it! vals=list(ninja_belts.values()) print(vals) print(vals.count('black')) #this prints the number of occurences in the vals list ninja_belts['yoshi']="red" print(ninja_belts) # adding a new key into our existing dict is so fucking easy! #alternate way to make a dictionary person=dict(name="adarsh",age=27,height="6ft") print(person) def ninja_intro(dictionary): for key,val in dictionary.items(): print(f' I am {key} is {val} colour belt') ninja_belts={} while True: ninja_name=input("Enter the ninja name") ninja_belt=input("Enter the belt colour") ninja_belts[ninja_name]=ninja_belt another=input("add another?(y/n)") if another=='y': continue else: break ninja_intro(ninja_belts)
true
80970b63c28851bcb5ab76b8b3d418e5f5289489
Chadmv95/cis457-Project-1
/ftp-client.py
2,774
4.125
4
# CIS457 Project 1 # Description: ftp-client will connect to an ftp server. Valid commands are exit, retrieve, store, and list #!/usr/bin/python3 import ftplib # Function to get FTP connection information from user # return IP of server and port number def welcome(): print("Welcome to FTP client app\n") server_name=input("Please enter the server name:\n") port_number=input("please enter the port number:\n") return server_name, port_number # Create client connection to server # Param - IP and port of server # return ftp connection # To Do: Add try/catch for connection def create_client(ip, port): ftp = ftplib.FTP('') #ftp.connect("127.0.0.1", 8080) ftp.connect(ip, int(port)) ftp.login() return ftp # List directories on server # param - ftp connection def list_files(ftp): print("List files in directory: ") print(ftp.retrlines('List')) print("\n\n") # Retrieve a file from the server # param - ftp connection def retrieve(ftp): filename= input("Enter filename of file to retrieve\n") # create file to store retrieved data in try: localfile = open(filename, 'wb') ftp.retrbinary('RETR '+filename, localfile.write, 1024) localfile.close() print("File Retrieved \n\n") except IOError: print("Failure to retrieve file\n\n") except ftplib.all_errors: print("Error: ftp error \n") # Store file in server # param - ftp connection def store(ftp): filename=input("Enter filename to store \n") try: ftp.storbinary('STOR ' + filename, open(filename, 'rb')) except IOError: print("Error: file does not appear to exist \n") except ftplib.all_errors: print("Error: ftp error \n") # End client connection to server # param - ftp connection def quit_connection(ftp): print("quit") ftp.quit() def main(): ftp_connection=None while ftp_connection is None: server_name, port_number = welcome() try: ftp_connection = create_client(server_name, port_number) except ftplib.all_errors: print("Could not connect to server, try again\n") ftp_connection = None command = None while command != "quit": command = input("Enter Command: LIST, RETRIEVE, STORE, QUIT: ") if command.lower() == "list": list_files(ftp_connection) elif command.lower() == "retrieve": retrieve(ftp_connection) elif command.lower() == "store": store(ftp_connection) elif command.lower() == "quit": quit_connection(ftp_connection) command = "quit" else: print("Invalid command, please try again\n\n") if __name__ == "__main__": main()
true
b94da510b1b838748c6f1fac774f8dc8ab74fd0a
iliankostadinov/thinkpython
/Chapter9/Ex9.6.py
573
4.15625
4
#!/usr/bin/env python3 """ Write a function called is_abecedarian that returns True if the letters in a word appear in alphabetical order (double letters are ok). How many abecederian words are there? """ def is_abecedarian(word): tmp_char = 'a' for letters in word: if tmp_char > letters: return False tmp_char = letters return True if __name__ == "__main__": fin = open("words.txt") count = 0 for line in fin: word = line.strip() if is_abecedarian(word): count += 1 print(count)
true
059220dcf416327b83c9fe2eeb06b3fb25b39202
iliankostadinov/thinkpython
/Chapter9/Ex9.4.py
336
4.25
4
#!/usr/bin/env python3 """ Write a function named uses_only that takes a word and a string of letters, and that returns True if the word contains only letters in the list """ def uses_only(word, string): for chars in word: if chars in string: continue else: return False return True
true
08b048f0fddd8a43263c32cce9a76238df233e20
joshuathompson/ctci
/linked_lists/palindrome.py
794
4.1875
4
from linked_list import LinkedList def is_palindrome(linkedList): palindromeStr = "" node = linkedList.head while node is not None: palindromeStr += node.data node = node.nextNode palindromeStr = palindromeStr.replace(" ", "") reversedPalindrome = palindromeStr[::-1] return palindromeStr == reversedPalindrome linkedList = LinkedList() linkedList.appendToTail('r') linkedList.appendToTail('a') linkedList.appendToTail('c') linkedList.appendToTail('e') linkedList.appendToTail('c') linkedList.appendToTail('a') linkedList.appendToTail('r') print(is_palindrome(linkedList)) linkedList = LinkedList() linkedList.appendToTail('r') linkedList.appendToTail('a') linkedList.appendToTail('w') linkedList.appendToTail('r') print(is_palindrome(linkedList))
false
389c7c1344976822a774803fa44dfcca8e0f4414
behrouzmadahian/python
/pandas/13-hierarchical-Indexing.py
2,756
4.34375
4
import pandas as pd ''' Up to this point we've been focused primarily on one-dimensional and two-dimensional data, stored in Pandas Series and DataFrame objects, respectively. Often it is useful to go beyond these and store higher-dimensional data–that is, data indexed by more than one or two keys. ''' print('Representing two-dimensional data with one-dimensional series:\n') index = [('California', 2000), ('California', 2010), ('New York', 2000), ('New York', 2010), ('Texas', 2000), ('Texas', 2010)] populations = [33871648, 37253956, 18976457, 19378102, 20851820, 25145561] pop = pd.Series(populations, index=index) print(pop, '\n') index = pd.MultiIndex.from_tuples(index) ''' Notice that the MultiIndex contains multiple levels of indexing–in this case, the state names and the years, as well as multiple labels for each data point which encode these levels. ''' print('Building MultiIndex:\n', index) pop = pop.reindex(index) print('Our Series with multiIndex:\n') print(pop) print('Accessing data for year=2010:\n') print(pop[:, 2010]) ''' We'll now further discuss this sort of indexing operation on hierarchically indexed data. ''' # 2-MultiIndex as extra dimension: print('\nThe pandas built-in unstack() method will quickly convert a multiply ' 'indexed Series into a conventionally indexed DataFrame:') pop_df = pop.unstack() print(pop_df) print('\nstack() method provides the opposite operation: ') pop_df = pop_df.stack() print(pop_df) ######################################################################################### print('\nMultiple indexing Data Frame- 2 Dimensional data:') populations = [33871648, 37253956, 18976457, 19378102, 20851820, 25145561] index = [('California', 2000), ('California', 2010), ('New York', 2000), ('New York', 2010), ('Texas', 2000), ('Texas', 2010)] index = pd.MultiIndex.from_tuples(index) pop_df = pd.DataFrame({'total': populations, 'under18': [9267089, 9284094, 4687374, 4318033, 5906301, 6879014], }, index=index) print(pop_df) ''' This allows us to easily and quickly manipulate and explore even high-dimensional data. ''' print('\nAll the ufuncs and other functionality discussed in Operating on Data in Pandas work with hierarchical' ' indices as well. Here we compute the fraction of people under 18 by year in each state, given the above data:') f_u18 = pop_df['under18']/pop_df['total'] print(f_u18, '\n') f_u18 = f_u18.unstack() print('Unstacked results:\n', f_u18)
true
8c01d08334ea73dfef9c593241aaf2281585dd79
behrouzmadahian/python
/python-Interview/4-sort/3-insertion-sort.py
1,122
4.125
4
''' for index i: looks into the array A[:i] and shifts all elements in A[:i] that are greater than A[i] one position forward, and insert a[i] into the new position. takes maximum time if elements are sorted in reverse order. ''' def insertion_sort(a): for i in range(1, len(a)): key = a[i] j = i-1 # Move elements of arr[0..i-1], that are # greater than key, to one position ahead # of their current position while j >=0 and key < a[j]: a[j + 1] = a[j] j -= 1 a[j+1] = key return a a = [1,2,5,4,9,7,10,200,12,15,100,0] print(insertion_sort(a)) def insSort(a): for i in range(1, len(a)): curr = a[i] j = i-1 while j >=0 and a[j]> curr: a[j+1] =a[j] j -= 1 a[j+1]= curr return a print(insSort(a)) def insSort2(a): for i in range(1, len(a)): j = i-1 curr = a[i] while j >=0 and a[j] > curr: a[j+1] = a[j] j -= 1 a[j+1] = a[i] return a print(insSort2(a))
true
ba3f073b642f828f39bc28fb3ea7b185fbf01f1c
behrouzmadahian/python
/python-Interview/4-sort/2-bubbleSort.py
689
4.125
4
''' Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order. on the first pass, the last element is sorted, On the second pass the last two elements will be sorted,.. O(n2) ''' def bubble_sort(a): for i in range(len(a)): for j in range(len(a)-i-1): if a[j] > a[j+1]: a[j], a[j+1] = a[j+1], a[j] return a a = [1,2,5,4,9,7,10,200,12,15,100,0] print(bubble_sort(a)) def bubSort(a): for i in range(len(a)): for j in range(len(a)-i-1): if a[j] > a[j+1]: a[j], a[j+1] = a[j+1], a[j] return a print(bubSort(a))
true
d4a2ec8e6957ad4b2550589260d608267a3c90c9
behrouzmadahian/python
/python-Interview/5-linkedList/2-Insertion.py
1,568
4.53125
5
''' A node can be added in three ways 1) At the front of the linked list 2) After a given node. 3) At the end of the linked list. ''' class Node: def __init__(self, data): self.data = data self.next = None # LinkedListClass class LinkedList: # function to initialize the linkedList object def __init__(self): self.head = None def printList(self): temp = self.head while temp: print(temp.data) temp = temp.next def push_inFront(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node def pushAfter_node(self, prevNode, new_data): new_node = Node(new_data) new_node.next = prevNode.next prevNode.next = new_node def push_atEnd(self, new_data): ''' we have to traverse the list till end and then change the next of last node to new node. ''' new_node = Node(new_data) if self.head is None: self.head = new_node tmp = self.head while tmp.next: tmp = tmp.next tmp.next = new_node llist = LinkedList() first = Node(3);second = Node(4);third = Node(5) llist.head = first;llist.head.next = second;second.next = third llist.printList() # Add a node to the front: the new element becomes the head print('=========') llist.push_inFront(10) llist.printList() llist.pushAfter_node(second, 25) llist.printList() llist.push_atEnd(33) llist.printList()
true
64fa4a7d5c0651baf5a24367aeac8663b1e94e34
KkrystalZhang/ToyRobot
/robot.py
2,228
4.125
4
from grid import Grid from utils import DIRECTIONS, MOVES class Robot(object): """ The Robot class contains state of the robot and methods to update the state. """ def __init__(self): self.x = None self.y = None self.direction = None def place(self, x: int, y: int, direction: DIRECTIONS): """ Place the robot at the specified position. Attributes: x (int): x coordination value. y (int): y coordination value. direction (DIRECTIONS): facing direction. """ if Grid.valid_position(x, y) and Grid.valid_direction(direction): self.x, self.y, self.direction = x, y, direction def move(self): """ Move the robot a step forward against the facing direction. """ if self.valid(): delta = MOVES[self.direction] new_x = self.x + delta[0] new_y = self.y + delta[1] if Grid.valid_position(new_x, new_y): self.x = new_x self.y = new_y def left(self): """ Change the facing direction counterclockwise by 90 degree. """ if self.valid(): current_index = DIRECTIONS.index(self.direction) self.direction = DIRECTIONS[current_index - 1] def right(self): """ Change the facing direction clockwise by 90 degree. """ if self.valid(): current_index = DIRECTIONS.index(self.direction) self.direction = DIRECTIONS[(current_index + 1) % 4] def report(self): """ Print the current state of the robot. """ if self.valid(): print(f'Output: {self.x},{self.y},{self.direction}') def valid(self): """ Check if current state of the robot is valid against the grid. Returns: boolean """ return Grid.valid_position(self.x, self.y) and Grid.valid_direction(self.direction) def get_state(self) -> (int, int, DIRECTIONS): """ Get current state of the robot. Returns: x, y, direction """ return self.x, self.y, self.direction
true
f5562b6f521fcebd02606b50dc90b0e42080298d
Niranjana55/unsorted-array-questions
/MtoNprime.py
633
4.125
4
#prime num import math def isprime(N): a=True for i in range(2,int(math.sqrt(N)+1)): if(N%i==0): a=False break return a #print all prime num m to n def PrintPrimesFromMToN(m,n): count=0 if(m==1 or m==2): print(2) count+=1 m=3 if(m%2==0): m+=1 for i in range(m,n+1,2): if(Isprime(i)): print(i) count+=1 if(count==0): print("there are no prime num between {0} and {1}".format(m,n)) m=input("enter the num m:") n=input("enter the num n:") if(m>n): m,n=n,m print("prime num between m and n:")
false
016a78e9e87e2eaa9bebe126a658dcef73ce281a
Sarbodaya/PythonGeeks
/Variables/Variables.py
831
4.28125
4
# Global Variable # Global variables are those who are declared # outside the function we need to use inside the function def f(): s = 'Me Too' print(s) s = "I want to Become Data Scientist" f() print(s) # If a variable with the same name is defined inside the scope of # function as well then it will print the value given inside the # function only and not the global value. # The question is, what will happen if we change the value of s # inside of the function f()? Will it affect the global s as well? We test it in the following piece of code: # filter_none def f(): global s # we have to use the keyword “global”, as can be seen in the following example: print(s) s = "Python is great" print(s) # Global Scope s = "I Love Geeks for Geeks" f() print(s)
true
7bef1dc5c4f2ac421b43578a7e4bac9c2629b58e
Sarbodaya/PythonGeeks
/Variables/PackingUpacking2.py
987
4.875
5
# A Python # program to # demonstrate both packing and # unpacking. # A sample python function that takes three arguments # and prints them def unpacking(a, b, c): print(a, b, c) def packing(*args): args = list(args) args[0] = 'GeeksForGeeks' args[1] = 'awesome' unpacking(*args) packing('Hello', 'Sarbodaya', 'Jena') # ** is used for dictionaries # A sample program to demonstrate unpacking of # dictionary items using ** def fun2(a, b, c): print("Unpacking of Dict : ") print(a, b, c) # dict1 = {'Hello': 1, 'Geeks': 2, 'Guys': 3} d = {'a': 2, 'b': 4, 'c': 10} fun2(**d) # A Python program to demonstrate packing of # dictionary items using ** def fun4(**kwargs): # kwargs is a dict print(type(kwargs)) # Printing dictionary items for key in kwargs: print("%s = %s" % (key, kwargs[key])) fun4(name="Sarbodaya", ID="11804093", language="Python")
false
24ffdc95caf475b3cd21d1dd134adfb64ad97f42
Sarbodaya/PythonGeeks
/Data Types/AccessingTuples.py
1,048
4.78125
5
# Accessing the tuple with indexing Tuple1 = tuple("Geeks") print("First element of Tuple : ") print(Tuple1[1]) # Tuple Unpacking Tuple1 = ("Sarbodaya Jena", "Indian Army", "Indian Navy", "Indian Air Force") # This line unpack the values of tuple a, b, c, d = Tuple1 print("Values after Unpacking : ") print(a) print(b) print(c) print(d) # Concatenation of Two Tuples Tuple1 = (1, 2, 3, 4, 5, 6) Tuple2 = ("Hello", "Geeks", "Welcome") Tuple3 = Tuple1 + Tuple2 print(Tuple3) # Printing First Tuple print("Tuple 1: ") print(Tuple1) # Printing Second Tuple print("Tuple 2: ") print(Tuple2) # Printing Final Tuple print("Final Tuple : ") print(Tuple3) # Slicing of a Tuple Tuple1 = tuple("GEEKSFORGEEKS") # Removing a first Element print("Removal Of first element : ") print(Tuple1[1:]) # Reversing a Table print("Reversing a Table : ") print(Tuple1[::-1]) # Printing elements of Range print("Elements between Range 4-9 : ") print(Tuple1[4:9]) # Deleting a Tupple del Tuple1 # print(Tuple1)
true
d9d06ff6ea7e72fa2a977246d418e3d06f765637
Sarbodaya/PythonGeeks
/ControlFlows/tut5.py
1,046
4.53125
5
king = {'Akbar': 'The Great', 'Chandragupta': 'The Maurya', 'Modi': 'The Changer'} for key, value in king.items(): print(key, value) # Using sorted(): sorted() is used to print the container is sorted order. It doesn’t # sort the container but just prints the container in sorted order for 1 instance. # The use of set() can be combined to remove duplicate occurrences. lis = [1, 3, 5, 6, 2, 1, 3] print("The List in sorted order is : ") for i in sorted(lis): print(i, end=" ") print("\r") print("The List in sorted order (Without Duplicates) is ") for i in sorted(set(lis)): print(i, end=" ") print("\r") # Example 1 basket = ['guava', 'orange', 'apple', 'pear', 'guava', 'banana', 'grape'] for i in sorted(set(basket)): print(i, end=" ") print("\r") # Example 2 lis = [1, 3, 5, 7, 9, 11, 13] print("The List in reversed order : ") for i in reversed(lis): print(i, end=" ") # Example 3 print("Reversed Range : ") for i in reversed(range(1, 10, 3)): print(i, end=" ")
true
6f367f512d9df7f20689ea7716053401e2f09045
Sarbodaya/PythonGeeks
/Basics/StringIsKeywordOrNot.py
798
4.15625
4
# Python code to demonstrate working of iskeyword() import keyword key = ["while", "sarbodaya", "for", "global", "nonlocal", "lambda", "Tanishq", "Rahul", "def", "import"] for i in range(len(key)): if keyword.iskeyword(key[i]): print(key[i], " is a keyword") else: print(key[i], " is not a keyword") # How to print list of all keywords? print("List of all keywords in python : ") print(keyword.kwlist) a = 5 print("Value of a variable : " + str(a)) # One liner if-else instead of Conditional Operator (?:) in Python b = 1 if 20 > 10 else 0 print("The value of b " + str(b)) # Print without newline in Python 3.x print("geeksforgeeks",end=" ") print("Hello Geeks") a = [1, 2, 3, 4, 5] for i in range(len(a)): print(a[i],end=" ")
false
5db93f86f3128a7ff07ecead0bacc8cd82b362a3
Sarbodaya/PythonGeeks
/ControlFlows/tut3.py
431
4.1875
4
fruits = ["apple", "orange", "kiwi"] for fruit in fruits: print(fruit) # Creating an iterator object # from that iterable i.e fruits fruits = ["mango", "banana", "grapes"] iter_obj = iter(fruits) while True: try: # getting the next item fruit = next(iter_obj) print(fruit) except StopIteration: # if StopIteration is raised, # break from loop break
true
c2045c9e986ff05195bc2860905f7ae37819cc90
Sarbodaya/PythonGeeks
/ControlFlows/tut2.py
1,387
4.53125
5
print("List Iteration : ") list1 = ['Sarbodaya', 'Jena', 'Army'] for i in list1: print(i) print("Tuples Iteration : ") tuple1 = ("Geeks", "For", "Geeks") for i in tuple1: print(i) print("String Iteration : ") s = "geeks" for i in s: print(i) print("Dictionary Iteration : ") d = dict() d['xyz'] = 100 d['abc'] = 101 for i in d: print(f"{i} {d[i]}") # Iterating by index of Sequence list1 = ["Geeks", "For", "Geeks"] for index in range(len(list1)): print(list1[index]) else: print("Inside Else Block") # Nested Loops print("Nested Loops : ") for i in range(1, 5): for j in range(i): print(i, end=" ") print() # Loop Control Statements : # Continue Statement: It returns the control to the beginning of the loop. print("Continue Statement : ") for letter in "geeksforgeeks": if letter == 'e' or letter == 's': continue print("Current Letter : ", letter) # Break Statement : It brings control out of the loop print("Break Statement : ") for letter in "geeksforgeeks": if letter == 'e' or letter == 's': break print("Current Letter : ", letter) # Pass Statement : We use pass statement to write empty loops. # Pass is also used for empty control statement, function and classes. for letter in 'IndianAirForce': pass print("Last Letter : ", letter)
false
21795b39ac96ea65e171431811c5c75f2594e797
Sarbodaya/PythonGeeks
/ControlFlows/tut4.py
1,594
4.9375
5
# Different Looping Techniques # Using enumerate(): enumerate() is used to loop through the containers printing # the index number along with the value present in that particular index. for key, value in enumerate(['The', 'Big', 'Bang', 'Theory']): print(key, value) for key, value in enumerate(['Geeks', 'for', 'Geeks', 'is', 'the', 'Best', 'coding', 'platform']): print(value, end=" ") # Using zip(): zip() is used to combine 2 similar containers(list-list or dict-dict) # printing the values sequentially. The loop exists only till the smaller container # ends. A detailed explanation of zip() and enumerate() can be found here. print() question = ['name', 'colour', 'shape'] answers = ['apple', 'red', 'circle'] for question, answers in zip(question, answers): print(f"What is your {question} ? I am {answers}.") # Using iteritem(): iteritems() is used to loop through the dictionary printing the # dictionary key-value pair sequentially. # Using items(): items() performs the similar task on dictionary as iteritems() but # have certain disadvantages when compared with iteritems(). # Disadvantages # It is very time-consuming. Calling it on large dictionaries consumes quite # a lot of time. # It takes a lot of memory. Sometimes takes double the memory when called # on a dictionary. d = {"geeks": "for", "only": "geeks"} # print("The key value pair item using iteritems : ") # for i, j in d.iteritem(): # print(i, j) print("The key value pair item using items : ") for i, j in d.items(): print(i, j)
true
6955a27ab909bd7a55235829d2eb3390cbdb75f8
rekikhaile/Python-Programs
/4 file processing and list/list_examples.py
828
4.28125
4
# Initialize my_list = [] print(my_list) my_list = list() print(my_list) ## Add element to the end my_list.append(5) print(my_list) my_list.append(3) print(my_list) # notice, list can contain various types my_list.append('Im a string') print(my_list) ## more operations on lists my_list.remove('Im a string') print(my_list) print(my_list.index(5)) last = my_list.pop() print(last) my_list.insert(1, 10) print(my_list) print([1, 1, 2, 1, 3].count(1)) ## built-in functions # inplace my_list.reverse() my_list.sort() # with a return value my_list_copy = sorted(my_list) my_list_reversed = reversed(my_list) n = sum(my_list) print('sum is', n) my_max = max(my_list) my_min = min(my_list) print ('max is %s, min is %s.' % (my_max, my_min)) ## list addition print([2, 3, 4] + [5, 9, 8]) ## check the documentation for more
true
d31fd6fcfd7419e8f184d0fefa6e77b280d96858
Nahid-Hassan/fullstack-software-development
/code-lab/DSA - Fibonacci Numbers.py
910
4.21875
4
import random import math def fibonacci_recursive(n): if n <= 1: return n return fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2) def fibonacci_iterative(n): fib = [0, 1] for i in range(2, n+1): fib.append(fib[i-1]+fib[i-2]) return fib[n] def fibonacci_formula(n): root_5 = math.sqrt(5.0) return (1 / root_5) * ((((1 + root_5) / 2) ** n) - (((1 - root_5) / 2) ** n)) def main(): # stress test for _ in range(10): n = random.randint(1, 20) recursive = fibonacci_recursive(n) iterative = fibonacci_iterative(n) method = fibonacci_formula(n - 1) print(n, '---->', math.floor(method)) if recursive != iterative: print( f'Wrong Answer: recursive = {recursive}, iterative = {iterative}.') else: print('Ok') if __name__ == "__main__": main()
false
447513034ca76fc1c522377b2c89ad7fb15e4198
pyfor19/babel-emmanuel
/input/first.py
529
4.1875
4
# Premier traitement fullname = input("Quel est votre prénom et nom ?") print(fullname) names = fullname.split() print(names) print(type(names)) len_listnames = len(names) print(len_listnames) if len_listnames == 2: print("Prénom " + names[0] + " Nom: " + names[1]) elif len_listnames == 3: print(f"Prénom {names[0]}, Milieu {names[1]} Nom {names[2]}") elif len_listnames == 1: print("Nom seul: " + names[0]) else: print("Format : Prénom <Milieu> Nom") print("Que faire de : " + " ".join(names[3:]))
false
c52f66676fcf6ab8ed68d82dfb96cf773ab265f2
KarlYapBuller/03-Higher-Lower-game-Ncea-Level-1-Programming-2021
/02_HL_Get_and_Check_User_Choice_v1.py
1,092
4.1875
4
#Get and Check User input #Number Checking Function goes here def integer_check(question, low=None, high=None): situation = "" if low is not None and high is not None: situation = "both" elif low is not None and high is None: situation = "low only" while True: try: response = int(input(question)) if situation == "both": if response < low or response > high: print("Please enter a number between {} and {}".format(low, high)) continue elif situation == "low only": if response < low: print("Please enter a number that is more than (or equal to) {}".format(low)) continue return response except ValueError: print("Please enter an integer") continue #Main Routine lowest = integer_check("Low Number: ") highest = integer_check("High Number: ", lowest + 1) rounds = integer_check("Rounds: ", 1) guess = integer_check("Guess: ", lowest, highest)
true
a4af8a265f728ad04325783b9a2279421beb44ed
zhanglae/pycookbook
/ch1/cookbook1_13.py
1,192
4.3125
4
'1.13 Sorting a List of Dict by common key' ''' Problem You have a list of dictionaries and you would like to sort the entries according to one or more of the dictionary values. ''' 'Think about its a small db, sort by one column' rows = [ {'fname': 'Brian', 'lname': 'Jones', 'uid': 1003}, {'fname': 'David', 'lname': 'Beazley', 'uid': 1002}, {'fname': 'John', 'lname': 'Cleese', 'uid': 1001}, {'fname': 'Big', 'lname': 'Jones', 'uid': 1004}, {'fname': 'Dig', 'lname': 'Jones', 'uid': 1004} ] from operator import itemgetter rows_by_fname = sorted(rows, key= itemgetter('fname')) print(rows_by_fname) rows_by_uid = sorted(rows, key= itemgetter('uid')) print(rows_by_fname) print("\nsort by multiple keys") rows_by_uid_fname= sorted(rows, key=itemgetter('uid','fname')) print(rows_by_uid_fname) # The itemgetter() can also accept multiple keys 'also i will use lambda function ' print("\nsort by keys, lambda") new = sorted(rows, key = lambda x: x['fname']) print(new) 'also i will use lambda function more keys' print("\nsort by multiplekeys, lambda") new = sorted(rows, key = lambda x: (x['fname'], x['uid']) ) print(new)
true
88ea161e3affcbd9132cf26218c035f67a03e953
Lokarin/Fragmentos
/tabuada.py
495
4.1875
4
# -*- coding: utf-8 -*- numero = float(input("Número do multiplicando: ")) x1 = numero * 1 x2 = numero * 2 x3 = numero * 3 x4 = numero * 4 x5 = numero * 5 x6 = numero * 6 x7 = numero * 7 x8 = numero * 8 x9 = numero * 9 x10 = numero * 10 print("--- Tabuada do %i --- \n"%numero ) print("×1 = %f"%x1) print("×2 = %f"%x2) print("×3 = %f"%x3) print("×4 = %f"%x4) print("×5 = %f"%x5) print("×6 = %f"%x6) print("×7 = %f"%x7) print("×8 = %f"%x8) print("×9 = %f"%x9) print("×10 = %f"%x10)
false