text
stringlengths
37
1.41M
""" recursive function summary of number sequence s(n) = s(n-1) + n s(10) = s(9) + 10 s(9) = s(8) + 9 ... s(1) = 1 """ def s(n): if n == 1: return 1 return s(n-1) + n result = s(10) print(f"The sum is {result}") """ numbers = [1,2,3,4,5,6,7,8,9,10] print("=== start ===") sum = 0 for n in nu...
""" string to datetime object """ from datetime import datetime date_string = "6 December, 2020 01:10:38" print("date_string =", date_string) print("type of date_string =", type(date_string)) try: date_object = datetime.strptime(date_string, "%d %B, %Y %H:%M:%S") except ValueError as ve: print("String d...
""" Q2.chengjun """ list1 = [1, 2, 3, 4, 5] a = 1 for b in list1: a= a * b print(a)
""" 1, 2, 3, 4, ..., 20 ? product = 1x2x3x....x20 """ product = 1 """ product x 1 -> product product x 2 -> product ... product x 20 -> product """ for i in range(1,21): product = product * i print("Product is {}".format(product)) """ 2432902008176640000 2432902008176640000 """
""" set max size for a window maxsize != maximize """ import tkinter as tk root = tk.Tk() root.title('Python GUI - subtopic') winw= 800 winh= 450 posx=300 posy=200 root.geometry(f'{winw}x{winh}+{posx}+{posy}') # case 1. root.maxsize() # case 2. root.maxsize(1000,600) root.mainloop()
""" python file I/O Opening Files open() first look """ # case 4. open file which does not exist # error occurs print("[info] open file in specified full path") print("[info] opening file_open.txt ...") # FileNotFoundError: [Errno 2] No such file or directory: f = open("D:/workspace/pycharm201803/ceit4101python/mo...
""" [Homework] Write codes to try out number formatting type Date: 2021-05-09 Due date: by the end of next Sat. """ # case 1 num1 = 10 str1 = "I am testing the data: {:5d}".format(num1) print(str1) print('======') # case 2. char = 200 str2 = "I am testing the data: {:c}".format(char) print(str2) char = 201 str2 = "I...
""" i/o input / output standard input dev. keyboard standard output dev. monitor/screen/console *object sep = separator end = '\n' """ print("hello") print("hello","world", sep="_") print("hello","world", sep=",") print("hello","world", sep=";") print("hello","world", sep=":") print("hello","world", sep="::"...
""" stem1402_python_homework_2_steven """ # 1. Write a Python function to find the Max of three numbers. def maximum(x, y, z): list1 = [x, y, z] return max(list1) x = 21 y = 346 z = 345 print("The maximum number of {}, {} and {}, is {}".format(x, y, z, maximum(x,y,z))) print("------------------------------...
def AND(num_1, num_2): return num_1 and num_2 print(AND(float(input('Please enter the and:')),float(input('Please enter the other and:'))))
""" 8. Write a Python function that takes a list of words and returns the length of the longest one. """ """ wordlist = ['abc','cdef','ab','cdefg','bccc'] longest = wordlist[0] for word in wordlist: # print(word, len(word)) if len(longest) < len(word): longest = word print("The length of the longest...
""" review list """ # TypeError: '<' not supported between instances of 'str' and 'int' my_list = [2,'a5',1,'b6',7] # my_list.sort() # original password: mylaptop # encrypt by reversing original_pwd = ['m','y','l','a','p','t','o','p'] print(original_pwd) original_pwd.reverse() new_pwd = original_pwd print(new_pwd)...
""" you can input a Name again and again from keyboard Bonsoir, the Name! if you input 'Eva' print out Bonjour, Eva and then exit the program """ def greeting(name): print("Bonsoir {}".format(name)) while True: name = input("Input your name:") if 'eva' == name.lower(): print('Bonjour {}'.forma...
""" [Homework] Quiz6. question 8 """ """ Q8 """ matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] print(matrix[0][0], str(matrix[0][1])+'\t', str(matrix[0][2])+'\t', matrix[0][3]) print(matrix[1][0], str(matrix[1][1])+'\t', str(matrix[1][2])+'\t', matrix[1][3]) print(matrix[2][0], str(matrix[2][...
""" summary 1. list comp. is an elegant way to define and create lists based on existing lists. 2. list comp. is generally more compact and faster than normal functions and loops for creating lists. 3. we should avoid writing very long list comp in one line to ensure that code is user-friendly. 4. every list comp. can...
def replaceall(target, new): my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm'] * 3 next_index = -1 for i in my_list: if i == target: next_index = my_list.index(i, next_index + 1) print(next_index) my_list[next_index] = new return my_list my_list = replaceall('r'...
""" insert items """ # case 1. insert a single item # insert(index, item) odd = [1,9] odd.insert(1, 3) print(odd) # case 2. insert multi items odd[2:2] = [5,7] print(odd) # odd[2:2] = [] # print(odd)
# program 2 """ # plan: 1. define characters 2. input the string 3. create "counting" 4. define a counter function 3. count the number of each character using the counter 4. print the result of each character """ # program: def counter(user_str): counting = {} for char in user_str: try: co...
""" converting a floating number to a fraction """ import fractions import decimal # ex1. print(fractions.Fraction(1.1)) print(decimal.Decimal(1.1)) print(decimal.Decimal('1.1')) print() # solution 1. limit denominator result = fractions.Fraction(1.1).limit_denominator() print(result) # solution 2. as string print(...
""" fraction f = p/q (p, q are integers, q!=0) A fraction has a numerator and a denominator, both of which are integers. This module has support for rational number arithmetic. """ import fractions from fractions import Fraction as F f1 = fractions.Fraction(1.5) print(f1) f2 = fractions.Fraction(1.3) print(f2) ...
""" string literal """ # case 1: normal string with ", ' strings = "This is Python" strings2 = 'This is Python' print("strings",strings) print("strings2",strings2) # case 2 char = "C" char = 'C' print("char",char) # case 3 multiline_str = """This is a multiline string with more than one line code.""" print(multiline...
""" [Homework] Date: 2021-01-24 Write a Python GUI program to create your own window Common requirements: 1. set a title 2. set an image icon Extra requirements: 1. specify dimension at 16:9 2. make it at center point on your screen 3. set a background color 4. make it topmost 5. set max size and min size 6. make it re...
""" review of function """ """ 1a. what is function in python 1b. what is function in math mapping relationship 2. how it works 3. define a function keyword: def 4. how to use call a function 5. syntax of function signature of function function name function argument return statement 6. input and output ...
""" User-defined Exceptions 1. what is it? 2. how to write 3. how to use 4. why to use a. Built-in error b. ValueError, ValueError c. reusable Exception/Error Runtime Logical Built-in Error 20-30 Syntax try: pass except: pass except: pass else: pass finally: pass try:...
""" set set() empty set """ mylist = [1,2,3,2] myset = set(mylist) print(myset) mytuple = (1,2,3,2) myset = set(mytuple) print(myset) # empty set set1 = {} print(type(set1)) set1 = set() print(type(set1))
str1 = "aaaaaaaaaaa" str2 = "ab" "11" "2" print("11">"2") print(11>2)
""" 2021-04-04 Quiz5 q1 - q6 Due date: by the end of next Sat. """ """ answer: q1 ans: a q2 ans: integers: class 'int' floating point numbers: class 'float' complex numbers: class 'complex' q3 ans: integers: a = 1, a = 2 floating point numbers: b = 1.5, b = 2.5 complex numbers: c = 1+2j, c = 2+4...
def word(a,y): b = [] c = y.split(" ") for i in c: if len(i) > a: b.append(i) return b x = ('The python homework number three') print(word(4,x))
""" collection """ list1 = [3,1,6,7,4] list2 = [True, 1.2, 5, 'abc'] print(list1) print(list2) tuple1 = (3,2,1,4,6) tuple2 = (2,3,1,4,6) print(tuple1) print(tuple2) set1 = {True, 1.2, 5, 'abc'} print(set1) set2 = {1, 1, 2, 2, 3, 3} print(set2) set3 = {'a','b','c','d','e'} print(set3) dict = {"Mon":"1", "Tu...
""" try except """ def f1(): print("f1()") f2() def f2(): print("f2()") f3() def f3(): print("f3()") raise Exception # main program print("start") try: f1() except Exception: print("Waring: there is an exception!") print("end") print("continue to work")
from unittest import TestCase from .. import app class ValidNumberTest(TestCase): ERROR_MSG = 'Invalid - `%s`' def setUp(self): self.solution = app.Solution() ### sample input from leetcode def test_number(self): test_str = '0' self.assertTrue(expr=self.solution.isNu...
#metatropi string se arithmo ascii L=input("Insert a word: ") def split(word): return [char for char in word] word = list(L) num="" for i in list(map(str, map(ord, list(L)))): print(i, end="") num+=i int_num=int(num) prime=bool(False) if int_num > 1: for i in range(2, int(int_...
# ex 1 emptylist = [] print(emptylist) # ex 2 list1 = ["sport"] print(list1) # ex 3 list2 = ["sport", "books", "robots"] print(list2) # ex 4 list2.append("computers") print(list2) # ex 5 new_items = input("enter a hobby: ") list2.append(new_items) print(list2) # ex6 print(*list2) # ex 7 print(*list2, sep = ", ") ...
#Store five names and their favorite numbers in a dictionary favorite_numbers = {'eric':55, 'tony':93, 'sarah':23, 'melissa':85, 'matt':32,} #Inserts the key and value using the format function print(f"Eric's favorite number is {favorite_numbers['eric']}.") #Creates a variable for the key and value then prints ...
class User: def __init__(self, first_name, last_name, hometown, age, status): self.first_name = first_name.title() self.last_name = last_name.title() self.hometown = hometown.title() self.age = age self.status = status self.login_attempts = 0 def increment_login_attempts(self): self.login_att...
#Create a FOR loop that lists out the different types of pizza in the list. pizzas = ['supreme', 'hawaiian', 'meat lovers'] for pizza in pizzas: print(f"Give me a {pizza.title()} pizza and I will be happy.") print("Pizza is the best!")
def sandwich_order(bread, meat, *toppings): print(f"We will make a {meat} sandwich on {bread} bread with the following toppings: ") for topping in toppings: print(f"- {topping}") sandwich_order('white', 'turkey', 'lettuce','pickle','mayo')
#Prints the name in the variable using all three case types on a separate line. name = "kevin debruyne" print(f"{name.title()} \n{name.upper()} \n{name.lower()}")
#Create three dictionaries of people's info then store the dicitonaries in a list people = [] person = { 'first': 'isabella', 'last': 'fouquier', 'age': 15, 'city': 'white oak', } people.append(person) person = { 'first': 'matthew', 'last': 'fouquier', 'age': 41, 'city': 'tampa', } pe...
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # 切片操作左闭右开 result = arr[7:10] # 取出7~10位 ['8', '9', '10'] result = arr[-3:-1] # 取出倒数第三位到倒数第1位 ['8', '9'] result = arr[-3:] # 如果想包含到最后一位,直接省略后面一个就行,最前面同理。['8', '9', '10'] result = arr[:] # 两边都省略就是包含全部的list内容 # 控制切片步长 result = arr[1:6:2] # 1~6位每两位取出一个['2', '4', '6'] resul...
# 字典是另一种可变容器模型,且可存储任意类型对象。 # 字典的每个键值 key=>value 对用冒号 : 分割,每个键值对之间用逗号 , # 分割,整个字典包括在花括号 {} 中 ,格式如下所示: # d = {key1 : value1, key2 : value2 } dict = {'a': 1, 'b': 2, 'c': '3'} print(dict) dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'} # 值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。
# 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 def sumEvenGrandparent(self, root): nodes = [root] total = 0 while nodes: currentNode = nodes.pop() ...
def isValid(s): stack = [] d = {'(': ')', '[': ']', '{': '}'} for ch in s: if ch in d.keys(): stack.append(ch) elif len(stack) > 0 and ch == d[stack.pop()]: continue else: return False if len(stack) > 0: return False else: ...
def isPowerOfThree(n): if n == 0: return False while n % 3 == 0: n = n / 3 if n == 1: return True else: return False print(isPowerOfThree(1))
def kidsWithCandies(candies, extraCandies): return [True if person + extraCandies >= max(candies) else False for person in candies] print(kidsWithCandies([4,2,1,1,2], 1))
def longestCommonPrefix(strs): if not strs: return "" shortest_word = min(strs,key=len) for i, ch in enumerate(shortest_word): for other in strs: if other[i] != ch: return shortest_word[:i] return shortest_word print(longestCommonPrefix(["f...
# list 清單 a = ['Toyota', 'Honda'] # 空清單 print(a) # index(索引) (車廂代號, 從0開始) print(a[0]) print(a[1]) # .append() 加東西進清單 a.append('Audi') print(a) # len() 取長度 length print(len(a)) # in + 清單, 檢查東西有沒有在裡面 print('Audi' in a) # 是非題 True, False print('Benz' in a)
def isPrime(n): if (n <= 1): return False max_divisor = n cur_divisor = 2 while (cur_divisor <= max_divisor): # print("cur_divisor: {0}, max_divisor: {1}".format(cur_divisor, max_divisor)) if (cur_divisor == max_divisor): return True elif (0 == n % cur_di...
def close_enough(old, new): return abs(old - new) < 0.001 def fixed_point(f, start): # 这个方法来计算不动点: # 思路就是不断把得数带入自变量里 # 前提条件是 这个过程 是收敛的 def iter(old, new): if close_enough(old, new): return new else: return iter(new, f(new)) return iter(start, f(start)) ...
''' This program reads through the email and finds all the lines that contain From: and To: . We will count the following: usernames in the From: field hosts in the From: field usernames in the To: field hosts in the To: field We will print the different objects in csv format ''' # To access STDOUT import sys #To a...
board = [ [0,0,0,0,0,0,8,1,7], [0,2,0,9,0,0,0,3,0], [8,0,0,7,0,0,9,0,0], [5,0,0,0,8,0,0,0,0], [0,0,3,1,0,2,5,0,0], [0,0,0,0,4,0,0,0,6], [0,0,8,0,0,5,0,0,4], [0,7,0,0,0,4,0,6,0], [2,9,4,0,0,0,0,0,0] ] def show_board(board): for i in range(len(board)): if i % 3 == 0 and i...
# Student: Frank O'Connor # E-80 Assignment 3 # Email: fjo.con@gmail.com import csv, sys, os.path, bisect assign_count = {} availibility = {} fail_reason = "" def main(argv): # Example Usage: 'python .\assign_times.py shifts.txt' if len(sys.argv) < 2 or len(sys.argv) > 2: sys.exit('Usage: %s shifts_filename' % ...
#! import usr/bin/python3 # Dictionary.py : Simple program to find the meaning of given word import requests from bs4 import BeautifulSoup print("Word:") w = str(input()) print("please wait..... while we get u ur meaning") res = requests.get("http://www.dictionary.com/browse/" + w) soup = BeautifulSoup(res.content,"...
#calender of the year which is entered import calendar y = int(input("Enter Any year")) m = 1 print("\n**********CALENDAR********") cal=calendar.TextCalendar(calendar.SUNDAY) i=1 while i <=12: cal.prmonth(y,i) i+=1
input_string = input("Enter Tasks separated by coma ") task_list = input_string.split(",") print("Printing all Task For Today") for task in task_list: for i, task in enumerate(task_list,1): print(i, '. ' + task, sep='',end='i')
''' APS-2020 Problem Description, Input, Output : https://codeforces.com/contest/1367/problem/A Code by : Sagar Kulkarni ''' for _ in range(int(input())): str1=input(); list1=list(str1) if len(list1)==2: print(str1) else: list2=[] for i in range(1,len(list1)-2,2): l...
''' APS-2020 Problem Description, Input, Output : https://www.codechef.com/problems/SPLITIT Code by : Sagar Kulkarni ''' for _ in range(int(input())): n=int(input()) list1=list(input()) if list1[-1] in list1[:n-1]: print("YES") else: print("NO")
''' APS-2020 Problem Description : Remove punctuations from a string Input : string Output : string (without punctuations) Code by : Sagar Kulkarni ''' punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~''' print("Enter a String") my_str=input() no_punct="" for char in my_str: if char not in punctuations: no_pu...
''' APS-2020 Problem Description, Input, Output : https://codeforces.com/contest/71/problem/A Code by : Sagar Kulkarni ''' for _ in range(int(input())): str1=input() if len(str1)>10: newStr=str1[0:1]+str((len(str1)-2))+str1[-1] print(newStr) else: print(str1)
''' APS-2020 Problem Description, Input, Output : https://codeforces.com/contest/1301/problem/A Code by : Sagar Kulkarni ''' T=int(input()) for _ in range(0,T): a=input() b=input() c=input() list1=list(a) list2=list(b) list3=list(c) for i in range(0,len(list3)): if list3[i]==list...
# -*- coding: utf-8 -*- import math import random def average(data): return sum(data) * 1.0 / len(data) def variance(data): avg = average(data) var = map(lambda x: (x - avg)**2, data) return average(var) def standard_deviation(data): return math.sqrt(variance(data)) def get_variance_range(...
import unittest from cooking import cook class CookingTest(unittest.TestCase): def test_single_input_unchanged(self): number = 5 expected_output = (5, 5) output = cook(number) self.assertEqual(output, expected_output) def test_two_digit_no_swap(self): number = 22 ...
#!/home/hmeng/anaconda3/bin/python #list print([1, 2] + [3, 4]) print([1]*5) print(2 in [1, 2, 5]) l = [3, 5] l.append(6) print(l) # tuple t = (1, 'a', 2, 'b') a, b, c, d = t print(b) #dictorary dict = {'name':'Josh', 'age': 15, 'weight':'40kg'} for key in dict.keys(): print(key) for value in ...
from abc import ABCMeta, abstractmethod class ABCMesh(object): """Abstract base class for mesh. Attributes ---------- name : str name of mesh """ __metaclass__ = ABCMeta @abstractmethod def get_point(self, uid): # pragma: no cover """ Returns a point with a given u...
import linkedlist def addList(): li = linkedlist.LinkedList() li.add(0, 2) li.add(1, 1) li.add(2, 5) li.add(3, 2) li.add(4, 3) li.add(5, 6) li.add(6, 7) return(li) #1 def listPartition(LinkedList,k): li = list() node = LinkedList.head while(node): li.append(no...
def main(): print("iterable_example") iterable_example() def iterable_example(): iterable = ['Spring', 'Summer', 'Autumn', 'Winter'] iterator = iter(iterable) print(next(iterator)) print(next(iterator)) print(next(iterator)) print(next(iterator)) try: print(next(iterator)) ...
class WordDictionary: class Node: def __init__(self): self.is_word = False self.next = [None for _ in range(26)] def __init__(self): """ Initialize your data structure here. """ self.root = WordDictionary.Node() def addWord(self, word: str) -...
class WordDictionary: class Node: def __init__(self): self.is_word = False self.next = dict() def __init__(self): """ Initialize your data structure here. """ self.root = WordDictionary.Node() def addWord(self, word: str) -> None: """...
""" This program is used to scrape NBA data and separate into a different file for each year between 1989 and 2019 for all NBA players (31 years). The website used is https://www.basketball-reference.com """ # Imports from bs4 import BeautifulSoup import requests import csv # This part creates a dictionary of URLs ba...
# 辅助函数 def select_count(cursor, table): sql = "select count(*) from {}".format(table) cursor.execute(sql) rows = cursor.fetchall() return rows[0][0] def insert_person(cursor, id, name): sql = "insert into person values('{}', '{}')".format(id, name) cursor.execute(sql) return cursor.rowcoun...
""" Check 2 binary trees for equality - same sructure - same values at each node n1 / \ n2 n3 / \ \ n4 n5 n6 n1 / \ n2 n3 / n4 n1 / \ n2 n3 \ n4 """ import collections class Node: left = None right = None val = None def make_tree(drop_last=...
## The Pythonic Way! import random names = [ 'Raffaello', 'Donatello', 'Michelangelo', 'Leonardo'] instruments = [ 'daggers', 'no-idea1', 'No-idea2', 'pole'] ''' for name in names: print name print for i,name in enumerate(names, 10): print i, name print for name in reversed(names): print name for name, inst...
import requests import datetime import time import xlsxwriter class Tweet: # Class to hold data related to tweets def __init__(self, text=None, date=None): self.text = text self.d = date class Day: # Class to track tweets on a certain date def ...
""" Ticket numbers usually consist of an even number of digits. A ticket number is considered lucky if the sum of the first half of the digits is equal to the sum of the second half. Given a ticket number n, determine if it's lucky or not. """ def isLucky(n): num=[int(i) for i in str(n)] if len(num)%2!=0: ...
""" An IP address is a numerical label assigned to each device (e.g., computer, printer) participating in a computer network that uses the Internet Protocol for communication. There are two versions of the Internet protocol, and thus two versions of addresses. One of them is the IPv4 address. Given a string, find out ...
""" Write a function that reverses characters in (possibly nested) parentheses in the input string. Input strings will always be well-formed with matching ()s. """ def reverseInParentheses(inputString): s='' e='' c=0 r=inputString l=True while l==True: for i,j in enumerate(r): ...
""" Given integers a and b, determine whether the following pseudocode results in an infinite loop while a is not equal to b do increase a by 1 decrease b by 1 Assume that the program is executed on a virtual machine which can store arbitrary long numbers and execute forever. """ def isInfiniteProcess(a, b): ...
""" Two arrays are called similar if one can be obtained from another by swapping at most one pair of elements in one of the arrays. Given two arrays a and b, check whether they are similar. """ def areSimilar(a, b): count = 0 A = [] B = [] for i in range(len(a)): if (a[i]!= b[i]): ...
""" Given two cells on the standard chess board, determine whether they have the same color or not. """ def chessBoardCellColor(cell1, cell2): if ord(cell1[0])%2==ord(cell2[0])%2: if int(cell1[1])%2==int(cell2[1])%2: return True if ord(cell1[0])%2!=ord(cell2[0])%2: if int(...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed May 3 14:44:31 2017 @author: missyallan Missy is practicing Python with NYU DataCamp GitBook """ a = "some" b= "thing" c = a + b print('c =', c) #%% x = 2 y =3 z = x/y print('z =', z) 4+5 # add 4 and 5 print(4+5) #%% f = "I don't believe it...
def InsertSort(Array): for i in range(1,len(Array)): temp = Array[i] Index = i while Index > 0 and Array[Index - 1] > temp : Array[Index] = Array[Index - 1] Index = Index - 1 Array[Index] = temp def QuickSort(Array): if len(Array) <= 1 : ...
# Person class # Creates a Person object that Fellow and Staff classes inherit from class Person(object): """Creates a Person object that Fellow and Staff class inherit from""" def __init__(self, name): self.name = name def __repr__(self): return "<Person %s>" % self.name
#Vous pouvez suprimer ce code c'est juste pour le test def main(): print("Hello World!") print("Langage disponibles :\n\t-Java (J) \n\t-Python3 (PY3)") Langages = ["PY3", "J"] LangageInitial = input("Quel est le langage du programe Initial:") if LangageInitial.upper() not in Langages: print("Langage non dispon...
def print_evens(start): ''' function: counts by two from a starting number to 100 inclusive parameters: starting number returns: printed counting by twos from start to 100''' start = 0 while start < 99: start += 2 print(start) def main(): count_from = 0 print_...
##def main(): ## ## for i in range(-1,-101,-1): ## print(i) ## ## ##main() ##def main(): ## data = ["hello", 9002, 8, 3.0, 5] ## ## for i in range(len(data)): ## print(data[i]) ## i +=1 ## ##main() def spread_strings(list_of_strings): i = 0 spaced_word = " " while i < len(list_o...
def convert_tuple(user_tuple): '''function: takes tuple input and returns a list that contains same elements and order parameters: one tuple return: list with same elements and order as tuple''' new_list = [] i = 0 while i < len(user_tuple): new_list.append(user_tuple[i]) ...
def spread_strings(word): index = 0 spaced_word = "" while (index < len(word)): spaced_word += word[index] + " " index += 1 return spaced_word def main(): word_list= ["Hello", "howdy", "Hiya"] word_one_list = word_list[0] word_two_list = w...
from sklearn.mixture import GaussianMixture from sklearn.cluster import KMeans import matplotlib.pyplot as plt from sklearn.datasets import load_iris import sklearn.metrics as sm '''scikit-learn, an estimator for classification is a Python object that implements the methods fit(X, y) and predict(T)''' '''scikit-l...
#ARMANDO DANIEL SAUCEDO ALEGRIA# #COBOS VALDEZ JESUS RICARDO# def entrada(matriz,fila,columna): M = len(matriz) for i in range(columna): if matriz[fila][i] == "2": return False for i in range(columna,M,1): if matriz[fila][i] == "2": return False for f,c in zip(range(fila,-1,-1), range(columna,-1,-1)): ...
""" Write a program that compares two lists and prints a message depending on if the inputs are identical or not. Your program should be able to accept and compare two lists: list_one and list_two. If both lists are identical print "The lists are the same". If they are not identical print "The lists are not the same....
# parkhaus.py # Angabe für das Beispiel: siehe Moodle a = 0; print("Linienbus Simulator 2018!") haltestellen = input("Wie viele Haltestellen gibt es? ") haltestelle = int(haltestellen) i = 0 while(i < haltestelle): i= i + 1 y = a print("Sie sind an der Haltestelle " , i , ". Wie viele Personen steigen...
import random from hangman_art import stages, logo from hangman_words import word_list # import only system from os from os import system, name # define our clear function def clear(): # for windows if name == 'nt': _ = system('cls') # for mac and linux(here, os.name is 'posix') ...
from art import logo import random # import only system from os from os import system, name #Define our clear function def clear(): # for windows if name == 'nt': _ = system('cls') # for mac and linux(here, os.name is 'posix') else: _ = system('clear') cards = [11, 2, 3,...
'''sort a dictionary by key or value''' dict1={} n=int(input("enter the number of element in dict1: ")) while n>0: key=input("enter the key: ") value=int(input("enter the value: ")) dict1.update({key:value}) n-=1 dict1=sorted(dict1.items(),key=lambda x:x[0]) print(dict1)
def add1(a, b): return a + b def func2(add1): def innerf(a,b): print("this function subtract also") c=a-b #print(c) return add1(a,b) return innerf ans=func2(add1) print(ans(5,3))
def repeatingElement(a): result = a[0] for i in range(1,len(a)): result = result ^ a[i] print (result) repeatingElement([1,2,3,4,5,5,6,7,8])
#simulation for two players at a time #Players are chosen with uniform sampling #Feel free to change parameters p,d,p,etc. import random '''fixes the bet for all games''' #p players p = 7 #d dollars d = 77 #fixes the bet for all games k = 11 Counts = [] num_iterations = 10000 for i in range(num_iterations): coun...
# author:JinMing time:2020-05-11 # -*- coding: utf-8 -*- # 在一个内部函数里边,对在外部作用域(不能是全局作用域)的变量进行调用 # 那么这个内部函数就被称之为闭包 def outer(): x = 10 def inner(): print(x) return inner outer()() # inner() # 可以拆为下面两行 a = outer() # a = inner a() # inner()
# author:JinMing time:2020-04-10 alist = [9,2,6,0] alist.sort(reverse=True) print(alist) print(alist[::-1]) # alist.reverse()# 翻转顺序--不排序 # print(alist)
class Tiger: nickName = '老虎' #静态属性 def __init__(self,inWeight):#实例属性 self.weight = inWeight #实例方法-- def roar(self): print('我是老虎---wow!,体重减5斤') self.weight -= 5 def feed(self,food): if food == 'meat': self.weight += 10 print('恭喜,喂食正确,体重增加10斤'...