text
stringlengths
37
1.41M
"""Generates URLs for factorio icons.""" import os.path _NAME_TO_ICON = {} def init(icon_directory_path): """Initializes the factorio icon manager. Args: icon_directory_path: The path of the factorio-data icon directory. Must be relative to the directory containing app.yaml. """ ...
""" Modifiers a function modifies the objects it gets as parameters the changes are visible to the caller """ def increment(time, seconds): time.second += seconds if time.second >= 60: time.second -= 60 time.minute += 1 if time.minute >= 60: time.minute -= 60 time.hour += 1
""" Time """ class Time(object): """Represents the time of day. attributes: hour, minute, second """ #create a new Time object and assign attributes def print_time(object): print("%.2d : %.2d : %.2d" % (object.hour, object.minute, object.second)) time = Time() time.hour = 11 time.minute = 59 time.second = ...
""" Create a dictionary of parameters """ from typing import Dict from .... import tk def preprocess(user_dict, default_dict): # type: (Dict, Dict) -> Dict """Create a new parameter dictionary Create a new parameter dictionary based on user inputs and defaults. Args: user_dict (dict): us...
""" A function returning a color string given an index and a list of color options """ from typing import List, AnyStr def choose_color(i, color_list): # type: (int, List[AnyStr]) -> AnyStr """Return a color Return a color given a integer index and a list of color options. If index is greater tha...
""" Read a file or just a number. This allow user to specify either a single number or a file that contains a number """ import numpy def readFileOrNumber(x): """Read a file or just a number Args: x: file name or just a number Returns: a number (float) """ if isinstance(x, str): ...
""" Transpose data """ from numpy import ndarray import numpy def transpose(data, act=True): # type:(ndarray) -> ndarray """Transpose data Args: data (ndarray): input data act=True (bool): whether to do the transposing Returns: a new ndarray """ if act: return...
# -*- coding: utf-8 -*- """ Using the Python language, have the function ArrayRotation(arr) take the arr parameter being passed which will be an array of non-negative integers and circularly rotate the array starting from the Nth element where N is equal to the first integer in the array. For example: if arr is [2, 3, ...
sum = 0 # 轮子轴距的实现 class Whell: def __init__(self, delta_left, delta_right,angu,rad): self.delta_left = delta_left self.delta_right = delta_right self.angu =angu self.rad=rad; def displayCount(self): length_one_fram_ang = 12.03*3.1415926/450 whell_rounds=(self.d...
# 实例属性和类属性 # 给实例绑定属性的方法是通过实例变量,或者通过self变量: class Students(object): def __init__(self, name): self.name = name s = Students('Bob') s.score = 90 # 但是,如果Student类本身需要绑定一个属性呢?可以直接在class中定义属性,这种属性是类属性,归Student类所有: class Student(object): name = 'Student' s = Student() # 创建实例s print(s.name) # 打印name属性,...
# 排序算法 ''' Python内置的sorted()函数就可以对list进行排序: ''' print(sorted([36, 5, -12, 9, -21])) print(sorted([36, 5, -12, 9, -21], key=abs)) # 按照绝对值排序 # 对字符串排序,是按照ASCII的大小比较的,由于'Z' < 'a',结果,大写字母Z会排在小写字母a的前面。 print(sorted(['bob', 'about', 'Zoo', 'Credit'])) ''' 我们提出排序应该忽略大小写,按照字母序排序。要实现这个算法,不必对现有代码大加改动,只要我们能用一个 key函数把字符串映射为忽略大小...
lines_seen = set() # holds lines already seen with open("Output_file.txt", "w") as output_file: for each_line in open("Input_file.txt", "r"): if each_line not in lines_seen: # check if line is not duplicate output_file.write(each_line) lines_seen.add(each_line)
#!/usr/bin/env python # La primera letra de cada palabra. Por ejemplo, si recibe Universal Serial Bus debe devolver USB. def iniciales(cadena): lista=cadena.split(" ") return "".join(palabra[0] for palabra in lista) # Dicha cadena con la primera letra de cada palabra en mayúsculas. Por ejemplo, si recibe repú...
# MSSERG | 13:00 MSC 20.01.2018 print('''Калькулятор: \nРасчёт зарплаты производиться по формуле N/100*80.5 для нахождения чистой зарплаты, и N+(N/100*19.5) для нахождения оклада, где N=Одно из значений зарплаты (чистая или оклад), коэффициенты: ставка НДФЛ-18%, военный сбор-1.5%.\n''') check = int(input('Же...
#! /usr/bin/env python # -*- encoding:utf-8 -*- """This module will be used to filte the word from input file with the stopword file. Usage: python SEFilter.py filename """ import sys import codecs import __init__ from SEPreprocess.ReadConfig import ReadConfig from SEUtility.File_RW import DictPrint,ReadIntoDict def ...
""" Given n, how many structurally unique BST's (binary search trees) that store values 1...n? For example, Given n = 3, there are a total of 5 unique BST's. 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 ...
""" How to use draw_graph3D to create a tridimensional grid connected graph """ import numpy as np import maxflow from examples_utils import plot_graph_3D def create_graph(width=6, height=5, depth=2): I = np.arange(width*height*depth).reshape(depth, height, width) g = maxflow.Graph[float]() nodeids = g...
a=str(input("enter ur name:")) b=int(input("enter ur age:")) c=str(input("enter ur address:")) print(a,"\n",b,"\n",c)
amt=int(input("enter the amount")) note=int(input("enter the sample notes")) no=amt//note print("no of notes :", no)
n = int(input()) d ={} for i in range(n): text = input().split() d[text[0]]=int(text[1]) for i in d: print(i) for i in d.values(): print(i)
#Python program to add a key to a dictionary car={"brand":"ford", "model":"mustang"} print(car) car.update({"year":2009}) print(car)
#Python program to add an item in a tuple a=input().split(",") b=tuple(a) print(b) b=b+(9,0) print(b)
d1={'a':1,'b':2} d2={} for i in(d1,d2): if(len(i)>0): print("the dictionary is not empty") else: print("the dictionary is empty")
import queue class Node: id = -1 pai = None def __init__(self,id): self.id = id class Grafo: matriz = [] n = 0 direcionado = False def __init__(self,n): self.n = n for i in range(n): self.matriz.append([0]*n) def...
from numpy import genfromtxt import numpy as np from scipy import optimize # loosely adopted from Welch labs tutorial class NeuralNetwork(object): def __init__(self): #Define Hyperparameters self.inputLayerSize = 7 self.hiddenLayerSize = 3 self.outputLayerSize = 1 ...
import unittest import pythoncode location = './input/itcont.txt' class TestCalc(unittest.TestCase): def test_nsubs(self): result1, result2 = pythoncode.summarize(location) self.assertEqual(result1,1) print("Only " + str(result1) + " unique prescriber - his name is Amir") ...
#!/usr/bin/python3 """Unittest for max_integer([..])""" import unittest max_integer = __import__('6-max_integer').max_integer class TestMaxInteger(unittest.TestCase): """unittest class for max_integer""" def test_max_integer(self): """ tests""" self.assertEqual(max_integer(""), None) ...
#!/usr/bin/python3 def multiply_by_2(a_dictionary): dic = {} for key, value in a_dictionary.items(): dic[key] = (value * 2) return dic
#!/usr/bin/python3 """ containes class Rectangle """ from models.rectangle import * class Square(Rectangle): """ class square """ def __init__(self, size, x=0, y=0, id=None): """constructor""" super().__init__(size, size, x, y, id) def __str__(self): """ toString""" return...
#!/usr/bin/python3 """number_of_lines""" def number_of_lines(filename=""): """number of lines of file""" with open(filename, 'r', encoding='utf8') as file: i = 0 for l in file: i += 1 return i
""" This files defines all the different maps and the map class """ import images import pygame import os main_dir = os.path.split(os.path.abspath(__file__))[0] + "//maps//" #The directory to the saved maps, in folder maps map_list = {} #All maps will be saved here class Map: """ An instance of Map is a blueprint ...
""" This file defines the class A.I and declares its methods. """ import math import pymunk from pymunk import Vec2d import gameobjects from collections import defaultdict, deque import sounds # NOTE: use only 'map0' during development! MIN_ANGLE_DIF = math.radians(3) # 3 degrees, a bit more than we can turn each ti...
import Traductores.condiciones from Traductores.variables import variables from Traductores.funciones import funciones from Traductores.comentarios import comentarios class ciclos(object): def __init__(self, ast, anidado): self.ast = ast['Ciclo'] self.exec_string = "" self.anidado = anidado de...
""" Author: Phạm Thanh Nam Date: 30/10/21 File: savingsaccount.py This module defines the SavingsAccount class. """ class SavingsAccount(object): """This class represents a savings account with the owner's name, PIN, and balance.""" RATE = 0.02 # Single rate for all accounts def __in...
import faiss import numpy as np from scipy import sparse, special def estimate_pdf(target, emb, C=0.1): """Estimate the density of entities at the given target locations in the embedding space using the density estimator based on the k-nearest neighbors. :param target: Target location at which the de...
# This function reads text data from a text file def readFile(file_name): data = "" file = open(file_name, "r") for line in file: data = data + line.strip("\n") return data # This function prints the frequency dictionary def printFreqsDict(freqs_dict): for key, val in freqs_dic...
# CalculateDistancePatternDna.py # # Written by: Steven Parker and Lynn Bui # # ######################################### # Upload the Dna file def readFile(file_name): data = [] file = open(file_name, "r") for line in file: data.append(line.strip("\n")) return data # Hamming Dista...
''' Return fibonacci No. for given no. M ''' ''' To run: python denominations.py 6 Output: 8 ''' import sys m = int(sys.argv[1]) def fib(n): if n == 0 or n == 1: return n return fib(n-1) + fib(n-2) print fib(m)
print('Введите число:') a = int(input()) if a > 0: print('Ваше число больше нуля - оно положительное )') elif a < 0: print('Ваше число меньше нуля - оно отрицательное (') elif a == 0: print('Ваше число равняется нулю - оно нейтрально')
balance = 0 drinks = [ {'name': '可樂', 'price': 20}, {'name': '雪碧', 'price': 20}, {'name': '茶裏王', 'price': 25}, {'name': '原萃', 'price': 25}, {'name': "純粹喝", 'price': 30}, {'name': '水', 'price': 20}, ] def add(x, y): """ 數字相加 :param x: 數字1 :param y: 數字2 :return: 相加結果 """ ...
#customized utils import math import json_utils import graphspace_utils def parse_input(edgefile, delimiter, isDirected=False, isWeighted=False): """ Input file parser that takes in a file full of edges and parses them according to a modular delimiter. Can handle edge files that have weights, but the setting i...
def calculator(): num1 = float(input("Enter a number:")) op = input("Enter a operator:") num2 = float(input("Enter a number:")) if op == '+': return round(num1 + num2) elif op == '-': return round(num1 - num2) elif op == '*': return round(num1 + num2) elif op == '/': return round(num1 + nu...
auction = {} def max_offer(auction): max = -1 winner = '' for bidder in auction: if auction[bidder]>max: max = auction[bidder] winner=bidder return winner print("Welcome to the secret auction") while True: name = input("Input your name: \n") offer = float(input...
def add(x,y): return x+y def substrac(x,y): return x-y def multiply(x,y): return x*y def divide(x,y): return x/y operations={ "+":add, "-":substrac, "*":multiply, "/":divide } carry = 'no' print("Simple calculator") while True: if carry == 'no': num1 = int(input("Input th...
from calculate.calculate import Calculate cal = Calculate() print("Currently IOTA/USD --->" + str(cal.GotIOT2USD())) print("Currently IOTA/BTC ---> " + str(cal.GotIOT2BTC())) print("Currently BTC/TWD --->" + str(cal.GotSellPrice())) try: select = input("choose you want \n1. Mi to TWD \n2.TWD to Mi\n") if se...
# -*- coding: utf-8 -*- import Utils import BaseThreadedModule import Decorators import re import sys @Decorators.ModuleDocstringParser class Math(BaseThreadedModule.BaseThreadedModule): """ Execute arbitrary math functions. Simple example to cast nginx request time (seconds with milliseconds as float) t...
# v1: Ordenacao para "arrays alvo" -> Com QuickSort para array "incial", com InsertionSort para array com os elementos finais # INPUT-PALAVRAS: SEM ordenacao por insercao NEM pesquisa binaria no array_palavras e no array auxiliar dos IDs para eficiencia # #### BIBLIOTECAS #### import sys # #### CONSTANTES #### CMD_...
for i in range(0, 10): #Number of rows for j in range(0, i): #Blank spaces before the stars print(' ', end = ' ') for k in range(0, 19 - 2 * i): #Number of stars per row print('*', end = ' ') print('') #New line after each row
# a prompt series that displays different prompts based on user input, choose-your-own-adventure style # prepare to receive yes/no resposes from the user affirmativeResponses = ['yes', 'y', 'yep', 'affirmative'] negativeResponses = ['no', 'n', 'nope', 'negative'] def getYNResponses(x): # forces yes/no response from us...
''' Created on Jun 1, 2013 @author: Nenad Blackjack is a simple, popular card game that is played in many casinos. Cards in Blackjack have the following values: an ace may be valued as either 1 or 11 (player's choice), face cards (kings, queens and jacks) are valued at 10 and the value of the remaining ca...
# tree data structure from graphviz import Digraph, Source import rospkg class Tree: """ A class to represent the structure of a node ... Attributes ---------- name : str Name of the state. nodeType : str Type of state machine - state, parallel state machine, sequential s...
import numpy as np from scipy.spatial.transform import Rotation from matplotlib import pyplot as plt """ This file is a toy example to understand and test using Quaternion for rotations and PID controllers. """ class Quaternion: def __init__(self, q_0=0, q_1=0, q_2=0, q_3=1): self.q_0 = q_0 self.q...
import hashlib str = "String" result = hashlib.md5(str.encode()) print(f"The hexadecimal equivalent of hash is : result.hexdigest()")
def reverse(str1): i=0 j=(len(str1)-1) while (i<j): temp2=str1[i] str1 = str1[:i]+str1[j]+str1[i+1:] str1 = str1[:j]+temp2+str1[j+1:] i+=1 j-=1 return str1 str2 = input('Enter the string:') print("String before reverse: {}".format(str2)) print("String aft...
ss=input() c=0 for i in range(len(ss)): if (ss[i].isalpha() or ss[i].isnumeric() or ss[i]==" "): continue c=c+1 else: print(c)
u=input() y=set(u) if(y=={"0","1"}): print("yes") else: print("no")
n=int(input()) sum=0 for i in range(1,n+1): sum+=i print(sum)
import math #What is the largest prime factor of the number 600851475143? n=raw_input('Enter the integer you wish to find the prime factors of: ') n = int(float(n)) L=[] def too_small(): """to be called for int < 4""" L.append(n) if n>0: L.append(1) retu...
#!/usr/bin/env python3 ''' Mediator is a behavioral design pattern that lets you reduce chaotic dependencies between objects. The pattern restricts direct communications between the objects and forces them to collaborate only via a mediator object.''' class Mediator: def __init__(self): self._colleague_1 ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- a = int(input("введите число:")) if a < 0: print("Neg") elif a == 0: print("Zero") else: print("Pos")
from __future__ import division import math import json class TargetLoc: # Generates new points along the line between drone and target using drones current x,y position and Line of Bearing def locate(self, tc): # inputs are JSON Records a set of three points in the form of 'lat', 'l...
def control_equal(*variables): for variable0 in variables: for variable1 in variables: if variable0 != variable1: return False return True def control_not_equal(*variables): n = 0 for variable0 in variables: n += 1 for variable1 in variables[n:]: ...
# Задание №1 # Пользователь вводит с клавиатуры 4 целых числа. # Напишите функцию следующим образом: если первое число больше второго, # то выводится среднее арифметическое всех четырех чисел, # иначе надпись 'Ошибка'. # # Выполнил # Петров Данил Анатольевич # Mail: cclarice@student.21-scho...
import pandas as pd import numpy as np print('====what is a dataframe====') # df is a 2-dim labeled data structure with columns of potentially different types print('====create a dataframe====') # use a dictionary(1D ndarrays, lists, dicts, or Series) d = {"Math": [100, 99, 89], "Chemistry": [98, 80, 78], "...
# ======variables====== string = 'hello, let\'s learn python' string1 = '--test the strip()---' # ======Escape character====== print('doesn\'t') print("doesn't") # ======Common functions====== string.replace(",", "") # 把所有的','去掉 string.split(" ") # 以" "为分隔符,分割成列表的形式. # split(str="", num=string.count(str)) (分隔符,要分...
def hello_name(name): return("Hello " + name + "!") def make_abba(a, b): return(a + b + b + a) def make_tags(tag, word): return("<" + tag + ">" + word + "</" + tag + ">") def make_out_word(out, word): return(out[0:2] + word + out[2] + out[3]) def extra_end(str): return(str[-2]+str[-1]+str[-2]+...
import pandas as pd df = pd.read_csv('olympics.csv',index_col=0,skiprows=1) df.head() for col in df.columns: if col[:2]=='01': df.rename(columns={col:'Gold'+col[4:]}, inplace=True) if col[:2]=='02': df.rename(columns={col:'Silver'+col[4:]}, inplace=True) if col[:2]=='03': df.renam...
# -*- coding: utf-8 -*- """ Created on Fri May 21 10:35:56 2021 check whether a number is a huppay number """ def numSquareSum(n): squareSum = 0 n = str(n) l = list(n) l = list(map(int,l)) for i in l: squareSum += i**2 return squareSum def main(): n = int(input("C...
from .Die import Die class DiceSet: """ Simple set of dice with custom number of sides. Any dice set can have any number of dice and each dice having the same number of sides. Attributes: dice (int) representing the number of dice in the box sides (int) representing the number of sides eac...
from tkinter import * from random import randrange def drawline(): "Tracé d'une ligne dans le canevas can1" global x1, y1, x2, y2, coul can1.create_line(x1,y1,x2,y2,width=2,fill=coul) y2, y1 = y2+10, y1-10 def changecolor(): "Changement aléatoire de la couleur du tracé" global coul pal=['p...
a=5 b=10 print("This file tests conditional statements") print("a: ") print(a) print("b: ") print(b) # test < print("a < b:") print(a < b) # test <= print("a <= b:") print(a <= b) # test > print("a > b:") print(a > b) # test >= print("a >= b:") print(a >= b) # test == print("a == b:") print(a == b) # test != pri...
""" Purpose Recover wasted disk space, by finding duplicate files. Their removal could potentially free a lot of disk space. Two things: 1. what image has the most duplicates 2. what image takes the most space Searches deep inside a directory structure, looking for duplicate file. Duplicates aka copies have t...
print('My name is') for ii in range(5): print('Jimmy Five Times (' + str(ii) + ')') sum = 0 for i in range(101): sum = sum + i print(sum) for i in range(1, 10, 3): print(i) for i in range(0, -10, -2): print(i)
v = list() def s(val, list_v): list_v.append(val) for i in range(10): print(v) s(i, v) print(v)
while True: import pyfiglet # pyfiglet lib ascii_banner = pyfiglet.figlet_format("Ascii-Py") print(ascii_banner) print("Text to convert below...") inp = input() ascii_result = inp if ascii_result.isalpha: print(pyfiglet.figlet_format(ascii_result))
'''Creating a machine learning model for sentiment analysis. Training data will be the New_sentiment_train.csv file created with the original stanford sentiment Treebank. Then, apply the ML model on web scraped data containing amazon reviews of 10 mobile phones. ''' import pandas as pd from sklearn.feature_extra...
import shelve def create(): shelf = shelve.open("mohit.raj", writeback=True) shelf['desc'] ={} shelf.close() print "Dictionary is created" def update(): shelf = shelve.open("mohit.raj", writeback=True) data=(shelf['desc']) port =int(raw_input("Enter the Port: ")) data[port]= raw_input("\n Enter th...
import unittest from unittestfile.count import Count #必须要继承TestCase类 class CountTest(unittest.TestCase): #每条用例开始执行setup和结束teardown都会执行 def setUp(self): print("start") def tearDown(self): print("end") #必须要以test_开头 def test_sub(self): c = Count(13,5) result = c....
from multiprocessing.pool import Pool class Menu: def __init__(self): self.title = '网易云音乐' if __name__ == '__main__': select = ['1,爬取热门歌单','2,爬取歌单详细','3,爬取歌曲评论'] while True: for s in select: print(s) key = input("选择操作:") # 爬取歌单 if key == '1': ...
#!/usr/bin/python '''USAGE: fq2fa.py fastq Converts a fastq to a fasta ''' import sys fasta = str(sys.argv[1]).rstrip('fastq') + 'fasta' fasta = open(fasta, 'w') with open(sys.argv[1], 'r') as fastq: current = 1 for line in fastq: if current == 1: line = line.replace('@','>') line = line.replace(' ','|') ...
# записать в список только положительные числа numbers = [1, 2, 3, 4, 5, -1, -2, -3, -4, -5] # классический случай result = [] # переменная для результата for number in numbers: # в цикле перебираем наши числа if number > 0: # если число > 0 result.append(number) # то добавляем в результат это число print(...
import random words_list = ('автострада', 'бензин', 'инопланетянин', 'самолет', 'библиотека', 'шайба', 'олимпиада', 'зима', 'пальма') secret_word = random.choice(words_list) print(secret_word) gamer_word = ['*'] * len(secret_word) print(''.join(gamer_word)) # gamer_word[2] = 'г' # print(''.join(gamer...
# Функция - map # Набор чисел numbers = [5, 3, 4, 7, 8] # Получить список квадратов чисел print(list(map(lambda x: x**2, numbers))) # Получаем [25, 9, 16, 49, 64] # Привести числа к строке print(list(map(lambda x: str(x), numbers))) # Получаем ['5', '3', '4', '7', '8']
def my_f(my_var): my_var = 999 print('Внутри функции:', my_var) a = 1 my_f(a) print('После выполнения функции: ', a) global_var = 1 def my_f2(): # Локальная переменная local_var = 100 # Используем ее внутри функции print(local_var) # Глобальная переменная, объявлена в модуле (изменить нел...
# 2: Дан список, заполненный произвольными числами. # Получить список из элементов исходного, удовлетворяющих следующим условиям: # Элемент кратен 3, # Элемент положительный, # Элемент не кратен 4. numbers = [1, 5, -9, 10, 27, 0, 17, 45, 100, 11, -7, 12, -27] result = [number for number in numbers if number > 0 and n...
'''Exercise : how many''' # write a procedure, called how_many, which returns the #sum of the number of values associated with a dictionary. def how_many(animals): ''' aDict: A dictionary, where all the values are lists. returns: int, how many values are in the dictionary. ''' # Your Code Here ...
'''define the simple_divide function here''' def simple_divide(item, denom): '''start a try-except block''' try: return item / denom except ZeroDivisionError: return 0 def fancy_divide(list_of_numbers, index): '''fun''' denom = list_of_numbers[index] return [simple_divide(item,...
x = 2 for x in range(2,11,2): print("print"+" "+str(x)) print("print Goodbye!")
''' Write a python program to read multiple lines of text input and store the input into a string. ''' def newlines(newline): '''printing new line''' newl = newline return newl def main(): '''f ''' documents = "" lines = int(input()) for i in range(lines): i += 1 documen...
#! /usr/bin/python2.7 #''' ##################################################################### # function: find how many same character in array. # input = ['a', 'b', 'c', 'd', 'e', 'a', 'a', 'b', 'e'] class soluTion(object): def searchDuplicate(self, arrayA): lenGth = len(arrayA) result = [] ...
#! /usr/bin/python2.7 #''' ##################################################################### # function: LeetCode:Easy 26. return number of array after removing Duplicates from Sorted Array # Input: [1,1,2] # Output: [1,2] -> 2 # Input: [0,0,1,1,1,2,2,3,3,4] # Output: [0,1,2,3,4] -> 5 print("================...
#! /usr/bin/python2.7 #''' ##################################################################### def appendFile(text, filename): with open(filename, "a") as f: f.write(text) f.write("\n") f.close() #infile = "a3"+".out" #appendFile("hahaha", infile) appendFile("hahaha", "a3.out") appendFile...
def MisterRobot(n, data): sort_data = data[:] sort_data.sort() flag = True while flag: flag = False for i in range(n - 2): if (data[i + 1] > data[i] > data[i + 2] or data[i] > data[i + 1] and data[i + 1] < data[i + 2]): data[i], data[i + 1]...
# import statements. from globals import friends,Spy from termcolor import colored from spy_details import spy # add new friends. import re def add_friend(): new_friend =Spy(" "," ",0,0.0,False) tempcheck=True#temporary variable #Validation Using Regex patternsalutation='^Mr|Ms$' patternname='^[A-Za...
import re # # Funcion para crear un objeto de tipo TimeCode a partir de un string ("08:37:45:17" o "08:37:45;17") y de un entero con el Frame Rate # # Emiliano A. Billi 2011 # class TimeCodeError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value...
# -#- coding: utf-8 -*- #sys是一个包,argv是这个包中的一个模块 from sys import argv script,filename = argv #使用open函数可以找到文件,并返回一个file对象给txt变量 txt = open(filename) print "Here's your file %r:" % filename #file.read([size])函数是读取文件内容,如果不写size,则一直读到文件末尾(EOF),否则读入size字节的内容 #file对象调用read函数后文件指针不会回溯到文件头 print txt.read() #读完文件就关闭文件对象是个好习惯 t...
import math def olympic_ring(string): li='ADOPQRabdegopq' count=0 for x in string: if x in li: count=count+1 elif x=='B': count=count+2 count=math.floor(count/2) if count<2: return 'Not even a medal!' elif count==2: return 'Bronze!' eli...
def find_outlier(integers): index=[] for i in range(len(integers)): index.append((integers[i])%2) if (sum(index))==1: return(integers[(index.index(1))]) return(integers[(index.index(0))])
def countBits(n): bitstring = "" n=int(n) bit=0 ans=0 while n>0: bit=int(n%2) quotient=int(n/2) bitstring=str(bit)+bitstring n=quotient for i in range(len(bitstring)): ans=ans+int(bitstring[i]) return(ans)
def is_divisible(n,x,y): if n%x==n%y==0: return True return False