text
stringlengths
37
1.41M
C1, C2, C3 = map(int, input().split()) if(C1==C2 or C1==C3): print("S") elif(C2==C3 or C2==C1): print("S") elif(C3==C2 or C3==C1): print("S") elif(C1+C2==C3): print("S") elif(C2+C3==C1): print("S") elif(C1+C3==C2): print("S") else: print("N")
#from collections import Counter #c = Counter() def fibonacci(n): contador = [0] * n def fib(n): contador[n] += 1 #c[n] += 1 if n == 0: return 0 elif n == 1: return 1 return fib(n-1) + fib(n-2) print(contador) fibonacci(3)
lista = [] for i in range(6): lista.append(float(input())) contador = 0 pos = [] soma = 0 for i in range(6): if(lista[i]>0): pos.append([lista[i]]) soma += lista[i] contador += 1 for i in pos: media = soma/len(pos) print("%d valores positivos" %contador) print("%.1f" %media)
valor_1 = int(input('Informe o 1º valor: ')) valor_2 = int(input('Informe o 2º valor: ')) soma = valor_1 + valor_2 subtracao = valor_1 - valor_2 multiplicacao = valor_1 * valor_2 print(f'A soma entre {valor_1} e {valor_2} é = {soma}') print(f'A subtracao entre {valor_1} e {valor_2} é = {subtracao}') print(f'A multipl...
from tkinter import * root = Tk() root.title("Nado GUI") root.geometry("640x480") frame = Frame(root,relief="solid") frame.pack() scrollbar = Scrollbar(frame) scrollbar.pack(side="right", fill="y") # 위 아래로 채움 listbox = Listbox(frame, selectmode="single", height=10, yscrollcommand=scrollbar.set) # listbox 와 scroll...
while True: print("Enter an operator") print("================Options:==================") print("Enter '+' to add two numbers") print("Enter '-' to subtract two numbers") print("Enter '*' to multiply two numbers") print("Enter '/' to divide two numbers") print("Enter 'quit' t...
list_month=['jan','feb','mar','apr','may','jun','july','aug','sep','oct','nov','dec'] month=raw_input("enter number :") month=int(month) end=month*3 start=end-3 print list_month[start:end]
# A Tuple is a collection which is ordered and unchangeable. Allows duplicate members. # Create tuple fruits = ('Apples', 'Oranges', "Grapes") #fruits2 = tuple(('Apples', 'Oranges', 'Grapes')) # Single value need trailing coma fruits2 = ('Apples',) # Get value print(fruits[1]) # Cant't change value #fruits[0] = '...
car = "sUbaru" print("Is car == \"subaru\"? I predict True.") print(car.lower() == "subaru") print("\nIs car == \"subaru\"? I predict False.") print(car == "audi") price = 20999 print("\nIs price == \"20999\"? I predict True.") print(price == 20999) print("\nIs price == \"20999\"? I predict False.") print(price == 2...
from datetime import datetime def count_words(filename): """Подсчет слов в файле""" try: with open(filename, encoding='utf-8') as f: contents = f.read() except FileNotFoundError: with open('missing_file.txt', 'a', encoding='utf-8') as mf: dt = datetime.today() ...
def city_country(city, country): cc = f"{city}, {country} " return cc in_city = input("Введите название города: ") in_country = input("Введите название страны: ") formated_cc = city_country(in_city, in_country) print(formated_cc)
T = int(input()) def binary_search(s, e, num): global N_list global result if N_list[s] > num: return None elif N_list[s] == num: for test_case in range(T): N, M = map(int, input().split()) N_list = list(map(int, input().split())) N_list.sort() M_list = list(map(i...
T = int(input()) def ternary_tracking(idx, change_num): global ternary_num global ternary_list global ternary_sum_list if change_num > 1: return None if idx == len(ternary_num) and change_num != 1: return None if idx == len(ternary_num): num = 0 pivot = 0 ...
# fibo.py def fibo(n): if n <= 2: return 1 else: return fibo(n - 1) + fibo(n - 2) def main(): print("This program returns the nth Fibonacci number.") n = int(input("Enter n: ")) print("The Fibonacci number at position", n, "is", fibo(n)) if __name__ == '__main__': main()
# month.py def main(): months = "JanFebMarAprMayJunJulAugSepOctNovDec" n = int(input("Enter a month number (1-12): ")) pos = (n - 1) * 3 monthAbbrev = months[pos:pos + 3] print("The month abbreviation is", monthAbbrev + ".") main()
# sums.py def sum_n(n): count = 0 for i in range(1, n + 1): count += i return count def sum_n_cubes(n): count = 0 for i in range(1, n + 1): count += (i * i * i) return count def main(): print("This program returns sums: of the first n natural numbers and of " ...
class LList: ## Start: Nested Node class, not visible from outside ---------------------- class _Node: __slots__ = '_element', '_next' # Optional: assign memory space for the member variables, faster! def __init__(self): self._element = None self._next = None d...
# Python script QBlix Data Analyst Code - May 2021 # This script transforms a txt in a json format import json from tkinter import Tk from tkinter.filedialog import askopenfilename from datetime import datetime as dt Tk().withdraw() filename = askopenfilename() # show an "Open" dialog box and return the path to the s...
#!/usr/bin/env python """Determining the maximum of a list of numerical values by using reduce """ f = lambda a,b: a if (a > b) else b print(reduce(f, [47,11,42,102,13])) # output: 102 # calculating the sum of numbers from 1 to 100 print(reduce(lambda x, y: x+y, range(1,101))) # output: 5050
char=input() var=char.lower() if var=='a'or var=='e'or var=='i'or var=='o'or var=='u': print("VOWEL") else: print("CONSONANT")
input1=input() count=0 for i in input1: if i.isalpha(): count+=1 print(count)
num1=int(input()) num2=int(input()) num3=int(input()) if num1>num2 and num1>num3: print(("Big is %d")%num1) elif num2>num3: print(("Big is %d")%num2) else: print(("Big is %d")%num3)
# U04_Ex07_CircleIntersection.py.py # # Author: Michael Hu # Course: Coding for OOP # Section: A2 # Date: 06 Nov 2018 # IDE: PyCharm # # Assignment Info # Exercise: 07 # Soource: Python Programming # Chapter: 04 # # Program Description # This program will compute the intersection of a circle, and the screen will displa...
# U04_Ex11_5ClickHouse.py.py # # Author: Michael Hu # Course: Coding for OOP # Section: A2 # Date: 06 Nov 2018 # IDE: PyCharm # # Assignment Info # Exercise: 11 # Soource: Python Programming # Chapter: 04 # # Program Description # The program allows the user to click five times, which will draw a house with a door, win...
# U03_Ex11_Natural#s.PY.py # # Author: Michael Hu # Course: Coding for OOP # Section: A2 # Date: 03 Oct 2018 # IDE: PyCharm # # Assignment Info # Exercise: 11 # Soource: Python Programming # Chapter: 3 # # Program Description # Calculate the sum of natural numbers based off user input for the amount # # Algorithm (pseu...
# U07_Ex16_ArcheryScore.py.py # # Author: Michael Hu # Course: Coding for OOP # Section: A3 # Date: 01 Mar 2019 # IDE: #{PRODUCT_NAME} # # Assignement Info # Exercise: 16 # Source: Python Programming # Chapter: 07 # # Program Description # This program draws an archery target, accepts five clicks as the arrow ...
# U03_Ex16_Fibonacci.PY.py # # Author: Michael Hu # Course: Coding for OOP # Section: A2 # Date: 03 Oct 2018 # IDE: PyCharm # # Assignment Info # Exercise: 16 # Soource: Python Programming # Chapter: 3 # # Program Description # Output the number in the Fibonacci sequence that is selected by the user # # Algorithm (pseu...
# Finance8.py # # Author: Michael Hu # Course: Coding for OOP # Section: A2 # Date: 05 Sep 2018 # IDE: PyCharm # # Assignment Info # Exercise: 8 # Soource: Python Programming # Chapter: 2 # # Program Description # Compounds the rate of an investment per year # # Algorithm (pseudocode) # Print Introduction # Get input f...
# U06_Ex06_AOT.py.py # # Author: Michael Hu # Course: Coding for OOP # Section: A3 # Date: 29 Jan 2019 # IDE: #{PRODUCT_NAME} # # Assignement Info # Exercise: 06 # Source: Python Programming # Chapter: 06 # # Program Description # This program calculates the area of a triangle from user input of it's three sid...
# -*- coding: utf-8 -*- """ Created on Sat Feb 09 17:11:57 2013 @author: Anirudh """ import urllib2 access_key = "ZFFYQ5I5" def getBookDataXML(ISBN, accessKey): ''' Returns xml data for a book from www.isbndb.com. Inputs - ISBN number of book, access_key - provided from isbndb.com after account is...
import math import argparse import random import time from parser import parse_input_walk_sat def walkSAT(model, clauses,var_to_clauses, p_random_step): """ Performs stochastic local search to determine whether a file in cnf format is SAT or UNSAT. Input: model - a dictionary of variables to booleans ...
#Output functions for degrees of truth #Matheus da Rosa #22/09/2011 def input_small(val): if val<100: ret = 1 elif val>=100 and val<=200: ret = 1-((val-100)/100.0) elif val>200: ret = 0 return ret def input_medium(val): if val<100: ret = 0 elif val>=100 and val<...
########################################### # Affine Cipher using python # Nishant Tomar # 2020PMD4210 ########################################### # Keys to encrypt and decrypt the message key1 = 17 key2 = 20 # To take plain-text input from the user (Message to be encrypted) def take_input(): print("\n\n########...
#!/usr/bin/env python3 import re # current_dir is N S E or W # letter is L or R def rotate_dir(current_dir, letter) -> str: all_directions = ["N", "E", "S", "W"] i = all_directions.index(current_dir) if letter == "L": i -= 1 if i == -1: i = len(all_directions) - 1 elif letter == "R": i += 1 if i == len...
# searchProblem.py - representations of search problems # AIFCA Python3 code Version 0.7.7 Documentation at http://aipython.org # Artificial Intelligence: Foundations of Computational Agents # http://artint.info # Copyright David L Poole and Alan K Mackworth 2017. # This work is licensed under a Creative Commons # Att...
list = (range(7)) symm = 0 for i in list: if list[i] % 2 != 0: symm = symm + list[i] result = symm * list[-1] print ("The result of multiplying the odd elements of the list and the last = {}".format(result))
print("Please enter your first name?") first_name = input() print("Please enter your last name?") last_name = input() print("Please enter your age?") age = int(input()) print("\nName:") print("----") print(first_name, last_name) print("\nVoting eligible:") print("----") print(age >= 18)
# /learning/environment.py # 투자할 종목의 차트 데이터를 관리하는 모듈 class Environment: PRICE_IDX = 4 # 종가의 위치. 5번째 열에 있어서. def __init__(self, chart_data=None): self.chart_data = chart_data # 주식 종목의 차트 데이터 self.observation = None # 현재 관측치 self.idx = -1 ...
import re import html # The regular string.split() only takes a max number of splits, # but it won't unpack if there aren't enough values. # This function ensures that we always get the wanted # number of returned values, even if the string doesn't include # as many splits values as we want, simply by filling in extra...
"""" Find all the pairs of two integers in an unsorted array that sum up to a given S. For example, if the array is [3, 5, 2, -4, 8, 11] and the sum is 7, your program should return [[11, -4], [2, 5]] because 11 + -4 = 7 and 2 + 5 = 7 """ # looking for complements # integers can be pos or neg # expected output is two ...
def containsDuplicate(self, nums: List[int]) -> bool: # uses set to store elements dups = set() for num in nums: if num in dups: return True else: dups.add(num)
def extract_characters(shakespeare="shakespeare", combine=True): file = open("data/shakespeare.txt", "r") if shakespeare else open("data/spenser.txt", "r") if shakespeare == "shakespeare": poetry_list_by_line = shakespeare_extract_poetry_list(file) else: poetry_list_by_line = spencer_extrac...
from collections import OrderedDict class GenericTreeNode(OrderedDict): def __init__(self, *args, **kwargs): OrderedDict.__init__(self, *args, **kwargs) def insert(self, key, val=None): OrderedDict.__setitem__(self, key, val) def delete(self, key): OrderedDict.popitem(self, key) class GenericTree(object): ...
import random import unittest class TreeNode: def __init__(self, key, left=None, right=None): self.key = key self.left = left self.right = right def insert(root, x): if root is None: return TreeNode(x) new_root = TreeNode(root.key) if root.key <= x: new_root.l...
# -*- coding: utf-8 -*- """ Created on Wed Jun 30 07:35:33 2021 @author: Cleme """ #! python3 # table_printer.py - Takes a list of strings and displays it as a neat table table_data = [['apples', 'oranges', 'cherries', 'banana'], ['Alice', 'Bob', 'Carol', 'David'], ['dogs', 'cats', 'moose', 'goose']] ...
def letra_i(n): varFinal = "*"*n varFinal += "\n" for i in range(1 , n-1): linea = "" for j in range(1,n): #Si es par, debo dejarlo en posicion n/2 if(n%2 == 0): if(n//2 == j): linea += "*" else: ...
def letra_x(n): varFinal = "" rango = n-1 for i in range(0 , n): lineaVertical = "" for j in range(0 , n): if(i==j): lineaVertical += "*" elif((i+j)== rango): lineaVertical += "*" else: lineaVertical += " " ...
# การสร้างข้อมูลแบบ List number = [5, 6, 13, 24, 7, 16] name = ['John', 'Jane', 'jum', 'Wasan'] mix = [10, 25.75, True, 'Samit'] # การเข้าถึงสมาชิกใน List print(number[1]) print(number[3]) print(mix[2], mix[3]) # การนับสมาชิก print("สมาชิกทั้งหมดของ number=", len(number)) # การสร้าง list แบบว่าง data = [] # การเพิ...
class robot: def __init__(self,x, y, world_map, goal): """ Input: x, y - Starting coordinates of the robot world_map - Map of the obstacle course as a 2d array 'o' - Water 'x' - Obstacle 'R', 'W', 'G' - Gate (red, white, and green) ...
def factorial(n): if n < 1: return 1 else: returnNumber = n * factorial(n - 1) return returnNumber def sum_digits(n): s = 0 while n: s += n % 10 n /= 10 return s print(sum_digits(factorial(100)))
''' #Data structures #Data types #int #str #float #boolen #collection datatype #List #tuple (Immutable) #dictionary #set #frozon set (Immutable) #None #Range ''' #Data types a = 2 b = 'str' c = 10.3 d = True print(type(a),type(b),type(c),type(d)) #List x = [2, 4, 5, 6, 7, 8, ...
filename = input("Input the Filename: ") f_extns = filename.split(".") if f_extns[-1]=="py": print("The extension of the file is: 'python'") elif f_extns[-1]=="java": print("The extension of the file is: 'Java'") elif f_extns[-1]=="cpp": print("The extension of the file is: 'C++'")
import random import string import pprint_jhs def getRandomName(length = 4, exclude_list = []): # return a random text string of length `length` thisName = ''.join([random.choice(string.ascii_lowercase) for _ in range(length)]) while thisName in exclude_list: thisName = ''.join([random.choice(strin...
''' Assignment 32: Lists – Hands - on - Practice Objective: Given a List of elements representing a computational problem, be able to access elements in different ways using an object oriented language (Python) using an IDE Problem Description: Write a Python program to generate first ‘n’ Fibonacci numbers. Store the ...
# -*- coding: utf-8 -*- """ Created on Tue Dec 11 09:39:23 2018 @author: Aman Zadafiya """ def compare(phoenix_to_slc,phoenix_to_tamba): if phoenix_to_slc>phoenix_to_tamba: print("SLC is far from phoenix compare to tamba,florida") elif phoenix_to_slc<phoenix_to_tamba: print("Tamba,florida is fa...
''' Assignment 33: Lists – Hands - on - Practice developer:Aman Zadafiya date & time: 11/12/2018 12:35 PM ''' currancy=[4,3,2,5,6,4,7,8] for i in range(0,len(currancy)): for j in range(0,len(currancy)-1): if(currancy[j]<currancy[j+1]): currancy[j],currancy[j+1]=currancy[j+1],currancy[j] print(currancy)
import pandas as pd import streamlit as st import altair as alt from PIL import Image # page title image = Image.open('dna-logo.jpg') st.image(image, use_column_width=True) st.write(""" #DNA Count web app this app count nucleotide composition from a given DNA *** """) # input text box # hedear st.header("enter y...
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data learning_rate = 0.1 batch_size = 100 mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) X = tf.placeholder(tf.float32, [None, 784]) Y = tf.placeholder(tf.float32, [None, 10]) W = tf.Variable(tf.zeros([784, 10])) b = tf.Va...
from linked_list import LinkedList if __name__=="__main__": mylist=LinkedList() mylist.insert(4) mylist.insert(5) mylist.print_list() #mylist.recursive_reverse(mylist.head) print "\n" mylist.iterative_reverse() mylist.print_list()
import random import string from game.style import bcolors class Code: """Keep track of players guesses, codes, and info. Attributes: self._items (dict): contains player information. """ def __init__(self): """The class constructor. Args: self (Code):...
def reverse_binary(num): binary = bin(num) bin_string = str(binary) bin_string = bin_string[::-1] bin_string = bin_string[:-2] res = int(bin_string, base=2) res = int(res) print(res) num = input() reverse_binary(int(num))
import sys input = sys.stdin.readline cnt = int(input()) for _ in range(cnt): sentence = input() stack = [] for word in sentence: if word == ' ' or word == '\n': print(''.join(stack[::-1]), end='') stack.clear() print(word, end='') else: stack...
#!/usr/bin/env python #Nicole Guymer and Niklas Delboi #ME 599: Solid Modeling #Homework 3 #2/10/2019 """Homework Problem 1: Wright a function that returns 'inside' or 'outside' for whether a point is inside or outside a polygon. This polygon can be simple or complex. 2D problem. """ """The algorithm is fr...
#-*- encoding: utf-8 -*- """ Jogo FizzBuzz Quando o n£mero for multiplo de 3, fala fizz; Quando o n£mero for multiplo de 5, fala buzz; Quando o n£mero for multiplo de 3 e 5, fala fizzbuzz; Para os demais diga o pr¢prio n£mero; """ from functools import partial multiple_of = lambda base, num: num % base == 0 multi...
#This comes from the recomendation found here: https://github.com/karan/Projects #This is the description. Create an application which manages an inventory of products. #Create a product class which has a price, id, and quantity on hand. #Then create an inventory class which keeps track of various products and can su...
#!/usr/bin/env python3 """Download jpg/png images from Imgur that match a user's search term(s).""" import os import requests import bs4 from pathlib import Path def download_image(extension): """Search for and download all images of the argument type from Imgur.""" home = str(Path.home()) url = f'http:/...
from tkinter import * import tkinter as tk import sys import os #start the tkinter root = tk.Tk() root.title("Gpa Calculator") #Lists grades = [] # Define command def calculate(): global grade global gpa grade = e1.get() grade = e2.get() grade = e3.get() grade = e4.get() grade = e5.get...
import doctest from fizz_buzz_basic import fizz_buzz def fizz_buzz_state(num): """ For numbers between 1 and num, set the state of the number to: - Fizz if number is divisible by 3 only - Buzz if number is divisible by 5 only - FizzBuzz if number is divisible by 3 and 5 - numb...
# input the number of readings from cnor.py import numberofreadings nor=numberofreading(eval(input("enter the number of readings: "))) readings=list() #read the readings of experiment for i in range(nor): readings.append(eval(input(""))) print("the readings are",readings) # Inbuit parameters ductsize=0.015 diaof...
import random def cows_and_bulls(user_input, num): for i in range(len(user_input)): if user_input[i] == num[i]: global cows cows +=1 if ((user_input[i] in num) and (user_input[i] != num[i])): ...
import urllib.request import pandas class CompanyDetails: # makes all letters lowercase, then makes first letter of each word uppercase then makes list using split def scraper(self, airline): name = airline.lower().title().split(' ') symbol = '%20' linkTail = ''.join([j+symbol...
# Input: strs = ["flower","flow","flight"] # Output: "fl" # //////////////////METHOD ONE/////////////////// class Solution: def longestCommonPrefix(self, strs): if not strs: return "" shortest = min(strs, key=len) stop = None for i, s in enumerate(shortest): for rest in ...
# Sort the balloons by their end value # Then only update the end variable when the new balloon starts after the current balloon's end (no overlap). It means that we need a new arrow for the new balloon. # And after the current balloon, even if we come across a balloon whose start is less than the previous ends, we do...
# Input: nums = [3,2,1,5,6,4], k = 2 # Output: 5 # Input: nums = [3,2,3,1,2,4,5,5,6], k = 4 # Output: 4 # This is a O(nlogn) solution import heapq class Solution: def findKthLargest(self, nums, k): heapq.heapify(nums) for _ in range(len(nums) - k): heapq.heappop(nums) return heap...
# Input: ["i", "love", "leetcode", "i", "love", "coding"], k = 2 # Output: ["i", "love"] # Explanation: "i" and "love" are the two most frequent words. # Note that "i" comes before "love" due to a lower alphabetical order. import collections, heapq # class Solution: # def topKFrequent(self, words, k): # wor...
# ////////////////////////BFS kinda slow////////////////////////////// # target = "leet" class Solution: def alphabetBoardPath(self, target): board = ["abcde", "fghij", "klmno", "pqrst", "uvwxy", "z"] def bfs(r, c, target): if board[r][c] == target: return r, c, "!" ...
# Input: height = [0,1,0,2,1,0,1,3,2,1,2,1] # Output: 6 # Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. class Solution: def trap(self, height): if len(height) < 3: retu...
# Input: nums = [1,3,4,2,2] # Output: 2 # can use slow and fast pointer for to satisfy this problem's requirements - not modifying the existing input list and O(1) time complexity class Solution: def findDuplicate(self, nums): slow = fast = finder = 0 # let the slow and faster pointer meet ...
class Employee: def __init__(self, id: int, importance: int, subordinates: List[int]): self.id = id self.importance = importance self.subordinates = subordinates #////////////////////////////////////// # I think this problem is to understand that each employee is an object, so we can create ...
# create a dictionary out of the special 2D list # while class Solution: def shoppingOffers(self, price: List[int], special: List[List[int]], needs: List[int]) -> int: def find_lowest_price(needs): # memorization if tuple(needs) in self.memo: return self.memo[tuple(ne...
# Math + Two Pointers # I feel like this is more of a Math question than Two Pointer algorithm. # Math fact: # if a>0: the quadratic function is something like this # y # ^ # | + + # | + + # | + + # | + + # ---------------------------> x # if a<0: the quadratic function is...
# Input: 20 # Output: 6 # Explanation: # The confusing numbers are [6,9,10,16,18,19]. # 6 converts to 9. # 9 converts to 6. # 10 converts to 01 which is just 1. # 16 converts to 91. # 18 converts to 81. # 19 converts to 61. class Solution: def confusingNumberII(self, N): d = {0: 0, 1: 1, 6: 9, 8: 8, 9: 6} ...
# Input: grid = [[1,0,2,0,1],[0,0,0,0,0],[0,0,1,0,0]] # Output: 7 # Explanation: Given three buildings at (0,0), (0,4), (2,2), and an obstacle at (0,2). # Wow complex... We need a few variables: # hits: how many times the 0 can be reached from a 1 # disSum: how many steps can this 0 be reached by all 1s # visited (for ...
# Input: s = "leetcode", wordDict = ["leet","code"] # Output: true # Explanation: Return true because "leetcode" can be segmented as "leet code". # ////////////////O(n^3)///////////////////// class Solution: def wordBreak(self, s, wordDict): dp = [True] + [False] * len(s) wordDict = set(wordDict) ...
# Example 1: # Input: nums = [1,2,3] # Output: [1,3,2] # Example 2: # Input: nums = [3,2,1] # Output: [1,2,3] # Example 3: # Input: nums = [1,1,5] # Output: [1,5,1] # Example 4: # Input: nums = [1] # Output: [1] # The replacement must be in place and use only constant extra memory. # I think the secret is to reverse...
""" Initialize your data structur:type iterator: Iterator """ self.iter = iterator self.nxt = self.iter.next() if self.iter.hasNext() else None def peek(self): """ Returns the next element in the iteration without advancing the iterator. :rtype: int ...
# This problem is a hard ask, until you realize that we've actually solved this problem before in other sliding window problems. Generally, the sliding window problems have some kind of aggregate, atMost k, largest substring, min substring with k etc. They're always "given an array or string, find some computed sub pro...
#coding=utf-8 #1.无参数,无返回值 ''' def jia(): num1=int(input("num1")) num2=int(input("num2")) print(num1+num2) jia() ''' #2.无参数,有返回值 ''' def login(): username=input("input your name") return username name=login() print('your name is %s' % name) ''' #3.有参数,无返回值 def login1(name,passwd):...
attendees = ["Hanna", "Kevin", "Stefan"] # Add value in the list attendees.append("Ashley") # Add list to list attendees.extend(["Greg", "Jiran"]) optional_invitees = ["ederm", "malica"] potential_attendees = attendees + optional_invitees print("There are", len(attendees), "attendees currently. ") for attendee in a...
class Monster: def __init_(self, name, catchphrase): self.name = name self.catchphrase = cathphrase def speak(): print(f"Hello my name is {name} and I say {catchphrase}) monster_nova = Monster(nova) print(monster_nova.speak()) #make lower case print(monster_nova.speak().lower())
#add function def add(x,y): return x+y #subtract function def subtract(x,y): return x-y #multiply function def multiply(x,y): return x*y #divide function def divide(x,y): return x/y print("Select operation of calculation") print("1. Add") print("2. Subtract") print("3. Multiply") print("4. Divide") wh...
# TYPES OF Built in ERRORS # IndexError # KeyError # NameError (variable is not defined) # AttributeError (there are no that attribute in some object) # NotImplementedError ("This feature has not been implemented yet!") # RuntimeWarning (Base Error) # SyntaxError (mess up with Python: missed colons for example) # Inde...
# XGBoost # 1. Data Preprocessing # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd from warnings import filterwarnings filterwarnings('ignore') # Importing the dataset dataset = pd.read_csv('/home/mayank/Documents/Projects/Machine-Learning/Part 10 - XGBoost/Churn_Model...
import datetime now = datetime.datetime.now() hours=int(input("Годин:")) hours=hours+now.hour minutess=int(input("Хвилин:")) minutess=minutess+now.minute hours=hours+int(minutess / 60) minutess=minutess % 60 hours=hours % 24 print(str(hours) + " : " + str(minutess)) while True: now = datetime.datetime.now() if hours=...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Sep 27 18:57:29 2018 @author: vogebr01 """ import skimage import os from skimage import io from matplotlib import pyplot as plt import numpy as np # read in the images a = io.imread('/Users/brodyvogel/Desktop/homework3_images/a.tif') camera = io.imrea...
graph={ 'A':set(['B','C']), 'B':set(['A','D','E']), 'C':set(['A','F']), 'D':set(['B']), 'E':set(['B']), 'F':set(['C']) } def bfs(graph,start): queue=[start] visited=[] while queue: node = queue.pop(0) visited.append(node) neighbours=grap...
import sys a = ['M', 'M', 'M', 'C', 'C', 'C'] b = [] c = [] ch = 2 print("Rules of Game") print("1 : Only two or one person can travel by boat forward or reverse direction") print("2 : M stand for Missionaries") print("3 : C stand for Cannibles ") print("4 : If No Cannibles is found more than Missionaries on b...
#!/usr/bin/env python # -*- coding:utf8 -*- # author:mafei0728 def fun1(x): while x>0: print('ok') yield x x -= 1 y = fun1(10) # for i in y: # print(i) while True: try: next(y) except StopIteration: break
#!/usr/bin/env python # -*- coding:utf8 -*- # author:mafei0728 """ Return True if bool(x) is True for all values x in the iterable. If the iterable is empty, return True. """ ###穿一个可迭代对象,如果所有元素全部为true,返回为True print(all([1,2,3,4])) print(all([])) print(all([1,0])) print(all('')) print(all(' '))
#!/usr/bin/env python # -*- coding:utf8 -*- # author:mafei0728 f = open('a.text','r') f.__next__() f.__iter__() print(f) print(f.__iter__()) #文件句柄既是可迭代对象,又是迭代器,其实和文件本身相等,所以可以直接用next方法 print(next(f).strip()) print(next(f).strip()) print(next(f).strip()) print(next(f).strip()) #优点 # 1: 迭代器提供了一种不依赖索引取值的方式 # 2: 不用把所有可迭代对象的...