text
stringlengths
37
1.41M
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Apr 19 14:31:10 2021 @author: gustavo """ import random import numpy as np import math # OBJEIVO: CAFE def fitnessFuncion(individuo): objetivo = ['h', 'o', 'l', 'a', ' ', 'm', 'u', 'n', 'd', 'o'] aptitud = 0 indice = 0 for letra in ob...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Feb 22 14:28:16 2021 UNIVERSIDAD AUTÓNOMA DEL ESTADO DE MÉXICO CENTRO UNIVERSITARIO UAEM ZUMPANGO INGENIERÍA EN COMPUTACIÓN ALGORITMOS GENÉTICOS Alumno: Gustavo Rodrígez Calzada Profesor: Asdrúbal Lopez Chau Descripción: Implementa un cromosoma para r...
import torch def f(x): """最小解を求めたい関数""" return (x[0] - 2 * x[1] - 1)**2 +(x[1] * x[2] - 1)**2 + 1 def f_grad(x): """変数がある値のときの微分値を求める関数""" z = f(x) z.backward() return x.grad if __name__ == '__main__': # 初期値を決める(1, 2, 3) x = torch.tensor([1., 2., 3.], requires_grad=True) for i in ...
def konwerter_rekurencyjny(n, base): # (generator) # UWAGA! Zwraca od tyłu, nie tłumaczy na litery (A to 11, B to 12 etc.) yield n % base if n // base >= base: yield from konwerter_rekurencyjny(n // base, base) else: yield n // base def konwerter_iteracyjny(n, base): # ??? # ni...
import pandas as pd import numpy as np import matplotlib.pyplot as plt #import dataset df=pd.read_csv("Salary_data.csv") X=df.iloc[:, :-1] y=df.iloc[:, 1] #spliting dataset into two part trainingset & test set from sklearn.cross_validation import train_test_split X_train,X_test,y_train ,y_test =train_test_spli...
# mike n Pi # print("Mike H") # 29.10.2019 15:17:34 print ( 365 / 180) import turtle turtle.color("red") turtle.width(5) turtle.shape("turtle") def one_line(): turtle.forward(100) turtle.right(90) for i in range(1, 5, 1): one_line()
from tkinter import * def updateTextFill(num): global text_string text_string += str(num) text_label.set(text_string) def equal(): global text_string try: total = str(eval(text_string)) text_string = total text_label.set(text_string) text_string = "" except Syn...
#Παιχνίδι της κρεμάλας στο οποίο πρέπει να μαντέψετε ονόματα μεθόδων κάποιων βασικών τύπων της Python, #όπως αυτά επιστρέφονται από τη συνάρτηση dir. #Η main συνάρτηση. import random from wordGuessing import wordGuessing from RandomWord import RandomWord from draw import draw from findLetters import findLett...
class Car(object): def __init__(self, price, speed, fuel, mileage,): #attributes: price, speed, fuel, mileage self.price = price self.speed = speed self.speed = fuel self.mileage = mileage self.tax = .12 self.display_all = #In the class have a method called display_all() that returns all the ...
def draw_stars(lst): for ele in lst: #this will simply iterate over the list. convention dictates the use of "ele". if type(ele) == int: stars = "" for s in range(ele): stars += "*" print stars elif type(ele) == str: stars="" letter = ele[:1] for s in range(len(ele)): stars += letter.lowe...
def multiply(lst,num): for idx in range(len(lst)): lst[idx] *= num return lst a = [2,4,10,16] b = multiply(a,5) print b
from flask import Flask, render_template, request, redirect from mysqlconnection import MySQLConnector app = Flask(__name__) mysql = MySQLConnector(app, 'mydb') @app.route('/') def index(): #Display all of the friends on the index.html page query = "SELECT * FROM friend ORDER BY created_at DESC;" friends = mysq...
from system.core.model import Model class Course(Model): def __init__(self): super(Course, self).__init__() def get_all_courses(self): return self.db.query_db("SELECT * FROM course") def get_course_by_id(self, id): # pass data to the query like so query = "SELECT * FROM co...
import unittest from underscore import Underscore class UnderscoreTest(unittest.TestCase): def setUp(self): # create an instance of the Underscore module we created self._ = Underscore() # initialize a list to run our tests on self.test_list = [1,2,3,4,5,6,7] self.map_result...
# import the urlopen function from the urllib2 module from urllib2 import urlopen # import the BeautifulSoup function from the bs4 module from bs4 import BeautifulSoup # import pprint to print things out in a pretty way import pprint #import re to use regex import re # choose the url to crawl url = 'http://www.codingdo...
class Underscore(object): def map(self,*args): try: return [args[1](i) for i in args[0]] except: return "invalid inputs" def reduce(self,*args): count = 0 try: for i in args[0]: if count == 0: reduced = args[0][0] else: reduced = args[1](reduced,i) ...
#https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def getTargetCopy(self, original: Tre...
#https://leetcode.com/problems/convert-to-base-2/ class Solution: def baseNeg2(self, N: int) -> str: s = '' temp = N if N == 0: return "0" while abs(temp) >= 1: digit = int(fmod(temp, -2)) temp /= -2 if digit < 0: ...
#https://leetcode.com/problems/count-good-nodes-in-binary-tree/ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def recurse(self, root, maxk): if r...
#Created when I first began learning how to program print ("*"*60) print ("*"*60) print("** This programs calculates the equation of a line **") print("** Created by Parmvir Bath **") print ("*"*60) print ("*"*60) #Ask user to input points x1 = int(input("What is the valu...
""" Fractal Generation in Python by Chris Achenbach Using the Escape Time Algorithm to generate the Mandelbrot Set. The program is composed of several parts: - given variables (input) - initalizing data - main algorithm - image output """ # -------------------------------------------------------------------------...
# quick component to convert degrees C to F. # Function takes in value, does conversion and puts answer into a list def to_f(from_c): fahrenheit = (from_c * 9/5) + 32 return fahrenheit # Main Routine temperatures = [0, 40, 100, 3] converted = [] for item in temperatures: answer = to_f(item) ans_sta...
#!/usr/bin/env python # %% import time import threading from concurrent.futures import ThreadPoolExecutor def worker(name): print(f"{name} start...") time.sleep(2) print(f"{name} done.") # %% # 单线程阻塞 # 阻塞线程的情况下,程序会先等待线程任务执行完,再往下执行其他代码 def single_thread_block(): t = threading.Thread(target=worker, ar...
#!/usr/bin/python def binary_search(list1, item): low = 0 high = len(list1) - 1 while low <= high: mid = int((low + high) / 2) # print("mid", mid) guess = list1[mid] if guess == item: return mid elif guess > item: high = mid - 1 else: ...
def add(a, b, c): return a*b+c a = 1 b = 2 c = 3 print(add(a, b, c))
""" msg = "hello world" print(3.14) print("3.14") print(''''we should"''') print() print('''') """ # docstring- modullere tanımlama yapma """ print(print.__doc__) print(map.__doc__) print(sum.__doc__) print(input.__doc__) print(input.__doc__) """ # NAMİNG VARİABLES # vari...
# -*- coding: utf-8 -*- sayilar = [1,5,15,35,57,72,75,10,4,20] """ for i in sayilar: print(i) for (i) in sayilar: if (i%5==0): print(i) toplam = 0 for i in sayilar: toplam = toplam + i print(toplam) for i in sayilar: if (i % 2 == 0): print(i**2) """ """ urunler = ["iphone 8","iphone ...
# -*- coding: utf-8 -*- def leap(year): if not year % 4 and year % 100 or not year % 400: return f"{year} is a leap year" else: return f"{year} is not a leap year" print(leap(2020)) print(leap(2000)) print(leap(2100)) print(leap(2500))
# -*- coding: utf-8 -*- class Comment: def __init__(self,username, text,likes=0,dislikes=0): self.username = username self.text = text self.likes = likes self.dislikes = dislikes c1 = Comment("maykurt","ne mutlu türküm diyene",215,1) c2 = Comment("ahmet_y","güzel mac",1515,1) c3 = C...
# -*- coding: utf-8 -*- """ x = ["false", 0, True] # all - any y = [] z = [0,()] print(all(y)) x = list(filter(lambda x: x%2==0, range(5))) # filtreleme print(x) x = enumerate(range(5),10) # numaralandırma print(*x) def calculator(a,b,opr): if opr == "+": print(a+b) elif opr == "-": print(...
# -*- coding: utf-8 -*- """ while 0: print("bir") print("outside while") number = 0 while number<6: print(number) number +=1 print("now") number = 0 while number<6: print(number) number +=2 print("now") """ # yaşı doğru girdiren bir kod. """ age = input("Enter your age : ") while not age.isdigi...
# -*- coding: utf-8 -*- #with open("markalar.txt","a") as file: # file.write("6-bmw \n") #with open("markalar.txt","r+",encoding=("utf-8")) as file: # markalar = file.read() # markalar = "1-toyota\n"+markalar # file.seek(0) # file.write(markalar) with open("markalar.txt","r+",encoding=("utf-8")) as f...
# -*- coding: utf-8 -*- jan = mar = may = july = aug = octc = dec = 31 apr = jun = sep = nov =30 feb = 28 print(jan,feb,mar,apr,may,jun,july,aug,sep,octc,nov,dec) x = y = 12 print(x,y) x = 11 y = 12 z = 13 x = 14 z = 15 x = 16 print(x,y,z)
# -*- coding: utf-8 -*- #sayi int(input("sayi giriniz : ")) # if (sayi>50) and (sayi<100): # print("sayi 50 ile 100 arasındadır") # else: # print("sayi 50 ile 100 arasında değildir") """ if (sayi>0) and (sayi % 2==1): print("sayi pozitif tek sayıdır") else: print("sayı pozitif tek sayı DEGİLDİR") ...
# -*- coding: utf-8 -*- numb = int(input("enter a integer value : ")) fact = 1 process = list(range(1, numb+1)) for i in process: fact *= i print(fact)
# -*- coding: utf-8 -*- """ def is_palindrome(string): # backwards = string[::-1] # return backwards == string return string[::-1].casefold() == string.casefold() def palindrome_sentence(sentence): string = "" for char in sentence: if char.isalnum(): string += char print(s...
# -*- coding: utf-8 -*- """ ## append "a" modu ile sona ekleme yaparız-- cursor un yeri önemli değil with open("newfile.txt","w",encoding=("utf-8")) as file: file.write("murat aykurt \n") file.write("selin") file.close print(file) with open("newfile.txt") as file: print(file.read()) with open(...
#!/usr/bin/env python3 import math def calculate_fuel(mass): fuel = math.floor(mass/3.0) - 2 return max(fuel,0) def calculate_total_fuel(mass): fuel = calculate_fuel(mass) total_fuel = fuel while(fuel > 0): fuel = calculate_fuel(fuel) total_fuel += fuel return total_fuel...
#!/usr/bin/env python3 PROGRAM_START_ADDRESS=0 OUTPUT_ADDRESS = 0 NOUN_ADDRESS=1 VERB_ADDRESS=2 PROGRAM_STEP_LENGTH=4 PROGRAM_ADD_CODE=1 PROGRAM_MULT_CODE=2 PROGRAM_STOP_CODE=99 KNOWN_OPERATOR_CODES = [PROGRAM_ADD_CODE, PROGRAM_MULT_CODE] def pre_process(noun, verb, input_data): input_data[NOUN_ADDRESS] = nou...
from dicecup import DiceCup class PyZhee(DiceCup): def __init__(self): super().__init__('5d6') def find_kinds(self, num): """ Finds X of a Kind and puts them in a list of tuples (value, number_of_value) """ count = self.count() results = [] for key in c...
def get_max(dic): """ Given a dictionary of keys with related values, return the entry with the highest value Example: A scoreboard of players and their scores. """ if len(dic.items()) == 0: return None max_item, max_value = list(dic.items())[0] for elem in dic: if dic[elem] ...
#求和函数 可变参数 def cal_sum(*args): ax = 0 for n in args: ax = ax + n return ax print(cal_sum(10,12,4234,324)) #函数式编程 #函数作为返回值 def lazy_sum(*args): def sum(): ax = 0 for n in args: ax = ax + n return ax return sum f = lazy_sum(1,2,5,2) print(f)
import os def draw_board(board): print() print(' TIC TAC TOE') print() print() print(' | |') print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9]) print(' | |') print(' -----------------') print(' | |') print(' ' + board[4] + ' ...
''' Your function should take in a single parameter (a string `word`) Your function should return a count of how many occurences of ***"th"*** occur within `word`. Case matters. Your function must utilize recursion. It cannot contain any loops. ''' def count_subword(subword, word, start=0): count = None #==...
#Your task in order to complete this Kata is to write a #function which formats a duration, given as a number #of seconds, in a human-friendly way. #The function must accept a non-negative integer. #If it is zero, it just returns "now". #Otherwise, the duration is expressed as a combination #of years, days, hours...
# Uses python3 import sys def euclidGCD(a,b): if b == 0: return a else: c = a%b return euclidGCD(b,c) def lcm(a, b): gcd = euclidGCD(a, b) lcm = a*b/gcd return int(lcm) if __name__ == '__main__': #input = sys.stdin.read() a, b = map(int, input().split()) print(lcm(a, b))
from tkinter import * from tkinter import messagebox, simpledialog, Tk import turtle window = Tk() window.withdraw () window_width = 800 window_height = 800 root = Tk() canvas = Canvas(root, width=window_width, height=window_height, borderwidth=0, highlightthickness=0, bg="#000050") canvas.grid() # th...
class Gladiator: def __init__(self, name, weapon): self.name = name self.weapon = weapon class Arena: def __init__(self, name): self.name = name.capitalize() self.gladiators = [] def __repr__(self): return self.gladiators def addGladiator(self,gladiator)...
def count_zero(zlist): count=[] if 0 in zlist: for i in range(len(zlist)): if zlist[i]==0: zero = 0 while zlist[i]!=1: zero+=1 i+=1 if i>=len(zlist): i-=1 ...
import os import time import datetime import argparse from strings import xml_file, xml_item parser = argparse.ArgumentParser(description='Generate an rss file from a folder.') parser.add_argument('path', type=str, help='Path to the folder to generate the RSS file from') parser....
# -*- coding: utf-8 -*- """ Created on Mon Mar 12 20:34:57 2018 @author: mudit """ import numpy as np import pandas as pd exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'], 'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19]...
def count_words(text: str, words: set) -> int: counter = 0 #will count words that we can find in text for word in words: #loop through every word in words and check if it is available in given text if word in text.lower(): counter += 1 else: continue ...
def first_word(text: str) -> str: """ returns the first word in a given text. """ if text=='hi': return 'hi' else: alphabet="abcdefghijklmnopqrstuwxyz'" str='' for i in range(len(text)): if text[i].lower() not in alphabet: pass ...
def index_power(array: list, n: int) -> int: """ Find Nth power of the element with index N. """ if n>=len(array): #return -1 for the cases when n >= len(array) - to avoid error: index out of range return -1 else: return array[n]**n
def checkio(number: int) -> str: if number%3==0 and number%5==0: return 'Fizz Buzz' elif number%3==0: return 'Fizz' elif number%5==0: return 'Buzz' else: return str(number)
def print_tiles(tiles, s, n: bool = False): size = (s * 2) + 1 offset = s + 1 l = [["." for _ in range(size)] for _ in range(size)] for y in range(size): for x in range(size): tile = (y - offset, x - offset) if tile in tiles: tile = tiles[tile] ...
TARGET = "shiny gold" def create_rules(s: str) -> dict: rules = {} for l in s.strip("\n").split("\n"): current_bag, contained_bags = l.strip().split(" bags contain ") contained_list = [] for b in contained_bags.split(", "): if b == "no other bags.": continue...
def move_direction(x, y, vx, vy, n) -> (int, int): x += vx * n y += vy * n return x, y def move_target(vx, vy, d, n): if d == "E": vx += n elif d == "W": vx -= n elif d == "S": vy -= n else: # "N" vy += n return vx, vy def rotate_direction(vx, vy, w, ...
n=list(input()) str1="" if (len(n)%2==0): c=int((len(n))/2) d=c-1 n[c]="*" n[d]="*" print(str1.join(n)) else: c=int((len(n))/2) n[c]="*" print(str1.join(n))
x,y=[int(i) for i in input().split()] x = x ^ y y = x ^ y x = x ^ y print(x,y)
n=int(input()) c=0 for i in range(0,11): if (n>=i and n<=i): c="yes" else: c="no" print(c)
n=int(input("enter no")) m=int(input("enter power")) s=n**m print(s)
# Start over again about game designing in Python import pygame as py #initialize game py.init() py.display.set_caption("Hello") screen = py.display.set_mode((500,500)) # initialize about characters images x = 40 y = 450 width = 40 height = 60 vel = 10 # initialize about the jumppart jumpCount = 10 isJump = False # r...
import unittest import sys from src import network as nn class Test(unittest.TestCase): def test_can_create_a_network(self): network = nn.NeuralNetwork([1,2,1]) print(network) self.assertEqual(len(network.weights), 2) self.assertEqual(len(network.weights[0]), 2) self.as...
# -*- coding: utf-8 -*- """ Created on Fri May 7 16:19:39 2021 @author: eagle """ ######################### tuple is unmutable ####################################################### ######################### tuple unpacking ####################################################### p=(4,5) print(p[0]) #########...
presentacion = int(input ("Elija la opcion 1 o 2 : ")) contador = 1 while contador <= 10 : if presentacion == 1 : print (contador) if presentacion == 2 : print (contador,"\n") contador = contador + 1
i = 10 print(f"El bucle no ha comenzado. Ahora i vale {i}") for i in [0, 1, 2, 3, 4]: print(f"{i} * {i} = {i ** 2}") print(f"El bucle ha terminado. Ahora i vale {i}")
from math import floor def main(): print(get_fuel_requirement()) def get_fuel_requirement(): total_fuel = 0 file = open("input.txt") for line in file: module_fuel = floor(int(line) / 3) - 2 total_fuel += fuel(module_fuel) return total_fuel def fuel(module): total = module ...
""" Assignment 2 : CSP solution algorithms with Arc Constraint Submitted By : First Name : Amal Majeed Last Name : Mucheth Abdul Majeed Student Number : 200415928 """ import math import random def create_rb(n,p,r,alpha,test=False): """ Function to create the RB instance / cre...
"""************** The Hangman Code *****************""" import emoji import random from words import word_list class Hangman(): #Function that will generate a random word from the wordlist python file def getWord(self): self.randomWord = random.choice(word_list) return self.randomWord ...
def poweroftwo(x): return (x and (not(x & (x - 1)))) n1 = int(input()) if(poweroftwo(n)): print("yes") else: print("no")
import itertools game = [[1, 0, 1], [0, 1, 0], [1, 1, 0]] def init_game(game_map, player=0, row =0, column=0, just_display= False): try: if game_map[row][column] != 0: print('this place is occupied , Try again.....') return game_map, False print(' 0, 1, 2')...
import sys,os import numpy as np from util1 import * from sklearn import linear_model """ Program to demonstrate logistic regression Sample run: $ python logistic_regression_l2.py ../dataset/DS2/data_students/ """ # Penalty, can be 'l1' or 'l2' penalty = 'l2' def logistic_regressor_learn(train_set): """ ...
import sys,os import numpy as np from util3 import * from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from linear_classification import linear_classifier_learn, report_accuracy """ Program to demonstrate feature extraction using LDA ( Linear Discriminant Analysis ) Sample run: $ python featur...
def parImpar(num): if num % 2 == 0: return True else: return False def main(): num = int(input("Ingrese un número entero: ")) print(parImpar(num)) if __name__ == '__main__': main()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import logging class FooError(ValueError): pass def foo(n): print('try...') x = int(n) if x == 0: raise ValueError('invalid value: %s' % n) r = 10 / x print('result:', r) return r def bar(): n = input('请输入除数:') return foo(n) * 2...
age = 30 name = "Stephen" def hello(name="STEPHEN", age=30): return "Hello {} you are {} years old!".format(name, age) sentence = hello() print(sentence)
#!/usr/bin/env python # coding=utf-8 ''' 以人民币的硬币为例,假设硬币数量足够多。要求将一定数额的钱兑换成硬币。要求兑换硬币数量最少。 这是用贪婪算法的典型应用。在本例中用python来实现,主要思想是将货币金额除以某硬币单位,然后去整数,即为该硬币的个数;余数则做为向下循环计算的货币金额。 这个算法的问题在于,得出来的结果不一定是最有结果。比如,硬币单位是[1,4,6],如果将8兑换成硬币,按照硬币数量最少原则,应该兑换成为两个4(单位)的硬币, 但是,按照本算法,得到的结果是一个6单位和两个1单位的硬币。这也是本算法的局限所在。所谓贪婪算法,本质就是只要找出一个结果,不考虑以后会怎么...
# -*- coding: utf-8 -*- # hello.py #name = raw_input('please input your name:\n') #print 'hello', name #print a values a = -4 if a >= 0: print a else: print -a names= ["Chen", "Bob", "Tim"] for name in names: print name sum = 0 for x in [1,2,3,4,5,6,7,8,9,10]: sum = sum + x print sum sum = 0 fo...
#! python3 import sys import os import send2trash from git import Repo USAGE_INFO = ''' Usage: python RmFileType.py <file_name> <file_path> <git_or_cmd> git: use git rm command to delete the file cmd: use windows command to delete the file and send to trash e.g: python RmFileType.py a.exe D:\ cmd''' def deleteFil...
import unittest import blackjack_final class TestPriorityQueue(unittest.TestCase): def setUp(self): # setUp test method allowing us to test other methods with fixed # attributes to eliminate randomness during testing. self.test_game = blackjack_final.Blackjack() def te...
import logging import re from enum import IntEnum from typing import Dict, List, Optional, Set, Tuple, TypedDict SalaryRange = Tuple[float, float] MAX_SALARY_RANGE_FRAC = 1.5 class Period(IntEnum): HOUR = 1 DAY = 8 WEEK = 40 YEAR = 2000 def valid_salary_period( salary: float, period: Perio...
#three games game_one="The Xbox __1__ is a home video game console developed by __2__. Announced on May 21, 2013, it isthe successor to the Xbox __3__ and the __4__ console in the Xbox family. It directly competes with Sony Computer Entertainment's PlayStation 4 and Nintendo's Wii U as part of the eighth generation of...
readMe = open('input.txt').read() print(readMe.split(' ')) value = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] operator = ['+', '-', '*', '/'] identifiers = ['a', 'b', 'c', 'd', 'i'] keyword = ['if', 'else', 'for', 'switch', 'while', 'return', 'byte', 'int', 'float', 'double', 'string', 'char', 'for'] logicalOp...
#!/usr/bin/python #-*-coding:utf8-*- ## I am trying to make the classifier more general purpose ## by reading the data from a file. ## Each line of the file contains tab separated fields. ## The first line of the file describes how those fields (columns) should ## be interpreted. The descriptors in th...
# 此题思路: # 这道题的关键在于找到这个规律,也就是matrix[i][j] = matrix[i + 1][j + 1] 不然做不出来 class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: group = {} for col,row in enumerate(matrix): #print(col,row) for index,value in enumerate(row): #print(index,v...
# Description # Build a function LB2KG which takes a value in pound as input and returns the corresponding value in kilogram. One pound equals to 0.4536 kg. # Examples # LB2KG(1) returns 0.4536 def LB2KG(pound): return pound * 0.4536
# Description # Build a function FizzBuzz which takes a positive integer as input. If the number is divisible by 3, the function returns "Fizz". If the number is divisible by 5, the function returns "Buzz". If the number is divisible by both 3 and 5, the function returns "FizzBuzz". Otherwise, the function returns the ...
# 这道题有两种解法: # 方法1: 利用双重index去扫描index,但是效率比较低 def TargetSum(a,b): for i in range(len(a) - 1): for j in range(1, len(a)): if a[i] + a[j] == b: return [i,j] return - 1 # 方法2:利用dic,key是要寻找的另一半数字,而value就是当前index def TargetSum(a,b): dic = {} for i in range(len(a)): ...
def RankK(a): # dic sort 11 ways: https://pythonguides.com/python-dictionary-sort/ sort_values = sorted(a.items(), key = lambda y:y[1]) #将dic按照value进行排序 # 得到的结果是sort values: [('b', 5), ('a', 7), ('c', 9)] # 而后我们就可以按照双重list的取数方法进行操作了 res = [] for i in range(len(sort_values)): print(i) ...
# Description # Build a function Odd which takes an integer as input and returns a boolin to tell whether the integer is odd or not. # Examples # Odd(3) returns True # Odd(4) returns False def Odd(num): if num % 2 == 1: return True else: return False
class RecentCounter(object): def __init__(self): self.nums = [] #之所以我们这里是要建立一个实例,是因为我们后来每一次哦毒药调用一次ping(),如果没有建立一个实例,那么每一次调用就会忘记我们之前调用的内容 #而这里调用了一个实例,那么就相当于是会记住每一次调用的内容 def ping(self, t): self.nums.append(t) index = -1 for i in range(len(self.nums)): ...
def SortRm(a): s = set(a) #先转变为set,消除重复值 return list(s) #而后将set转变为list # 或者可以就是传统for循环确认重复值与否 def SortRm(a): l = [] for i in a: if i not in l: l.append(i) return l
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def mergeTwoLists(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]: head = ListNode(0) #这个的意思就是建立一个开头为0的ListNode,...
"""Implement an MVC Mastermind game for one player. This file is the model.""" __author__ = "Ron Shafii and Sarah Fellows" class MasterModel: """determines #of guesses, computer generated goal, and history of player's guesses""" def __init__(self): self.guess_num = None #keeps track of the player guess counter ...
def main(): unsorted_list = [6, 17, 9, 34, 4] print("original", unsorted_list) #Make a list sorted_list = selection_sort(unsorted_list) print("selection", sorted_list) sorted_list = bubble_sort(unsorted_list) print("bubble", sorted_list) #define a function within this module called "se...
""" Defines the Creature class, the base class of all living things in our game.""" class Weapon: """Weapon object that creatures can equip""" def __init__(self, atk_value): self.base_damage = atk_value class Creature: #When you forget the () after the class name, you are not creating a new one, you are call...
text = "Это был огромный, в два обхвата дуб, с обломанными ветвями и с обломанной корой" text1 = text.split(',') print(text1)
'''Ex02 - Desenvolva um programa que leia quatro valores pelo teclado e guarde-os em uma tupla. No final, mostre: A) Quantas vezes apareceu o valor 9. B) Em que posição foi digitado o primeiro valor 3''' n1 = int(input('Digite um número: ')) n2 = int(input('Digite outro número: ')) n3 = int(input('Digite mais u...
#Faça um programa, com uma função que necessite de três argumentos, # e que forneça a soma desses três argumentos. def soma3(n1, n2, n3): soma = n1 + n2 + n3 return f'{n1} + {n2} + {n3} = {soma} ' n1 = float(input('Digite o primeiro valor: ')) n2 = float(input('Digite o segundo valor: ')) n3 = float...