text
stringlengths
37
1.41M
#print numbers in a Z within a NxN matrix def printz(n): num = 1 matrix = [[0]*n for i in xrange(n)] for i in xrange(n): for j in xrange(n): if i == 0 or i == n-1 or j == (n-i-1): if num > 9: for d in str(num): num = int(d[-1]) matrix[i][j] = num num += 1...
#Write a function that takes an array of unsorted integers & a sum. #Returns a boolean if 2 integers within the array sum to the given sum def array_sum(arr, summ): """ >>> array_sum([1, 5, 3], 8) True >>> array_sum([1, 5, 3], 9) False """ #sort an array O(nlogn) sorted_array = sorted(...
""" Infix to Postfix Evaluation Count number of particles in a chemistry expression Input: '((H2O)300(AM4B)6)2000' '( ( H2O ) 300 ( AM4B ) 6 ) 2000' Output: 1,872,000 """ def infix(expr): input_list = expr.split() #['(', '(', 'H2O', ')', '300', '(', 'AM4B', ')', '6', ')', '2000'] output_list = [] i =...
#Exercise 2.7 of Cracking the Coding Interview #Given 2 singly linked lists, deterine if the 2 lists intersect. Return the intersecting node. #Note that the intersection is defined based on reference, not value. #That is, if the kth node of the 1st linked list is the exact same node as the jth node of the second linked...
grade = int(input("Input grade ")) ''' if (grade >= 70) : print("Pass") if (grade <70) : print("Fail") ''' if (grade<59) : print ("F") elif(grade<69) : print("D") elif(grade<79) : print("C") elif(grade<89) : print("B") elif(grade<100) : print("A")
#problem 1 raw_numbers = input ('''Input at least three numbers separated by a space >>>''') print('''These are your numbers ######################### ''' + raw_numbers) cooked_numbers = raw_numbers.split(" ") og_number = -1000000000000000000000000000000000 for number in cooked_numbers : if int(number) > og_number ...
def find_min_val(values) : new_val = values[0] for value in values : if new_val > value : new_val = value return new_val def find_position(values, element): index = 0 for value in values: if value == element: return index index += 1 def selection_sort...
""" Below functions are for exercise for sorting """ def load_data(file_name): """ Function for loading data """ try: with open(file_name, 'r') as raw_data: data = [] for items in raw_data: lines = list(items.strip().split(' ')) lines[0] ...
import students_manager as sm import sys STUDENTS_FILE_NAME = 'students.txt' STUDENTS_FINAL_FILE_NAME = 'final_students.txt' MAX_PASSWORD_TRAILS = 3 if __name__ == '__main__': # 1.Read and load the students in runtime memory sm.load_students(STUDENTS_FILE_NAME) # 2. Prompt for student ID student_id ...
# Первая вариация цикла i = 1000 while i > 100: print(i) i /= 2 # Вторая вариация, данная конструкция перебирает строку for j in 'hello world': if j == 'w': # из цикла можно выйти break или пропустить итеррацию continue # end = '' позволяет написать все в одну строку print(j * 2, end = ...
# def - обозачение начала функции def funk1(x, a): return x + a def funk2(x): def add(a): return x + a return add # передедовать, так и возвращать можно как списки, так и строки print(funk1(23, 12)) #в данном случае в переменную записыватеся первая функция funk2() #следующим действием мы перед...
""" 移动图形 """ from tkinter import * root = Tk() cv = Canvas(root, bg='white', width=200, height=120) rt1 = cv.create_rectangle(20, 20, 110, 110, outline='red', stipple='gray12', fill='green') cv.pack() rt2 = cv.create_rectangle(20, 20, 110, 110, outline='blue') # 移动rt1 cv.move(rt1, 20, -10) cv.pack() root.mainloop()
''' class: ADXL345 Purpose: This class is used to communicate through the SMbus and collect information from the accelerometer. Methods: Constants: These constants are used throughout the code of the ADXL345 class and have been provided by the manufacturer. __init__: constr...
n=int(input()) name_number=[input().split() for _ in range(n)] phoneBook={k:v for k,v in name_number} while True: try: name=input() if name in phoneBook: print(str(name) +'=' + phoneBook[name]) else: print('Not found') except: break
def judge(moveA, moveB): if moveA == 'rock' and moveB == 'paper': return False elif moveA == 'rock' and moveB =='scissors': return True elif moveA == 'paper' and moveB == 'rock': return True elif moveA == 'paper' and moveB == 'scissors': return False elif moveA == 's...
#def display_winner(winner, msg): # if winner == 'Player': # outcome = 'You win! ' # else: # outcome = 'Computer wins! ' # # print(outcome + '(' + msg + ')') # Test the function #display_winner('Player', 'You were closest to 21') # Expected: #You win! (You were closest to 21) #display_winner('Co...
#Name: sliding_puzzle_3x3.py #Purpose: Play the 3x3 sliding puzzle #Author: Brian Dumbacher import random def isPuzzleSolved(puzzle): return puzzle == [["1","2","3"],["4","5","6"],["7","8"," "]] def slidesValid(puzzle): slides = [] iBlank = 0 jBlank = 0 for i in [0,1,2]: for j in [...
animals = ['bear', 'python', 'peacock', 'kangaroo', 'whale', 'platypus'] python = animals[1] print python peacock = animals [2] print peacock bear = animals [0] print bear kangaroo = animals [3] print kangaroo whale = animals [4] print whale peacock = animals [2] print peacock platypus = anim...
from turtle import * def yin(radius, color1, color2): width(3) color("black", color1) begin_fill() circle(radius/2., 180) end_fill() def main(): reset() yin(200, "black", "white") yin(200, "white", "black") ht() return "Done!" if __name__ == '__main__': ...
""" 给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。 你可以假设数组中无重复元素。 示例 1: 输入: [1,3,5,6], 5 输出: 2 示例 2: 输入: [1,3,5,6], 2 输出: 1 示例 3: 输入: [1,3,5,6], 7 输出: 4 示例 4: 输入: [1,3,5,6], 0 输出: 0 """ def searchInsert(nums, target): if target in nums: for i in range(len(nums)): if target=...
import random angka = random.randint(1, 10) Max_Tebakan = 3 No_Tebakan = 0 Tebakan_true = False print('Program ini akan memilih angka secara acak dari 1 sampai 10') print('Anda harus menebak dalam {} percobaan'.format(Max_Tebakan)) petunjuk = 'Ini adalah tebakan ke {} anda. Masukkan angka lalu tekan enter ...
data = [['A1', 28], ['A2', 32], ['A3', 1], ['A4', 0], ['A5', 10], ['A6', 22], ['A7', 30], ['A8', 19], ['B1', 145], ['B2', 27], ['B3', 36], ['B4', 25], ['B5', 9], ['B6', 38], ['B7', 21], ['B8', 12], ['C1', 122], ['C2', 87], ['C3', 36], ['C4', 3], ['D1', 0], ['D2', 5], ['D3', 55], ...
# 3.1 my_name = "Tom" print(my_name.upper()) # 3.2 my_id = 123 print(my_id) # 3.3 # _123 = my_id my_id = your_id = 123 print(my_id) print(your_id) # 3.4 my_id_str = '123' print(my_id_str) # 3.5 # print(my_name + my_id) # 3.6 print(my_name + my_id_str) # 3.7 print(my_name*3) # 3.8 print('Hello World. This is my ...
# lecture on list and set my_List = [1, 2, 3, 4, 5] print(my_List) my_nested_list = [1, 2, 3, my_List] print(my_nested_list) my_List[0] = 6 print(my_List) my_List.append(7) print(my_List) my_List.remove(7) print(my_List) my_List.sort() print(my_List) my_List.reverse() print(my_List) print(my_List + [8, 9]) my_Li...
#!/usr/bin/env python """ glob using regular expressions """ import os import re def irglob(d, r, with_matches=False): """ Return all files in a directory that match a regular expression. if with_matches is True, also return the re.match result: [(fn, re.match)...] kinda like glob.glob but ...
""" 测试目标 1. r+和w+,a+的区别: 2。文件指针对数据读取的影响 """ # r+:没有文件的时候报错,文件指针在开头,所以能读出所有数据 # f = open('test.txt','r+') # # con = f.read() # print(con) # # f.close() # w+ 没有该文件会新建文件,文件指针也在开头,但是会用新内容覆盖原内容 # f = open('test.txt','w+') # # con = f.read() # print(con) # # f.close() # a+:如果没有文件会新建文件,文件指针在内容的末尾 f = open('test.txt','a+') ...
dict1 = {'name': 'Tom', 'age': 20, 'gender': '男'} # 字典序列[key] = 值 # id的值110 # 1、del # del(dict1) # print(dict1) # del dict1['name'] # print(dict1) # 2. clear() dict1.clear() print(dict1)
# reduce函数 reduce(fun,lst) # 需求:计算list1序列中各个数字的累加和 # 1.准备列表 import functools list1 = [1, 2, 3, 4, 5] # 2.定义函数 def func(a, b): return a + b # 3.调用函数 result = functools.reduce(func, list1) # 4.验收成果 print(result)
""" @Time : 2021/1/27 11:10 @Author : Steven Chen @File : 6多层继承.py @Software: PyCharm """ # 目标:体验多层继承 # 方法: # 1.师傅类 class Master(object): def __init__(self): self.kongfu = "[古法煎饼果子配方]" def make_cake(self): print(f'运用{self.kongfu}制作煎饼果子') # 2.创建学校类 class School(object): def __init__(self...
# 1.一个类创多个对象 class Washer(): def wash(self): print('洗衣服') def print_info(self): print(f'洗衣机的宽度{self.width}') print(f'洗衣机的高度{self.height}') haier1 = Washer() # 2.添加属性值 haier1.height = 800 haier1.width =600 # 3.获取对象的属性 haier1.print_info()
# 1.定交两个函数 2、函数1有返回值50作为函数2的输入值 def test1(): return 50 def test2(num): print(num) # 先得到函数1的返回值 result = test1() print(result) test2(result)
list1 = [10, 20, 30, 40, 50] s1 = {100,200,300,400,500} t1 = (100, 200, 300, 400) # 转成元组 # print(tuple(list1)) # print(tuple(s1)) #list() # print(list(s1)) # print(list(t1)) # set() print(list(list1)) print(list(t1))
# reduce函数 reduce(fun,lst) # 需求:筛选序列中的偶数 # 1.准备列表 list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # 2.定义函数 def func(x): return x % 2 == 0 # 3.调用函数 result = filter(func, list1) # 4.验收成果 print(list(result))
from google.cloud import translate import os import csv os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "ADD PATH TO YOUR GOOGLE CLOUD SERVICE ACCOUNT API KEY HERE" # https://cloud.google.com/translate/docs/basic/translating-text # Pull training questions from input_file_name and call the Google Translation API to ret...
import numpy as np from abc import ABCMeta from abc import abstractmethod class DataSampler(metaclass=ABCMeta): """ABC for data sampling""" @abstractmethod def sample(self, dataset): """Should return index samples of the dataset.""" class SequentialDataSampler(DataSampler): """Sequential sa...
# -*- coding: utf-8 -*- """ Created on Mon Jul 12 19:12:26 2021 @author: User """ """ The 6x7 board: | | | | | | | | 1 ---------------------- 2 | | | | | | | | 3 ---------------------- 4 | | | | | | | | 5 ---------------------- 6 | | | | | | | | 7 -----------------...
def em(): email=input("Ingresar Email: ") if "@" in email: Correo=email.split('@') usuario=Correo[0] desa=Correo[1] if "." in desa: txfin=desa.split('.') os=txfin[0] extencion=txfin[1] print (...
#GAME from data import * from functions import * game_username = ask_username() game_scores = get_scores() if game_username not in game_scores.keys(): game_scores[game_username] = 0 continue_game = True while continue_game == True: print("Player {0}: {1} points\n".format(game_username,game_scores[...
#Create a class to build a new dictionary for answer number and play input number #import rand as r #secret=r.rnumlistwithoutreplacement(4,0,7) class dictionary(dict): # __init__ function def __init__(self): self = dict() # Function to add key:value def add(self, key, v...
import mainloop import color def defaultsetting(): digit=4 lower=0 upper=7 attempt=10 return (digit, lower, upper, attempt) player=input("----------Welcome to MasterMind Game-----------\nWhat's your name?") print("Hi,", player, "! Below is the Main Menu:") instru='''-------------------Main Menu----------------...
#coding: utf-8 from datetime import datetime from datetime import date from datetime import timedelta class MyDateClass(object): def __init__(self): self.TDY = date.today() #self.TDY = datetime.today() self.YYYYMMDD = None self.MM = None self.YYYYMM = None self.y...
n = int(input()) mydict = {} all_parents_dict = {} for i in range(n): str = input().split(':') print(str) if len(str) == 1: mydict[str[0]] = [] else: mydict[str[0].strip()] = str[1].strip().split() print(mydict) for key, value in mydict.items(): all_parents_dict[key] = [] if len...
def sort(a, p, r): if p < r: q = (p + r) // 2 sort(a, p, q) sort(a, q + 1, r) merge(a, p, q, r) def merge(a, p, q, r): left_copy = a[p:q + 1] right_copy = a[q + 1:r + 1] left_copy_index = 0 right_copy_index = 0 sorted_index = p while left_copy_index < len(le...
"""If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.""" def multipliers(muls): arr=[]; for mul in range(1,muls+1): if((mul%3==0) or (mul%5==0)): arr.append(mul) prin...
''' POWER DIGIT SUM 2**15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 2**1000? ''' def pow_dig_sum(base,exp): add=0 a=(base**exp) while (a!=0): add=add+int(a%10) a=(a//10) return(add) if __name__=="__main__": print(pow_di...
#!/usr/bin/python ''' quick inversion for specific element with tridiagonalized matrix. In the following description, we take p -> the block dimension, N -> the matrix dimension and n = N/p. *references*: * http://dx.doi.org/10.1137/0613045 * http://dx.doi.org/10.1016/j.amc.2005.11.098 ''' from numpy import ...
''' Linear algebra for block and tridiagonal matrices. In the following description, we take p -> the block dimension, N -> the matrix dimension and n = N/p. ''' from numpy.linalg import inv from numpy import * from scipy.sparse import coo_matrix,bsr_matrix,csr_matrix,block_diag from scipy.sparse import bmat as sbmat...
from reading import * from database import * # Below, write: # *The cartesian_product function # *All other functions and helper functions # *Main code that obtains queries from the keyboard, # processes them, and uses the below function to output csv results def split_query(user_input_query): '''(str) -> dict ...
#crear una calculadora #numero uno input( "ingresa el numero 1: ") #numero dos numero2 = input("ingresa numero 2: ") #operaciones #resultados
def select(mat, point0, point1): xmax = max(point0[0], point1[0]) xmin = min(point0[0], point1[0]) ymax = max(point0[1], point1[1]) ymin = min(point0[1], point1[1]) print(xmin, ":", xmax) print(ymin, ":", ymax) return mat[ymin:ymax, xmin:xmax]
import sys if sys.argv[1] != "": print "hello " + sys.argv[1] a ={} a["the"] = 1 a["boy"] = 0 a["is"] = 2 a["the"] = 5 print a.keys() print a.values()
import pandas as pd import nltk from nltk.tokenize import RegexpTokenizer import io import dataLoadModule import constants def get_countries(): countries = set() with open(constants.country_list, 'r') as f: for country in f.readlines(): countries.add(country.strip()) return countries...
"""This class is used to represent how classy someone or something is. "Classy" is interchangable with "fancy". If you add fancy-looking items, you will increase your "classiness". A function is created in "Classy" that takes a string as input and adds it to the "items" list. Another function calculates the "cla...
# O(n^2) time, O(1) space def longestPalindromicSubstring(string): if len(string) < 2: return string current_longest = [0, 0] for i in range(len(string)): odd = getPalindrome(string, i-1, i+1) even = getPalindrome(string, i-1, i) longer = max(odd, even, key=lambda x: x[1] - x[0]) current_longest...
class MyQueue: def __init__(self): self.inputStack = [] self.outputStack = [] def push(self, x: int) -> None: self.inputStack.append(x) def pop(self) -> int: if len(self.outputStack): return self.outputStack.pop() while len(self.inputStack): ...
# O(n) time and space def balancedBrackets(string): stack = [] openBrackets = '([{' closingBrackets = ')}]' pairs = {')': '(', '}': '{', ']': '['} for char in string: if char in openBrackets: stack.append(char) elif char in closingBrackets: if not len(stack) ...
# O(n) time, O(h) space def is_symmetric(root): if not root: return True return check_symmetry(root.left, root.right) def check_symmetry(left_node, right_node): if not left_node and not right_node: return True elif (not left and right) or (left and not right): return False ...
class MinMaxStack: def __init__(self): self.minValues = [float("inf")] self.maxValues = [float("-inf")] self.stack = [] def peek(self): if len(self.stack): return self.stack[-1] def pop(self): if len(self.stack): removed = self.stack.pop() if removed == self.minValues[-1]: ...
# O(c) time | O(1) space: c= total length of all the words in the input list added together # build graph, char1->char2 # track in_Degree, unique chars # remove edges, no_dep_letters # check len(order) and len(chars) from collections import defaultdict class Solution: def alienOrder(self, words: List[str]) -> str:...
# O(n) time | O(1) space def bracket_match(text): closing_brackets = 0 opening_brackets = 0 for brackets in text: if brackets == '(': closing_brackets += 1 else: closing_brackets -= 1 if closing_brackets == -1: opening_brackets += 1 closing_brackets = 0 return opening_...
class Node(object): def __init__(self,val): self.val = val self.next = None class SinglyLinkedList(object): def __init__(self): self.head = None self.tail = None self.size = 0 def length(self): return self.size # O(1) def insertAtStart(self,val): ...
def merge(left, right): result = [] i, j = 0, 0 while (len(result) < len(left) + len(right)): if left[i].split(' ')[1] < right[j].split(' ')[1]: #sort by age first result.append(left[i]) i+= 1 elif left[i].split(' ')[1] == right[j].split(' ')[1]: #if the age are same,...
import random EMPTY_MARK = 'empty' MOVES = { 'w': (lambda e: e // 4 == 0, -4), 's': (lambda e: e // 4 == 3, 4), 'd': (lambda e: e % 4 == 3, 1), 'a': (lambda e: e % 4 == 0, -1), } def shuffle_field(): numbers = list(range(16)) random.shuffle(numbers) empty_index = random.randint(0, 16) ...
import datetime #This is the my mystery function that will give a score to each string def mystery_score(mystr): # z is the highest character we want - totalScore = ord("z") charsum = 1 for ch in mystr: charsum += ord(ch) return charsum/totalScore if __name__ == "__main__": string= ...
# Danhel Alejandro Mercado Velasco # mision 10 equipos de football # liga BBVA import matplotlib.pyplot as plot # Mostrar el nombre de los equipos ordenadamente def listarEquiposOrdenados(nombreArchivo): entrada = open(nombreArchivo, "r") entrada.readline() entrada.readline() listaEquipos =...
import re from parler.dataType.hashtags import Hashtags from parler.dataType.hashtag import Hashtag class HashtagsParser: ''' Parses all hashtags from the given text. ''' def __init__(self, text): self.text = text if text is not None else "" def parse(self): ''' Helper f...
import RPi.GPIO as GPIO import time # blinking function def blink(pin): GPIO.output(pin,GPIO.HIGH) time.sleep(1) GPIO.output(pin,GPIO.LOW) time.sleep(1) return # to use Raspberry Pi board pin numbers GPIO.setmode(GPIO.BOARD) # set up GPIO output channel GP...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' This file contains the logic and scoring functions for each Pichu piece. Internally, we represented each bird as its equivalent Chess piece, but for the record, here is how we assigned each bird: P/p = Parakeet = Pawn R/r = Robin = Rook B/b = Bluejay = Bishop Q/q = Q...
def addspace(x): k = 0 length = len(x) currentstring = "" while k < length: currentstring = str(x[k]) + " " + currentstring k = k + 1 print(currentstring)
""" start point = 문제 = https://programmers.co.kr/learn/courses/30/lessons/42578# 정답 = https://programmers.co.kr/learn/courses/30/lessons/42578/solution_groups?language=python3 포모도로 = 4 결국 남의 코드 보고 품... 근데 코드작성 문제가 아니라 문제 자체를 어렵게 생각해서 그런거같음 내가 논리적으로 풀이를 못하네. 수학을 공부해야하나.. 너무 어려운걸, 문제를 쉽게 생각하자 쉽게게 """ clothesA = [["yell...
""" Rabbit MQ server - tutorial first part of this using RabbitMQ and send a single message to queue To do these, we need to establish a connection with Rabbit MQ sever *Description RabbitMQ server : Broker between producer(sender) and customer(reciever) pika : protocol """ import pika connection = pika.BlockingCon...
# D. verbing # Given a string, if its length is at least 3, # add 'ing' to its end. # Unless it already ends in 'ing', in which case # add 'ly' instead. # If the string length is less than 3, leave it unchanged. # Return the resulting string. def verbing(s): # +++your code here+++ i = 'ing' y = 'l...
def mix_up(a, b): return " ".join(("".join((b[:2], a[2:])), "".join((a[:2], b[2:])))) def test(got, expected): if got == expected: prefix = ' OK ' else: prefix = ' X ' print('%s got: %s expected: %s' % (prefix, repr(got), repr(expected))) # Provided main() calls the ab...
# PR hitung julah huruf 'c' dan kata 'startup' nama = 'Purwadhika Startup & Coding School' countc = nama.count('c') countstartup = nama.count('Startup') findc = nama.find('h') countspace = nama.count(' ') print (str(countstartup)*3) print (countc) print (findc) print (countspace) ####################### #Jumlah huruf...
''' class X: def __init__ (self, nama): self.nama = nama class Y(X): def __init__ (self,nama,gelar): X.__init__(self,nama) class Y(X): def __init__ (self,nama,gelar, univ): X.__init__(self,nama) self.gelar = gelar self.kampus = univ # class Y(X): # def __ini...
import pandas import pandasql weather_data = pandas.read_csv('../podaci/weather-underground.csv') # SQL query should return one column and one row - a count of the number of days in the dataframe where the rain column is equal to 1 (days it rained) q = """ SELECT COUNT(*) FROM weather_data WHERE rain = 1 """ rainy_...
# Создайте словарь типа "вопрос": "ответ", например: {"Как дела": "Хорошо!", "Что делаешь?": "Программирую"} и так далее. # Напишите функцию ask_user() которая с помощью функции input() просит пользователя ввести вопрос, # а затем, если вопрос есть в словаре, программа давала ему соотвествующий ответ. Например: # Польз...
""" Mykola Kryvyi Lab 0.1 Github link: https://github.com/mykolakryvyi/skyscrapers.git """ def read_input(path: str): """ Read game board file from path. Return list of str. """ file = open(path , 'r') contents = file.readlines() contents = list(map(lambda x: x.strip(),contents)) return ...
#Tuple Unpacking: assigning of tuples elements to variables. #note: count of variables must to equals to count of element else it will through an error like : "Too many tuples to unpack" # Example days = ("Mon","Tues","Wed") print(days) #now lets unpack it day1,day2,day3 = (days) #here tuples elements are ass...
#Range() Function: to generate a range of list Number_List = list(range(1,11)) print(Number_List)
#Natural Language Processing : is manily used to process free text or content or any kind of document to understand the person's #thoughts and thinking. Basically analysing sentences and words of any person. #before you start , please download nltk entire supporting packages. # install nltk package # > pip inst...
#Index() Function : to find the position of the element. You can define start and end as well to the index position Number = list(range(1,11)) print(Number) print(Number.index(5,1,10))
#**************Center Method************ Name = input("enter your name : ") print(Name.center(len(Name)+8,"*"))
#Sorting List: it sort the list and changes the original list as well. fruits = ["Apple","Orange","Mango","Banana","Apple","Orange","Pineapple"] fruits.sort() print(fruits) Numbers = [3,5,2,4,1,6,8,7,] Numbers.sort() print(Numbers) #sorted() method : it sorts the list but wont change the original list ...
#Keys in Dictionary #we can check if key is present in dictionary or not #Example: User= { "Name":"Sanju", "Age": 25 } print(User) #IF Condition to check if key is there or not if "Name" in User: print("Key present") else: print("No Key Found") #We can also check i...
# String Formating : using place holder {} we can pass the variable value without converting it into str value while printing the output Name = "Sanju" Age = 25 print(f"My name is {Name} and Age is {Age}") # if you want to increase age by 2 so we can do that calculation as well print(f"My name is {Name} and Age ...
#Functions: it helps in avoiding writting same taks code again and again by defining function and call it whenever it requires #Example: suppose you have a senario where you always want to sum two numbers def Sum_Number(Num1,Num2): return(Num1+Num2) Get_Total = Sum_Number(2,2) print(Get_Total) #Exampl...
""" Code for maximizing a convex function over a polytope, as defined by a set of linear equalities and inequalities. This uses the fact that the maximum of a convex function over a polytope will be achieved at one of the extreme points of the polytope. Thus, the maximization is done by taking a system of linear ineq...
# # -*- coding: utf-8 -* try: import tkinter as tkinter # for python 3.x import tkinter.messagebox as mb except: import Tkinter as tkinter # for python 2.x import tkMessageBox as mb import random, time ''' 欢迎关注 微信公众号菜鸟学Python 更多好玩有趣的实战项目 ''' class Ball(): ball_num = 0 gap = 1 ball_hit_...
# A Mad Libs-like program. #!/usr/bin/python print "Welcome to Mad Libs!" main_char = raw_input("Enter a name: ") adj_1 = raw_input("Enter an adjective: ") adj_2 = raw_input("Enter a second adjective: ") adj_3 = raw_input("Enter one more adjective: ") verb_1 = raw_input("Enter a verb: ") verb_2 = raw_input("Enter a ...
#!/usr/bin/python3 # Script to demonstrate Python comparison and boolean operators. import random # Some relationals. Relationals in Python can be chained, and are # interpreted with an implicit and. c = -2 for a in range(1,4): c = c + 4 for b in range(1,4): print('(' + str(a), '<', str(b) + ') ==', ...
#!/usr/bin/python3 # Script to copy standard input to standard output, one line at a time, # now using a break. import sys # Loop until terminated by the break statement. while 1: # Get the line, exit if none. line = sys.stdin.readline() if not line: break # Print the line read. print(li...
''' Script for caching three graphs from one of the examples from the post [1], for use in an interactive post. [1] https://jessicastringham.net/2019/07/01/systems-modeling-from-scratch/ ''' import numpy as np import json from model_simulation import * # In this model, fish regenerate slower if there aren't many o...
from sklearn import linear_model N=input().split() m=int(N[0]) #number of independepent variable n=int(N[1]) # number of dataset X=[] Y=[] for _ in range(n): l=list(map(float,input().strip().split(' '))) X.append(l[0:len(l)-1])#Exluding last number for getting x values Y.append(l[len(l)-1])# Gett...
#!/usr/bin/env python # coding: utf-8 # SVM Algorithm: # ->It is a Supervised Macine Learning algorithm # -> SVM offers very high accuracy as compared to other classifiers such as Logistic Regression and Decision trees # # ->It is used in variety of application such as face detection , intrusion detection, cla...
# coding: utf-8 # # simplified Confident Learning Tutorial # *Author: Curtis G. Northcutt, cgn@mit.edu* # In this tutorial, we show how to implement confident learning without using cleanlab (for the most part). # This tutorial is to confident learning what this tutorial # https://pytorch.org/tutorials/beginner/exa...
# Author: Michael R.Sorell # Fundamentals of Computing: Interactive Programming (Part 1) # 8 November 2018 # template for "Stopwatch: The Game" import simplegui import random # define global variables count_message = "" position = [250,250] width= 500 height= 500 interval = 100 # program 100 counter=0 y=0 x=0 ms = ...
from individual import Individual from fitnesscalculator import FitnessCalculator class Population: fit = FitnessCalculator() def __init__(self, populationSize = 30, initialize = True): self.individuals = [] if initialize: for i in xrange(populationSize): self.individuals += [Individual()] def size(...
# ---------------------------------------------------------------------------- # # Title: Assignment 07 # Description: This program demonstrates the concepts of error # handling and pickling. The user will be presented # a menu with 3 options: (1) Error Handling Demo; # (2) ...
# -------------- # User Instructions # # Write a function, inverse, which takes as input a monotonically # increasing (always increasing) function that is defined on the # non-negative numbers. The runtime of your program should be # proportional to the LOGARITHM of the input. You may want to # do some research into bi...