text
stringlengths
37
1.41M
# -*- coding: utf-8 -* ''' 选择排序 ''' import sort_helper @sort_helper.test_sort def select_sort(arr): n = len(arr) for i in range(0,n,1): # 寻找[i, n)区间里的最小值的索引 minIndex = i for j in range(i+1,n,1): if arr[j] < arr[minIndex]: minIndex = j # swap 操作 交...
# -*- coding: utf-8 -* ''' 三路快速排序 ''' import random import sort_helper def __sort(arr,l,r): if l > r: return k = random.randint(l, r) arr[l], arr[k] = arr[k], arr[l] v = arr[l] lt = l #arr[l+1....lt] < v gt = r + 1 #arr[r...gt-1] > v i = l + 1 ...
# Jonpierre Grajales # Project 1 Part 2 class node: def __init__(self, val): self.val = val self.left = None self.right = None self.parent = None def isLeaf(self): return not self.left and not self.right class recAVL: def __init__(self, rootval): ...
def find_rotation(arr): search_range = (0, len(arr) - 1) low = search_range[0] high = search_range[1] while (high - low) > 0: low = search_range[0] high = search_range[1] mid = (low + high) // 2 if arr[mid + 1] < arr[mid]: return mid + 1 if arr[mid] < current_low: previous_low = current_low ...
def in_array(a1, a2): resp=[] for word1 in a1: for word2 in a2: if word2.find(word1) != -1: resp.append(word1) break k=0 while k==0: for i in range(len(resp)-1): if resp[i] > resp[i+1]: j = resp[i] re...
def div32by(divideBy): try: return 32/ divideBy except ZeroDivisionError: print('ERROR! You cannot divide by zero!') print(div32by(5)) print(div32by(4)) print(div32by(6)) print(div32by(0)) print(div32by(14)) def howManyCars(numOfCars): print('How many cars do you have? :') numOfCars ...
# reading a file fileLocalization = (r'C:\Users\Okles\Documents\PycharmProjects\firstPythonProject\fileLoading.txt') testFile = open(fileLocalization) content = testFile.read() print(content) testFile.close() # writing to a file testFile = open(fileLocalization,'w') #opening a file in a write mode testFile.write('Writ...
import re namesRegex = re.compile(r'Agent \w+') print(namesRegex.findall('Agent Alice gave secret documents to Agent Bob')) print(namesRegex.sub('REDACTED', 'Agent Alice gave secret documents to Agent Bob')) #substitute Agent with the rest with REDACTED namesRegex2 = re.compile(r'Agent (\w)\w*') #one letter plus space...
def hello(name): print('Hi ' + name + '!') hello('Lukasz') hello('Roman') hello('Eric') def plusOne(number): return number +1 print('') newNumber = plusOne(5) print(newNumber) print('cat', 'dog', 'mouse', sep ='SEPARATOR')
'''str = """Python是一种面向对象、解释型、动态 类型计算机程序设计语言. 解释型:程序无需编译成二进制代码,而是在执行时对语句一条一条编译 动态类型:在程序执行过程中,可以改变变量的类型 它常被昵称为 胶水语言,能够把用其他语言制作的各种模块(尤其是C/C++)很轻松地联结在一起""" = isinstance("疯狂",str) print(a) x,y = 5,6 a = x if x > y else y print(a) value = "kwsj" for i in value: print(i,len(i))...
# #魔法方法-定义序列 # # 协议与其他编程语言中接口很相似,它规定你哪些方法必须要定义.然而,在 # # python中的协议就显得那么不正式.事实上,在python协议更像是一种指南/建议 # # 容器类型的协议: # # 1 当希望定义的容器是不可变的化,只需要定义__len__()和__getitem__()方法 # # 2 当希望定制的容器是可变的话,除了__len__()和__getitem__()方法,还需定义__setitem__()和__delitem__()两个方法 # # #需求,编写一个不可改变的自定义列表,要求记录列表中每个元素被访问的次数 # class MyList: # def _...
class Car: def __init__(self, car_id=None, car_make=None, car_model=None, car_year=None, car_color=None, car_price=None): self.car_id=car_id self.car_make=car_make self.car_model=car_model self.car_year=car_year self.car_color=car_color self.car_price=car_price ...
a = int(input("primeiro valor:")) b = int(input("segundo valor:")) c = int(input("terceiro valor:")) if a<b and a<c: menor=a if b<c and b<a: menor=b if c<a and c<b: menor=c if a>b and a>c: maior=a if b>c and b>a: maior=b if c>a and c>b: maior=c print("o menor valor foi:",menor) print("o maior v...
# Module 2 # Programming Assignment 2 # Prob-3.py # Daniel (Ash) Lingle import math def example(): print("\nExample Output") # print a blank line print() # create three variables and assign three values in a single statement v1, v2, v3 = 21, 12.34, "hello" # print the variables pr...
foo1 ="python" foo2 = "program" if foo1 == "python": if foo2 == "program1": print "Python is a Program" else: print "Maybea Snake then" else: print "I hve no idea what it is them"
# testExpr.py -- Unit tests for Expr from expr import * import unittest class TestExpr(unittest.TestCase): def test_str(self): e1 = Equation( Plus( Number(2), Times(Number(3), Number(4))), Times( Plus( ...
from tkinter import * def frame(root, side): w = Frame(root) w.pack(side=side, expand=YES, fill=BOTH) return w def button(root, side, text, command=None): w = Button(root, text=text, command=command) w.pack(side=side, expand=YES, fill=BOTH) return w class Calculator(Frame): def __init__(...
cathetet_1=int(input("Enter value of first cathet")) cathetet_2=int(input('Enter value of second cathet')) def triagle_square_perimeter(cathetet_1,cathetet_2): import math hypotenuse=(math.sqrt(cathetet_1 * cathetet_1 + cathetet_2 * cathetet_2)) triagle_square=(cathetet_1*cathetet_2)/2 triale_perimeter=...
writer="Daniel Keyes*1927-08-15*2014-06-15" #print(writer) space=writer.find(' ') #print(space) star=writer.find('*') #print(star) second_star=writer.rfind('*',star+1) #print(second_star) second_dash=writer.rfind('-',second_star) #print(second_dash) dash=writer.find('-') #print(dash) name=writer[0:star] #print(name) da...
def check_arams(string): temp="" dct = {} words=string.split(" ") words=sorted(words,key=len) for element in words: if len(element) not in dct: dct[len(element)] = [element] elif len(element) in dct: dct[len(element)] += [element] res = [] for ...
#!/usr/bin/python print 'content-type: text/html\n' import cgitb,cgi,hashlib cgitb.enable() form = cgi.FieldStorage() head = ''' <html> <head> </head> <body> ''' body = "" foot = ''' </body> </html> ''' if len(form)==0: body = ''' <h1>Create account:</h1> <form action="createaccount.py" method="POST...
# Bradford Smith and David Ott # CS 347 Assignment 3 # AbsenceCheck test_people.py # "I pledge my honor that I have abided by the Stevens Honor System." ##################################################################### from person import person from student import student from admin import admin #class to test the...
"""Print out all the melons in our inventory.""" from melons import melons_dict def print_melon(dictionary): """Print each melon with corresponding attribute information.""" for melon in melons_dict: print(melon[0]) print(f"seedless: {melon[2]}") print(f"price: {melon[1]}") ...
import random #随机生成电话号码函数 def create_number(i): arr = [] for i in range(21): area_num = ['187','186','158','155','156','155','152','151','134','135','136','137','138','139','131','130','133','153'] area_number = random.choice(area_num) #随机生成号码的三位数开头 seed = '1234567890' sa = ...
from sys import argv script, input_file =argv def print_all(f): print (f.read()) def rewind(f): f.seek(0) def print_a_line(line_count,f): print (line_count, f.readline())#bug(f.readline())点错写成了逗号 current_file = open(input_file) print ("First let's print the whole file :\n") print_all...
def add(a,b): print ("ADDING %d+%d" %(a,b)) return a+b def subtract(a,b): print ("SUBTRACTING %d -%d" % (a,b)) return a-b def multiply(a,b): print ("MULTIPLYING %d * %d " %(a,b)) return a*b def divide(a,b): print ("DIVIDING %d / %d" % (a,b)) return a/b print ("Let's d...
import math def solve(): a = int(input("Enter the coefficients of a: ")) b = int(input("Enter the coefficients of b: ")) c = int(input("Enter the coefficients of c: ")) # discriminant d = b ** 2 - 4 * a * c #This discriminant will never be lessthan zero as it is given in question that there ...
''' Simple code to connect to SQLite db, reads and print out rows. The file name is RDS.sqlite and located in what is your current working directory for that instance of python. ''' import sqlite3 conn = sqlite3.connect('RDS.sqlite') cursor = conn.cursor() f = cursor.execute("Select * FROM RDS") for i in f: print ...
############### # # take in an image, change color, and display # plot over image with matplotlib # save modified image # # by bex # ############### import cv2 import numpy as np import matplotlib.pyplot as plt # # define image and read the image with imread # img = cv2.imread('rm.jpg', cv2.IMREAD_GRAYSCALE) #graysca...
# This section initializes the prices of certain groceries such as water, chips, and milk. # Additionally, the total price is initialized to 0, but its value will change shortly. water_price = 2 chips_price = 2 milk_price = 5 price_total = 0 # This section asks the user for input while telling them the price of...
def openFile(): #opened_file = open("C:\\Users\\piano\\Downloads\\HP5.txt","r") opened_file = open("/Users/dale_nelson/Documents/Python/Lab07/HP5.txt","r",\ encoding="cp1252") return opened_file def wc(): read_file = openFile().read() total_words = read_file.split() return len(total_wor...
#!/usr/bin/python import sys def rock_paper_scissors(n): rps = ['rock', 'paper', 'scissors'] outcomes = [] def rounds(count, round = [] ): if count == 0: outcomes.append(round) return for i in rps: rounds(count-1, round + [i]) rounds(n, []) re...
import pandas as pd from datetime import datetime # Getting data from CSV. Skipping 3 lines of footer, # and setting engine to python so that the program dont use de default engine "C" dataframe = pd.read_csv("datasets/international_airline_passengers.csv", engine="python", skipfooter=3) def managing_columns(datafra...
from datetime import datetime from datetime import timedelta from datetime import date count = 0 def find_century(year): if (year % 100) >= 50: century_start = int(round(year, -2)) - 100 century_end = int(round(year, -2)) else: century_start = int(round(year, -2)) century_end =...
from random import choice from string import ascii_lowercase words_list = ('python', 'java', 'kotlin', 'javascript') init_word = list(choice(words_list)) init_set = set(init_word) past_turn_set = set() answer_word = ['-' for _ in init_word] def play_hang(): turn = 8 while turn != 0: print() p...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # ============================================================================= # @file dp.py # @author Albert Puig (albert.puig@cern.ch) # @date 14.04.2019 # ============================================================================= """Dynamic programming.""" impo...
""" from PYTHON Strings: Exercise 4 ( https://www.w3schools.com/python/exercise.asp?filename=exercise_strings4 ) question: Return the string without any whitespace at the beginning or the end. txt = " Hello World " x = ___________ """ txt = " Hello World " x = txt.strip()
""" from PYTHON Functions: Exercise 5 ( https://www.w3schools.com/python/exercise.asp?filename=exercise_functions5 ) question: If you do not know the number of arguments that will be passed into your function, there is a prefix you can add in the function definition, which prefix? def my_function(_kids): ...
""" from PYTHON If...Else: Exercise 6 ( https://www.w3schools.com/python/exercise.asp?filename=exercise_ifelse6 ) question: Print "Hello" if a is equal to b, or if c is equal to d. if a == b __ c == d: print("Hello") """ if a == b or c == d: print("Hello")
""" from PYTHON While Loops: Exercise 1 ( https://www.w3schools.com/python/exercise.asp?filename=exercise_while_loops1 ) question: Print i as long as i is less than 6. i = 1 _____ i < 6_ print(i) i += 1 """ i = 1 while i < 6: print(i) i += 1
""" from PYTHON Operators: Exercise 5 ( https://www.w3schools.com/python/exercise.asp?filename=exercise_operators5 ) question: Use the correct logical operator to check if at least one of two statements is True. if 5 == 10 __ 4 == 4: print("At least one of the statements is true") """ if 5 == 10 or 4 ...
""" from PYTHON Lists: Exercise 4 ( https://www.w3schools.com/python/exercise.asp?filename=exercise_lists4 ) question: Use the insert method to add "lemon" as the second item in the fruits list. fruits = ["apple", "banana", "cherry"] ________________"lemon") """ fruits = ["apple", "banana", "cherry"] frui...
import random def scalaViteACaso(dizionario): # funzione che prende un dizionario come input dove ad ogni nome è associato un intero # stampa a schermo i nomi inseriti in modo casuale per un numero di volte pari al numero di vite # quando tutti i participanti hanno finito le vite ricomincia da capo ...
'''List 2. Write a Python program to multiplies all the items in a list.''' list1 = [3,5,6,7,9,12] mul = 1 for number in range(len(list1)): mul = mul * list1[number] print(mul)
'''LIST 3. Write a Python program to get the largest number from a list.''' #def maximum(items): # print(max(items)) #maximum([10,20,30,40]) large = 0 list1 = [2,3,4,5,6,7] for i in list1: if i > large: large = i print(large)
def sum(n): i = 0 sum = 0 for i in range(n + 1): sum = sum + i print(sum) sum(int(input()))
'''List: 1. Write a Python program to sum all the items in a list.''' list1 = [16, 18, 20, 41, 59] sum = 0 for number in range (len(list1)): sum = sum + list1[number] print(sum)
items = ['vis','shi', 30, 50.8, 90,100.5,'bob'] total = 0 def sum(list): total = 0 for i in list: if isinstance(i, int) or isinstance(i,float): total += i return total def count(list): total = 0 for i in list: if isinstance(i,int) or isinstance(i,float): total += 1 return total def avg(list): sum_items...
print('Enter your mark') mark=input() if '100' <= mark >= '90': print('grade is A') elif '89' >= mark >='80': print('grade is B') else: print('You have failed')
import os import store i = 0 print('How many IP addresses do you want to enter?') ip = int(input()) while i < ip: try: IpFile1 = open('C:\\aaa\\IPAddress.txt', 'r') IpFile = open('C:\\aaa\\IPAddress.txt', 'a') list1 = IpFile1.readlines() print('Enter the name of the device') ...
import random randNumber = random.randint(1,21) for chance in range(1,7): number = int(input('Enter the number:')) if number < randNumber: print('The entered number is less than the actual number.') elif number > randNumber: print('The entered number is greater than actual number') elif...
def iso(str1,str2): if len(str1) != len(str2): return 'The given strings are not isomorphic' dict1 = {} for i,j in zip(str1,str2): if dict1.get(i,0) == 0: dict1[i] = j else: dict1[i] != j return 'The given strings are not isomorphic' return 'The string is isomorphic' print(iso('abcaa','xyzd'))
def example(): myList = ['dog', 'cat', 'fish', 'lion', 'tiger'] for i in range(len(myList)): print('Index ' + str(i) + ' has value ' + myList[i]) def example2(): myList2 = list(range(0,10)) for i in range(len(myList2)): print(myList2[i]) example() example2()
#!/bin/python3 #testing import sys def bonAppetit(n, k, b, ar): # Complete this function shouldCharge = 0 for i in range(n): if i != k: shouldCharge += ar[i] shouldCharge /= 2 if shouldCharge - b == 0: return 'Bon Appetit' else: ...
from typing import NamedTuple from typing import Callable from typing import List class Password(NamedTuple): lo: int hi: int chr: str pw: str def parse_rule(txt: str) -> Password: elemets = txt.split() lo, hi = elemets[0].split("-") chr_ = elemets[1][0] pw = elemets[2] return ...
# # # digits6.py # Name: Marie Boys & Monica Montano # import numpy as np from sklearn import datasets import pandas as pd try: # different imports for different versions of scikit-learn from sklearn.model_selection import cross_val_score # simpler cv this week except ImportError: try: from sklear...
# # hw5pr2.py ~ rps string analysis # # Name(s): Andrew Marks # import csv def open_csv( filename="rps.csv" ): """ opens the file with name filename by default: it looks for "rps.csv" reads all of the csv data and assembles it into a list-of-lists and then returns that... (Here, it u...
# # # digits6.py # # Andrew Marks import numpy as np from sklearn import datasets import pandas as pd try: # different imports for different versions of scikit-learn from sklearn.model_selection import cross_val_score # simpler cv this week except ImportError: try: from sklearn.cross_validation imp...
def dist(p1, p2): # p1 and p2 should be tuples of x, y coordinates # Returns Manhattan distance return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1]) def d6_1(data): data = data.split("\n") max_x = 0 max_y = 0 areas = {} points = [] for row in data: (x, y) = [int(e) for e in row.sp...
# Given an array and a value, remove all instances of that value in place and return the new length. # Do not allocate extra space for another array, you must do this in place with constant memory. # The order of elements can be changed. It doesn't matter what you leave beyond the new length. # Example: # Given inpu...
import numpy as np def area(radius): """Calculate the area of a circle. Parameters ---------- radius : float return np.pi *( radius ** 2)
Tabla=input("Dame el Number del 0 al 10: ") # aqui vamos a imprimir el texto , vamos a ponerle el numero que queramos Tabla=int(Tabla) #en el operador int le estamos diciendo que lo vamos a convertir en un numero entero for a in range(0 , 12): #aqui estamos dandole un ciclo que por ejemplo nosotros ponemos el...
# lista = [1, 2, 3, 4, 5, 6, 7, 8, 9] # try: # pos = int(input('A que posicion quieres acceder? ')) # except ValueError: # print('Ingresa un numero entero por favor') # else: # try: # print(lista[pos]) # except IndexError: # print('la posicion', pos, 'no esta en lista') lista = [1, 2, 3, 4, 5, 6, 7, ...
lista1 = [0, 1, 2, 3] lista2 = ["A", "B", "C"] lista3 = lista1 + lista2 #Crea nueva lista con el contenido de las listas que la componen print(lista3)
inicio = int(input("Inicio: ")) fin = int(input("Fin: ")) + 1 incremento = int(input("Incremento: ")) for i in range(inicio, fin, incremento): print(i)
suma = 0 dato = 1 while(dato != 0): dato = int(input("Ingrese un numero entero un numero a sumar o 0 para salir ")) suma += dato print("La suma es: " + str(suma))
lista = [4, 5, -1, 6, 7] lista.sort() # De menor a mayor print(lista) lista.sort(reverse = True) # De mayor a menor print(lista)
cadena = input("Ingresa una palabra o una frase: ").lower() buscado = input("Ingresa el caracter que quieres contar: ") print(cadena.count(buscado))
def full_name_fix(s): # full name input situation full = [] fname = s.split(' ')[0] lname = s.split(' ')[1] first_letter = fname[0].upper() full.append(first_letter + fname[1:]) first_letter = lname[0].upper() full.append(first_letter + lname[1:]) return full def name_fix(s): #...
''' OCR 20 Coding Challenges 01 Mastermind ============= Extension Version: © Mark Sansome June 2018 Generate a random four digit number. The player has to keep inputting four digit numbers until they guess the randomly generated number. After each unsuccessful try it should say how many numbers they got c...
''' OCR 20 Coding Challenges 02 Averages =========== Basic Version © Mark Sansome June 2018 Make a program that asks the user for a series of numbers until they either want to output the average or quit the program. Extensions: 1. Expand the program to print the median and mode averages also 2. Include ...
import numpy as np # 创建ndarray 的两种方式 # 第一种方式使用python列表创建一维数组 x = np.array([1, 2, 3]) print("一维数组: ", x) # 如果是一维,整个数组相加 print(sum(x)) x = np.array([[1, 2, 3], [4, 5, 6]]) print("二维数组: \n", x) # 如果是二维, 列相加,返回一维ndarray print(sum(x)) # 如果参数中是可选的话,你得加key设置value # x = np.random.randint(low=10, high=12, size=(3, 4)) x = np...
name = input("enter your name:") print("hello there {}".format(name.title())) try: num = int(input("entry num :")) print(num) except: print("not availd num") while True: try: xingming = float(input("entry float ....")) print(xingming) break except ValueError as e: p...
import numpy as np import time # 创建ndarray的两种方式 # 创建一个随机得列表 x = np.random.random(100000000) # start = time.time() # result = sum(x) / len(x) # print("原始python计算平均值 spend time : {}".format(time.time() - start)) start = time.time() np.mean(x) print(time.time() - start) x = np.arange(2,34,2).reshape(4,4) print(x) pr...
import os import random as rn class Question: def __init__(self,word, answer, source): self.word = word self.answer = answer self.source = source def check(self, answer): boolean = answer.upper().replace(' ', '') == self.answer.upper().split(';')[0].replace(' ', '') if ...
""" Parse the PRINT input file section """ from parameter import Parameter class Print(Parameter): """ This is a very simple section that allows linear combinations of calculated properties to be written to standard output. The syntax of this section is PRINT {what} [id op id op...] END ...
import random def input_num(prompt='Please enter a number: ', mini=0, maxi=100): """Read a positive number with the given prompt.""" while True: try: num = int(input(prompt)) if (num < mini or (maxi is not None and num > maxi)): p...
#Classes for Bicone Algorithm import numpy as np import random class Individual: def __init__(self, chromosome = None, fitness = 0.0): self.fitness = fitness #Fitness Score of the Individual if chromosome is None: #Genetic material for the Individual ...
# squareRoot.py # to estimate square root of number # Author: Andy Walker # first define function sqrt # the number value is defined later in the code # the more iterations it is possible to be more accurate, although too many is less efficient # Newton's Method: sqrt n = 0.5 * (n + a / n) where: # n is a postive numb...
# A Python program for the Rock, Paper, Scissors game. from random import randint def rock_paper_scissors(): t = ["rock", "paper", "scissors"] win = 0 lose = 0 points = int(input("\nHow many points does it take to win? ")) print() i =1 while (win < points and lose < points): ...
student1 = {'name': 'Morty', 'stream': 'universal quest', 'grade': 12, } student2 = {'name': 'Summer', 'stream': 'terrestrial quest', 'grade': 20, } # list of dictionaries students_list = [student1, student2] print (students_list[1]) # Diction...
# Variables in python # a variable is a box and we put stuff inside and give it a name # Assign a variable; give box name, put stuff inside box_pillows = 'pillows and stuff' # Look inside a box print(box_pillows) # variable reassignment, changing box contents box_pillows = "string" print(box_pillows) # important fu...
#!/usr/bin/python """ --- Day 7: Some Assembly Required --- This year, Santa brought little Bobby Tables a set of wires and bitwise logic gates! Unfortunately, little Bobby is a little under the recommended age range, and he needs help assembling the circuit. Each wire has an identifier (some lowercase letter...
#!/usr/bin/python import itertools """ --- Day 9: All in a Single Night --- Every year, Santa manages to deliver all of his presents in a single night. This year, however, he has some new locations to visit; his elves have provided him the distances between every pair of locations. He can start and end at ...
num = 5 def factorial(n): if n == 0: return 1 f = 1 i = 0 while i < n: i += 1 f = f * i return f print("факториал числа {n} равен {f}".format(n=num, f=factorial(num)))
""" Python is a strongly-typed language under the hood, which means that the types of values matter, especially when we're trying to perform operations on them. Note that if you try running the following code without making any changes, you'll get a TypeError saying you can't perform an operation on a string and an ...
tuple=(1,2,3) count=1 ans=[] while(count<4): for i in tuple: l=(i,count) ans.append(l) count+=1 print(ans)
# Problem Set 6, Bleep, Python, 14 July 2019 from cs50 import get_string from sys import argv import sys import os.path def main(): # TODO # Check the command-line argument if len(argv) != 2: print("Usage: python bleep.py textfile") sys.exit(1) banfile = argv[1] ...
while True: try: str = input() list = str.split() print(len(list)) for i in list: print(i) except: break
#!/usr/bin/python2 import socket recv_ip="127.0.0.1" recv_port=4444 # 0 - 1024 #creating udp socket # ip type v4 , uDp s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) # fitting ip and port with udp socket s.bind((recv_ip,recv_port)) choice = raw_input("Enter your Choice : 1.TWO way 2)ONE way") # rec...
#!/bin/python3 import os import crypt uname=input("Enter your Username : ") check=0 n=[0,1,2,3,4,5,6,7,8,9] for i in uname: if i in str(n): check=1 if(check==1): print("Invalid User Name (Please don't use numbers") else: psswd="hello"+uname encPsswd = crypt.crypt(psswd,"22") os.system("useradd -p " + encPsswd...
f = open('Test.txt','a+') for line in f.readlines(): if 'a' in line: f.write(line.replace('a','e')) elif 'e' in line: f.write(line.replace('e','i')) elif 'i' in line: f.write(line.replace('i','o')) elif 'o' in line: f.write(line.replace('o','u')) elif 'u' in line: f.write(line.replace('u','a')) else: ...
#Display sum of repeating numbers #Mrunali prn-23 import re data = open("givenFile","r").read() #opening file and reading it data = re.findall('[^\n\t\s\r\f\v]',data) #removing new line char,tabchar,specialchar,etc sum1=0 for i in range(len(data)-1): if data[i] == data[i+1]: # checking for same numbers s = data[i...
from tkinter import * mile = 1.609344 def calc_times(metric,pace,minutes,seconds,distances,fields): minutes = float(minutes) seconds = float(seconds) if metric==1: secs = minutes*60 + seconds else: secs = (minutes*60 + seconds)/mile n=0 #pace m = secs//60 s = secs -m*60 pace[0].set(round(m)) pace[1].se...
#Importacion de Random import random dic_pelis={} class Movie: """Esta es la clases que se encargara de darle los rangos , los likes y los dislikes desde varios metodos - Crear una clase llamada Movie (documentar la clase) - La clase tiene los siguientes atributos: - Title - Titu...
# # PURPOSE: Running this program should train the network on the faces in our data set, # trying to classify faces into 5 gender classes (each 20 years wide). The program will # create files containing the final weights and graphs of the training process. # # USAGE: First run saveAgeData.py to generate two data file...
#! /usr/bin/env python """ Project: Python Chess File name: ChessBoard.py Description: Board layout; contains what pieces are present at each square. Copyright (C) 2009 Steve Osborne, srosborne (at) gmail.com http://yakinikuman.wordpress.com/ """ import string class ChessBoard(object): ...
import min_multiplication def test_compute_min_multiplication_of_list_elements_1(): test_list = [-3, 2, 5, 7, 11, -6, -23, 0, -9] result = min_multiplication.compute_min_multiplication_of_list_elements(test_list) print('OK') if (result == -23 * 11) else print('Error test 1') def test_compute_min_multipl...
def index(): # para repitir as funcoes quantas for necessario while True: print("\n++++++ MEMU OUTPUT ++++++++ ") # Entrar com opcao desejada opcao = input("| 1 | Listar Conteudo da Calculadora \n| 2 | Listar Conteudo da Maquina de Vendas \n| 0 | Menu principal") # ifs para vere...
# Python内置了字典:dict的支持,dict全称dictionary, # 在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。 d = {'Michael': 95, 'Bob': 75, 'Tracy': 85} print(d['Michael']) #把数据放入dict的方法,除了初始化时指定外,还可以通过key放入 d['Michael']=66 print(d) # 由于一个key只能对应一个value,所以,多次对一个key放入value,后面的值会把前面的值冲掉 d['Jack'] = 90 d['Jack'] = 88 print(d) # 通过dict提供的get()方法,...