text
stringlengths
37
1.41M
arr = [0, 5, 8, 20, 300, 11, 66, 54, 7] # def bubbleSorting(arr): # for j in range(len(arr)-1): # for i in range(len(arr)-1-j): # if arr[i] > arr[i + 1]: # arr[i], arr[i + 1] = arr[i + 1], arr[i] # return arr # print(bubbleSorting(arr)) # # Selection Sorting # def bubble...
class BankAccount(): def __init__(self, accountID, int_rate, balance): self.int_rate = int_rate self.balance = balance self.id = accountID def deposit(self, amount): if self.balance < 35: self.balance = self.balance + amount - 5 return self self.b...
#!/usr/bin/python grades = [100, 100, 90] def print_grades(grades): for grade in grades: print grade def grades_sum(grades): total = 0 for grade in grades: total += grade return total def grades_average(grades): sum_of_grades = grades_sum(grades) average = sum_of_grades /...
#!/usr/bin/python def power(base, exponent): result = base**exponent print "%d with exponent %d is %d" % (base, exponent, result) return result power(5,2) from math import sqrt # import just sqrt from math # from math import * # import all print sqrt(27) def biggest_number(*args): print max(args) ...
#!/usr/bin/python -tt # Copyright 2010 Google Inc. # Licensed under the Apache License, Version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # Google's Python Class # http://code.google.com/edu/languages/google-python-class/ # A. fim_igual # Dada uma lista de strings, retorna o número de strings # com tamanho >= ...
venta = int ( input ( "Ingrese el valor de la venta:" )) iva = venta * 0.19 descuento = venta * 0.05 si venta > = 150000 : print ( "El valor de la venta mas iva y con descuento es de" , ( venta + iva ) - descuento ) otra cosa : print ( "El valor de la venta mas iva es de" , venta + iva )
#!/usr/bin/env python from visual import * import math class Body: dt = 0.05 def __init__(self): #self.left1=box(pos=vector(-1,0,0), # size=(1,3,1),color=color.white) #self.right1=box(pos=vector(1,0,0), # size=(1,3,1),color=color.white) #self.left2=box(pos=vector(-1,3,0), # ...
def main(): a=raw_input() b=raw_input() print(int(a)+int(b)) g=raw_input() c=len(str(g)) print(int(c)) #it prints the sum of the two inputs given from the user and also print the length of the string.
# 关于函数和变量的一些简单练习 # 注意这里,函数内的两个变量都是数,因此没有使用星号 * ,而是字符串时则需要使用 * def cheese_and_crackers(cheese_count, boxes_of_crackers): print("You have %d chesses!" % cheese_count) print("You have %d boxes of crackers!" % boxes_of_crackers) print("Man that's enough for a party!") print("Get a blanket.\n") print("We c...
# 本章节使用 argv 和 raw_input 一起来向用户提一些特别的问题 from sys import argv script, user_name = argv prompt = '> ' print("Hi %s, I'm the %s scripy." % (user_name, script)) print("I'd like to ask you a few questions.") print("Do you like me %s?" % user_name) likes = input(prompt) print("Where do you live %s?" % user_name) lives = i...
# 这一章节其实已经包含在上一章节中了 age = input("How old are you?") height = input("How tall are you?") weight = input("How much do you weight?") print("So, you're %r old, %r tall and %r heavy." % (age, height, weight)) # 加分析题 # 1. 在命令行界面下运行你的程序,然后在命令行输入 pydoc raw_input 看它说了些什么。 # 如果你用的是 Window,那就试一下 python -m pydocraw_input 。 # 2....
# import statements # functions go here # not blank def not_blank(question, error_message): valid = False while not valid: response = input(question) if response != "": return response else: print(error_message) # integer checker low_number = 12 high_numb...
print("********") for i in range(4,12,2): print(i) print("****BACKWARDS****") for i in range(10,-1,-1): print(i) print("***Printing String Characters***") str = "Monkey" for i in range(0, len(str), 1): print(str[i]) print("MOVING ON") print("****PRINT STRING IN REVERSE****") for i in range (len(str)-1,-1,-1)...
#/usr/bin/env python3 import argparse parser = argparse.ArgumentParser() # parser.add_argument("echo",help="echo the string you use here") parser.add_argument("square",help="display a square of a given number",type=int) # parser.add_argument("-v","--verbosity",type=int,choices=[0,1,2], # help="increase output verb...
# TO-DO: complete the helper function below to merge 2 sorted arrays def merge(arrA, arrB): elements = len(arrA) + len(arrB) merged_arr = [0] * elements x = 0 y = 0 for i in range(0, elements): if x >= len(arrA): merged_arr[i] = arrB[y] y += 1 elif y >= len(...
a = [[3,6,3], [3 ,7,4], [2 ,4,6]] for i in range(len(a)): print(a[i][i])
#!/usr/bin/env python # coding: utf-8 # In[4]: INTEGER, PLUS, MINUS, MUL, DIV, EOF = ( 'INTEGER', 'PLUS', 'MINUS', 'MUL', 'DIV', 'EOF' ) #token class class Token(object): def __init__(self, type, value): # token type: INTEGER, PLUS, MINUS, MUL, DIV, or EOF self.type = type # token va...
while True: import time print("Pon '1' para sumar") print("Pon '2' para restar") print("Pon '3' para multiplicar") print("Pon '4' para dividir") print("Pon '5' para exponenciar") print("Pon '6' para sacar el area y la longitud de un circulo") print("Pon '7' para hacerle descuento a un nu...
#Знайти найменше число в списку lst = [2, 3, 45, 4, 64, 56] min_el = lst[0] for i in lst: if i > min_el: min_el=i print(f'min element=', min_el) # Вивести в циклі всі парні числа до 100, крім 6, 8, 86 якщо число 90 зустрінеться в списку то перервати його роботу i = 0 while i < 100: if i % 2 ==...
class LinkedList: def __init__(self, value): self.value = value self.next = None def removeDuplicatesFromLinkedList(linkedList): currentNode = linkedList while currentNode is not None: nextDistinctNode = currentNode.next while nextDistinctNode is not None and nextDistinctNode.value == cur...
def cycleInGraph(edges): numberOfNodes = len(edges) visited = [False for _ in range(numberOfNodes)] currentlyInStack = [False for _ in range(numberOfNodes)] for node in range(numberOfNodes): if visited[node]: continue containsCycle = isNodeInCycle(node, edges, visited, currentlyInStack) if containsCyc...
# -*- coding: utf-8 -*- import os, sqlite3 db_file = os.path.join(os.path.dirname(__file__), 'test.db') if os.path.isfile(db_file): os.remove(db_file) # 初始数据: conn = sqlite3.connect(db_file) cursor = conn.cursor() cursor.execute('create table user(id varchar(20) primary key, name varchar(20), score int)') cursor...
# !/usr/bin/env python3 # -*- coding: utf-8 -*- # A first Python script # import sys # Load a library module # # print(sys.platform) # print(2 ** 100) # Raise 2 to a power # x = 'Spam!' # print(x * 8) # String repetition # 小明的成绩从去年的72分提升到了今年的85分,请计算小明成绩提升的百分点,并用字符串格式化显示出'xx.x%',只保留小数点后1位: # s1 = 72 # s2 = 85 # r =...
from microbit import * import music import radio import random import speech #Instructions: Start with button a pressed, to become master. # Press A on master to sing a note and tell listening slaves about it. # Listening slaves will sing a harmony to a note. # Press A to chan...
f = open("input.txt") lines = f.read().splitlines() passwordcounter = 0 for line in lines: parts = line.split() pos1, pos2 = parts[0].split('-') print(line, pos1, pos2) pos1 = int(pos1) - 1 pos2 = int(pos2) - 1 blob = parts[1][0] print(blob) password = parts[2] ch1 = password[pos1] ...
from turtle import Turtle class Scoreboard(Turtle): def __init__(self): super().__init__() # calls super class' init self.color("white") self.penup() self.hideturtle() # to hide the turtle arrow self.l_score = 0 # score at the beginning self.r_score = 0 # s...
import sqlite3 DB_name = 'database.db' conn = sqlite3.connect(DB_name) conn.cursor().execute(''' CREATE TABLE IF NOT EXISTS Users ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, username TEXT NOT NULL, mail TEXT NOT NULL UNIQUE, address TEXT NOT NULL, mobile INTEGER NOT NULL UNIQUE, pas...
def iterative_len(x): """Return the len of an iterator without using len Example: >>> a = "hola" >>> iterative_len(a) >>> 4 """ return sum(1 for i in x) def recursive_len(x): """Return the len of a string without using len but recursively Example: ...
def count_all(string): str_clean = [l for l in string if l.isalnum()] count_digits = len([l for l in str_clean if l.isdigit()]) count_letters = len(str_clean) - count_digits return {'LETTERS': count_letters, 'DIGITS': count_digits}
def even_odd_transform(lst,repeat): for _ in range(repeat): lst = [v-2 if v % 2 == 0 else v+2 for v in lst] return lst
""" - Connect to the hr.db (stored in supporting-files directory) with sqlite3 - Write a query to display the names (first_name, last_name) and department ID of all employees in departments 3 or 10 in ascending order by department ID. Expected columns: - first_name - last_name - department_id...
from arboles_bin_bus import ArbolBinBus from recorridos import pre_orden class Persona: def __init__(self, nom, edad): self.nombre = nom self.edad = edad def __str__(self): return (str(self.nombre) + ' : ' + str(self.edad)) def __eq__(self, otra_persona): return (isinsta...
class node: def __init__(self, data): self.data = data self.left = None self.right = None import sys def BFS(node, min, max): # Return true if tree is empty if node is None: return True # Check against min and max constraints if node.data < min or node.data > max: return...
# make a list to hold onto our items shopping_list = [] # print out instructions on how to use the app print(""" -------------------------------------------------------------------- The Shopping List Copyright 2016 ExplodingCow This is a simple shopping list intended for educational purposes only. --------------------...
''' Реализовать функцию int_func(), принимающую слово из маленьких латинских букв и возвращающую его же, но с прописной первой буквой. Например, print(int_func(‘text’)) -> Text. Продолжить работу над заданием. В программу должна попадать строка из слов, разделенных пробелом. Каждое слово состоит из латинских букв в ни...
class Enemy: count = 0 def __init__(self, hp, armor, dmg, name, speed): self.hp = hp self.armor = armor self.dmg = dmg self.name = name self.speed = speed def attack(self): print(f'{self.name} атакует с уроном {self.dmg}') def move(self): print(...
import random # создать исключение (обычно помещаются в отдельный файл) # существует иерархия ошибок class Crash(Exception): # ссылаемся на базовый класс Exception def __init__(self, txt): self.txt = txt class Auto: def __init__(self, brand): self.brand = brand def run(self, speed): ...
import cv2 from matplotlib import pyplot as plt #Settings SHOW_PLT = True #show with plt or just cv2 (better for big images) COLOR_DISPLAY = True #Display keypoints over color image or grayscale one, (easier to see colorful keypoints) SAVE_IMAGE = True #save the image? INPUT_MODE = True #if true, there will be ...
import random from hangman_art import stages,logo from hangman_list import lists print(logo) print("CHÀO MỪNG BẠN ĐẾN VỚI HANGMAN!!!!") key_word = random.choice(lists) a = len(key_word) mang = len(stages) - 1 key_pass = [] for _ in range(a): key_pass += "_" print(" ".join(key_pass)) print(f"Từ này có {len(key_pass)...
from turtle import Turtle, Screen screen = Screen() class YourTurtle(Turtle): def __init__(self): super().__init__() self.penup() self.shape("turtle") self.color("green") self.setheading(90) self.goto(0, -280) self.pen = Turtle() self.lever = 1 ...
# 1 def biggie(arr): for count in range(len(arr)): if arr[count] >0: arr[count] = 'Big' return arr print(biggie([-1,3,5,-5])) # 2 def positive(arr): total = 0 for count in range(len(arr)): if arr[count] > 0: total += 1 arr[len(arr)-1] = total return arr...
# basic stuff a = 12 b = 3 print(a + b) print(a - b) print(a * b) print(a / b) print(a // b) print(a % b) print() # basic python for loop for i in range(1, a // b): print(i) # same output as for loop i = 1 print(i) i = 2 print(i) i = 3 print(i) # integer division, customers want whole buns, not part of a bun,...
computer_parts = ["computer", "monitor", "keyboard", "mouse", "mouse pad"] # for part in computer_parts: # print(part) print(computer_parts) print(computer_parts[3:]) computer_parts[3:] = ["trackball"] print(computer_parts) # # print(compute...
class Animal(): def __init__(self): print("Animal Created") def whoami(self): print("I am an animal") def eat(self): print("I am eating") # myanimal = Animal() # myanimal.eat() # myanimal.whoami() # class Dog(Animal): # def __init__(self): # Animal.__init__(self) # ...
''' python自动化刷抖音 ''' from appium import webdriver import time server = "http://localhost:4723/wd/hub" param = { "platformVersion": "7.1.2", "platformName": "Android", "appPackage": "com.ss.android.ugc.aweme", "appActivity": "com.ss.android.ugc.aweme.splash.SplashActivity", "deviceName": "127.0.0.1:62001" ...
import os os.system('cls') tuple_1 = ('John', 'Bob', 'Mary') print(tuple_1[0]) tuple_2 = ("Sina", ) # tuple with single entry get a coma at the end, otherwise it's a string tuple_3 = tuple_1 + tuple_2 print(tuple_3) tuple_4 = tuple_1[0:2] # range: from 0 up until but not including 2 print(tuple_4) tuple_5 = tupl...
import os os.system('cls') my_name = "elodia" first_names = ["john", "bob", "mary", my_name] print(first_names[2]) #access index 2 of first_names num = [1,2,3,4] numbers = ['a', 'b', num] print(numbers[2][3]) #access index 3 of index 2 (wich is a list on ints own) of numbers first_names[0] = "Tina" #replacing entr...
# random password generator import random def get_char(list, num): character=[] for i in range(num): character.append(random.choice(list)) return character while True: num_char= int(input("Total number of int in password : ")) num_Upper=int(input("number of uppercharacter in password : ")) ...
#charity money class charity: def __init__(self,balance=100000): self.balance= balance def save_fund(self,amount): self.balance+= amount def spend_funds(self,amount): self.balance-=amount def investment(self, investment_return): self.balance*=1+investment_return def get_balance(sel...
# PRODUCT PRICE DISCOUNT def get_price(product, quantity): subtotal = price_diction[product] * quantity return subtotal buying_diction={"biscuits":2 , "chicken":3, "fruits":5} price_diction={"biscuits":3 , "chicken":15.5, "fruits":10} bill_price=0 membership = 'golden' for key ,value in buying_diction...
def validate_puzzle(arr): if len(arr) != 9: return False for i in range(9): if len(arr[i]) != 9: return False return True def print_sudoku(arr): for i in range(9): for j in range(9): print(arr[i][j], end=" ") print('\n') def find_next_void(arr,...
# -*- coding: utf-8 -*- """ Éditeur de Spyder Ceci est un script temporaire. """ couleurs = ['bleu', 'vert', 'rose', 'orange'] print (couleurs) couleurs[1]=15 print (couleurs) x = 10 print("avant if") if x>0: print("dans if") print("après if") #exercices 6.3 def F_to_C(Tf): """convertit une temperature de...
# 로또 생성 프로그램 import random cnt = int(input("로또를 몇 세트 자동생성 할까요? ")) for i in range(1, cnt+1) : numbers = [] while len(numbers) < 6 : rotto = random.randint(1, 45) if rotto not in numbers : numbers.append(rotto) numbers.sort() print(f"{i}번째 세트", end=...
import pandas as pd import csv import statistics df= pd.read_csv("data.csv") heightList= df["Height(Inches)"].to_list() weightList= df["Weight(Pounds)"].to_list() heightMean= statistics.mean(heightList) weightMean= statistics.mean(weightList) heightMedian= statistics.median(heightList) weightMedian= statistics.median(...
# socket_echo_server.py import socket import sys # Create a TCP/IP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) listaDeEsperaPassageiro = [] listaDeEsperaCarga = [] def decisao(message): message = message.split(',') print(message) if(message[0].upper()=='1'.upper()): # Passageiro listaDeEspe...
name = input('What is your name? ') print(name + ' SUCKS!!!!') color = input('what is your favorite? ') print(color + ' SUCKS!!!!') subject = input('What is your favorite subject? ') print(subject + ' SUCKS!!!!!!') animal = input('What is your favorite animal? ') print(animal + ' SUCK!!!!')
#A comment #anything after the pound sign is ignored by python. print "I could have code like this" #and here's a comment #comments can be used to disable a piece of code: #print "This won't run." print "This will run."
animals = ['bear', 'python', 'peacock', 'kangaroo', 'whale', 'platypus'] """ print "The animal at 1: " + animals[1] print "The third animal: " + animals[2] print "The first animal: " + animals[0] print "The animal at 3: " + animals[3] print "The fifth animal: " + animals[4] print "The animal at 2: " + animals[2] ...
from bs4 import BeautifulSoup import requests import pandas as pd def init_browser(): # @NOTE: Replace the path with your actual path to the chromedriver executable_path = {"executable_path": ""} return Browser("chrome", **executable_path, headless=False) def mars_scraper: url = "https://mars.nas...
num = int(input()) hrs = int(input()) val = float(input()) salary = val * hrs print("NUMBER = %d\nSALARY = U$ %.2f" %(num,salary))
import MapReduce import sys """ Relational Join Example in the Simple Python MapReduce Framework """ mr = MapReduce.MapReduce() # ============================= # Do not modify above this line def mapper(record): # key: document identifier # value: document contents key = record[1] rectag= record[0] ...
# Subsets # Given a set of distinct integers, nums, return all possible subsets (the power set). # Note: The solution set must not contain duplicate subsets. # Example: # Input: nums = [1,2,3] # Output: # [ # [3], # [1], # [2], # [1,2,3], # [1,3], # [2,3], # [1,2], # [] # ] # ==========================...
# Sort List # Sort a linked list in O(n log n) time using constant space complexity. # Example 1: # Input: 4->2->1->3 # Output: 1->2->3->4 # Example 2: # Input: -1->5->3->4->0 # Output: -1->0->3->4->5 # ====================================================================================== # Algorithm: # Merge sort # ...
# Pascal's Triangle # Given a non-negative integer numRows, generate the first numRows of Pascal's triangle. # In Pascal's triangle, each number is the sum of the two numbers directly above it. # Example: # Input: 5 # Output: # [ # [1], # [1,1], # [1,2,1], # [1,3,3,1], # [1,4,6,4,1] # ] # ==============...
# Delete Linked List # Example: # Input: 1->2->3->4->5->NULL # Output: None # ====================================================================================== # Algorithm: # TC: # SC: # Description: # ======================================================================================== class SllNode: d...
# Palindromic Substrings # Given a string, your task is to count how many palindromic substrings in this string. # The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters. # Example 1: # Input: "abc" # Output: 3 # Explanation: Three palindromi...
# Best Time to Buy and Sell Stock III # Say you have an array for which the ith element is the price of a given stock on day i. # Design an algorithm to find the maximum profit. # You may complete at most two transactions. # Note: You may not engage in multiple transactions at the same time # (i.e., you must sell the s...
# Remove duplicates from sorted array II # Given a sorted array nums, remove the duplicates in-place such that duplicates appeared # at most twice and return the new length. # Do not allocate extra space for another array, you must do this by modifying the input array # in-place with O(1) extra memory. # Example 1: # ...
# Path Sum # Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that # adding up all the values along the path equals the given sum. # Note: A leaf is a node with no children. # Example: # Given the below binary tree and sum = 22, # 5 # / \ # 4 8 # / / \ # 11 13...
# Given a string find longest palindromic subsequence in this string. # Example 1: # Input: # S = 'abcdca' # Output: 5 # Explanation: acdca # ======================================================================================== # Algorithm: # Similar to substring except use the table to keep track of longest length...
# Minimum Depth of Binary Tree # Given a binary tree, find its minimum depth. # The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. # Note: A leaf is a node with no children. # Example: # Given binary tree [3,9,20,null,null,15,7], # # 3 # / \ # 9 ...
# Binary Tree Level Order Traversal II # Given a binary tree, return the bottom-up level order traversal of its nodes' values. # (ie, from left to right, level by level from leaf to root). # For example: # Given binary tree [3,9,20,null,null,15,7], # 3 # / \ # 9 20 # / \ # 15 7 # return its bottom-...
# Remove Duplicates from Sorted List II # Given a sorted linked list, delete all nodes that have duplicate numbers, # leaving only distinct numbers from the original list. # Return the linked list sorted as well. # Example 1: # Input: 1->2->3->3->4->4->5 # Output: 1->2->5 # Example 2: # Input: 1->1->1->2->3 # Output:...
# Delete Node in a Linked List # Write a function to delete a node (except the tail) in a singly linked list, given only access to that node. # Example 1: # Input: head = [4,5,1,9], node = 5 # Output: [4,1,9] # Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after cal...
# Find All Anagrams in a String # Given a string s and a non-empty string p, find all the start indices of p's anagrams in s. # Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100. # The order of output does not matter. # Example 1: # Input: # s: "cb...
# Reverse Linked List # Reverse a singly linked list. # Example: # Input: 1->2->3->4->5->NULL # Output: 5->4->3->2->1->NULL # Follow up: # A linked list can be reversed either iteratively or recursively. Could you implement both? # ======================================================================================...
# Combination Sun II # Given a collection of candidate numbers (candidates) and a target number (target), # find all unique combinations in candidates where the candidate numbers sums to target. # Each number in candidates may only be used once in the combination. # Note: # All numbers (including target) will be posit...
# ============================================ # ; Title: Exercise 8.3–Python in Action # ; Author: Peter Itskovich # ; Date: 25 Aug 2020 # ; Modified By: Becca Buechle # ; Description: Calc with Python # ;=========================================== add(a,b): return a + b def subtract(a,b): return a - b d...
# -*- coding: utf-8 -*- """ Created on Thu Sep 15 19:45:30 2016 @author: Jian Gao Group c """ ##Prof G - This does not work. Part of the reason is that the reason is that the ##Prof G - "is_palindrome" function calls a function called "reverse", which is ##Prof G - undefined. # Question 1 def palindrome(string): ...
def missing_char(str, n): if n == str[-1]: return str.split(0, n - 1) return print(missing_char("kitten", 4)) print()
# O(n) time & space, n is # of items in merged list (Interview Cake) def merge_lists(my_list, alices_list): merged_length = len(my_list) + len(alices_list) #merged_list = [None] * merged_length merged_list = [] idx = 0 my_p = 0 a_p = 0 while idx < merged_length: if my_...
""" Input: array of three or more ints Output: sorted array of three largest nums, ascending Consideration: cannot use the native sort method Consideration: should return duplicates if there are any Example: Input: [141, 1, 17, -7, -17, -27, 18, 541, 8, 7, 7] Output: [18, 141, 541] """ # O(n) time | O(1) space def la...
''' Input: list of strings (3 nums) Input: len(list) = # of scenarios Input: [budget, cost of containers, trade-in price] PRINT RESULTS ON EACH LINE; NO RETURN VALUE ''' def max_containers(scenarios): for scenario in scenarios: scenario_list = scenario.split(' ') budget = int(scenario_list[0])...
input_file = open("day3", "r") content = input_file.read() content_list = content.split("\n") def count_trees(): counter = 0 for i, line in enumerate(content_list): string = line.strip() * ((len(content_list)//len(line)+1)*3) if string[3*i] == '#': counter += 1 print(counter) ...
a=input("masukkan Nilai a : ") b=input("masukkan Nilai b : ") print("variable a = ", a) print("variable b = ", b) print("Hasil penggabungan {1}&{0}=%d".format(a,b) %(a+b)) # Konversi nilai Variable a=int(255) b=int(255) print("Hasil penjumlahan {1}+{0}=%d".format(a,b) %(a+b)) print("Hasil pembagian {1}/{0}=%...
import numpy as np def parse_to_matrix(filepath, separator = " ", dtype = np.int32): """ By: Jan Reads a textfile to a matrix. Assumptions:Every line corresponds to one line of the matrix Every line has the same number of items A space character ends every line separator is the sign with which weights are sepa...
import time import pandas as pd import numpy as np # dictionary for acessing file name CITY_DATA = {'chicago': 'chicago.csv', 'new york city' : 'new_york_city.csv', 'washington': 'washington.csv'} # month and week dictionaries hold month and week keys for accesing dictionary values month_ind...
import sys def showSum(number): sum = 0 for i in range(1, number + 1): sum += i print(f'{int(sum)}') number = int(sys.stdin.readline()) showSum(number)
import sys def printUntilNumber(count): for i in range(1, count + 1): print(f'{i}') count = int(sys.stdin.readline()) printUntilNumber(count)
#!/usr/bin/env python # -*- coding:utf-8 -*- # @Time : 2021/6/30 16:10 # @Author : dxc # @File : change_money.py """ 面额问题 有 100 50 20 10 5 2 1 372 找最少张 贪心算法 """ class ChangeMoney: """ 面额问题 """ def __init__(self): self.amount = [100, 50, 20, 10, 5, 2, 1] def cal_num(self, money): ...
#!/usr/bin/env python # -*- coding:utf-8 -*- # @Time : 2021/6/30 17:49 # @Author : dxc # @File : activity_select.py # 活动时间 activities = [(1, 4), (3, 5), (0, 6), (5, 7), (3, 9), (5, 9), (6, 10), (8, 11), (8, 12), (2, 14), (12, 16)] # 保证活动按结束时间排序 activities.sort(key=lambda x: x[1]) def activities_select(a): """ ...
print("<--------------------------->") print("<---------CONTACTOS--------->") print("<--------------------------->") #BUCLE_WHILE-PARA_EL_MENU_DE_CONTACTOS opcion = 0 while opcion != 5: """OPCIONES A ELEGIR""" print("1.Crear contacto en la agenda") print("2.Listado de contactos") print("3.B...
import random #随机数 date = int(random.randint(0, 10)) #初始金币 money = 2000 #一局游戏玩的次数 i = 0 count = 1 while True: if i <= 10: i = i + 1 count = 10 - i num = input("输入数字:\n") if num.isdigit(): num = int(num) if num < date: money = money - 200 ...
from algorithms import selection_sort import random l = list(map(lambda x: random.randint(10,99), range(12))) print(l) selection_sort(l) print(l) words = ['y', 'n', 'hello', 'goodbye', 'please', 'thanks'] selection_sort(words) print(words)
directions = input().split(",") def sign(a): if a > 0: return 1 if a < 0: return -1 return 0 x = 0 y = 0 for direction in directions: if direction == "n": y += 1 if direction == "ne": x += 1 y += 0.5 if direction == "se": x += 1 y -= 0...
stream = input() score = 0 ignore = False garbage = False opened = 0 for c in stream: if not ignore: if not garbage: if c == '{': opened += 1 elif c == '}': score += opened opened -= 1 elif c == '<': garbag...
import numpy as np # initial weight and hyper parameters w = 0.0 learning_rate = 0.01 num_epoch = 100 # Training Data & Test data x_data = [1.0, 2.0, 3.0] y_data = [2.0, 4.0, 6.0] x_test = [4.0] y_test = [8.0] # Initialize the weight, w def init_weight(val = 1.0): global w w = val # Our model for the forwa...
""" A non-empty array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired. For example, in array A such that: A[0] = 9 A[1] = 3 A[2] = 9 A[3] = 3 ...
""" An array A consisting of N integers is given. The dominator of array A is the value that occurs in more than half of the elements of A. For example, consider array A such that A[0] = 3 A[1] = 4 A[2] = 3 A[3] = 2 A[4] = 3 A[5] = -1 A[6] = 3 A[7] = 3 The dominator of A is 3 because it occurs in 5...
class Solution1: def lengthOfLastWord(self, s: str) -> int: string = s.split() return len(string[-1]) if string else 0 class Solution2: def lengthOfLastWord(self, s: str) -> int: if not s and len(s) == 0: return 0 count = 0 for i in s[::-1]: if i ...