text
stringlengths
37
1.41M
a = 0 x = 0 for i in range(10): a = int(input("Введите число :")) x += a y = x / 10 print(y)
x = int(input("введите число ")) y = int(input("введите число ")) if x % 2 != 0 and y % 2 != 0: print(x, y) else: print("(((((")
# Tam Fredrick Kofi # Date: 21/09/2014 # file: kofi.py # UNI: fkt2105 # #*************************************** ### question 3 ### Python programme to find your age in days ### Greet the person print( '''Hello there, I hope you are fine! Let me help me you to find your age in days''') ### Ask for name of per...
import random giving_up = 0 def wake_up(): global giving_up print "When I woke up..." late_for_class = random.randint (0,6) if late_for_class == 1: giving_up += 5 print "I was late for class." stuff_due = random.randint (0,5) if stuff_due == 1: giving_up += 5 pr...
from numpy import sin, cos import matplotlib.pyplot as plt import scipy.integrate as integrate import matplotlib.animation as animation import matplotlib import matplotlib.pyplot as plt import numpy as np def multiplot(x1, y1, y1_2, x2, y2, y2_2, color1="blue", color2="orange", subtitle="", x1_label=""...
from tkinter import * def function(): print("that is function") root = Tk() myInput = Entry(root, text= "Click ME", width=100, bg='white', fg='black', borderwidth=5) myInput.pack() root.mainloop()
"""Using stacked decorators""" def bold(func): """Decorator function""" def wrapper(): """Decorator wrapper - the actual decorator""" return "<b>" + func() + "</b>" return wrapper def italic(func): """Decorator function""" def wrapper(): """Decorator wrapper - the actual de...
from tkinter import* import sqlite3 import tkinter.ttk as ttk import tkinter.messagebox as tkMessageBox root = Tk() root.title("Python: Simple CRUD Applition") screen_width = root.winfo_screenwidth() screen_height = root.winfo_screenheight() width = 700 height = 400 x = (screen_width/2) - (width/2) y = (screen_height/...
#List, Dictionary and Iteration Review ################################################################################### LISTS ################################################################################### ##Create a list called group_names which includes the name of every person in our group. group_names = [...
#变量作用域 def func(num1): num2=30 #python会在局部中复制全局变量,自动创建内部用 print(num1) print(num2) num2=20 func(10) print(num2);
#删除链表中的节点 #请编写一个函数,使其可以删除某个链表中给定的(非末尾)节点,你将只被给定要求被删除的节点。 #现有一个链表 -- head = [4,5,1,9],它可以表示为: # 4 -> 5 -> 1 -> 9 class Solution: def deleteNode(self, node): node.val=node.next.val#当前值被后一个值覆盖 node.next=node.next.next#下一节点跳到下下一节点
# 有效的字母异位词 #给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的一个字母异位词。 #示例 1: #输入: s = "anagram", t = "nagaram" #输出: true #示例 2: #输入: s = "rat", t = "car" #输出: false #说明: #你可以假设字符串只包含小写字母。 #进阶: #如果输入字符串包含 unicode 字符怎么办?你能否调整你的解法来应对这种情况? import collections class Solution: def isAnagram(self, s, t): if len(s) == len(t): dict ...
def ds(x): return 2*x+1 lambda x:2*x+1 g=lambda x,y:x+y print(g(3,4)) #内置函数filter过滤器,去掉非True的 print('=================') def odd(x): return x%2 temp = range(10) show = filter(odd,temp) print(list(show)) print(list(filter(lambda x : x%2,range(10)))) print(list(range(10))) print('=================') #内置函数map print(...
import random ## This is guess the number game print('Hello !!! What is your name ???') name = input() secnum = random.randint(1,20) print('Well,'+ name + ' ....I am thinking of number between 1 - 20') ##This is allowing user to guess the number (max guess --> 6) print('You have six guesses !!!') for i in range (1,7)...
from scipy import misc def chebyshev(x0,count): x1=x0-(f(x0)/fprime(x0))+(1/2)*((f(x0)**2)*fdprime(x0))/(fprime(x0))**3 print('f(x1),f(x0):{},{} and x1,x0:{},{}'.format(f(x1),f(x0),x1,x0)) count+=1 print('In the {} iteration, value of x{} is {}'.format(count,count,x1)) if f(x1)==0: print(...
grade1 = float(input("Type the grade of the first test: ")) grade2 = float(input("Type the grade of the second test: ")) abscenes = int(input("Type the number of abscenes: ")) total_classes = int(input("Type the total number of classes: ")) avg_grade = (grade1 + grade2) / 2 attendance = (total_classes - abscenes) / to...
def say_hello(): print("Hello!") def say_hello_arguments(person1, person2): print("Hello " + person1 + ", how are you doing? " + person2 + " is waiting for you.") def fahrTocelsius(fahr): celsius = (5 * (fahr - 32)) / 9 return celsius say_hello() person1 = "Marcia" person2 = "Luciano" say_hello_argum...
ALPHABET = (('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'), ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z')) def co...
#source file is from #http://stackoverflow.com/questions/12090503/listing-available-com-ports-with-python ''' This program should list out the serial port names to figure out what are the port names used to connect to mac (darwin), linux and windows. port names are needed to connnect to bluetooth device, as once pa...
""" Can you check to see if a string has the same amount of 'x's and 'o's? Eg: XO("ooxx") => true XO("xooxx") => false XO("ooxXm") => true XO("zpzpzpp") => true // when no 'x' and 'o' is present should return true XO("zzoo") => false Note: The method must return a boolean and be case insensitive. ...
""" Your goal is to create a function that removes the first and last letters of a string. Strings with two characters or less are considered invalid. You can choose to have your function return null or simply ignore. """ def solution(somestr): if len(somestr) > 2: return somestr[1:-1] return None def...
""" Given a 32-bit signed integer, reverse digits of an integer. Example 1: Input: 123 Output: 321 Example 2: Input: -123 Output: -321 Example 3: Input: 120 Output: 21 """ def reverse_dig(num): num = str(num) if num.startswith('-'): return int('-'+num.split('-')[1][::-1]) else: return i...
import math def normalize_angle(p): if p > 180: return p - 360 if p < - 180: return p + 360 else: return p theta = 0 target = int(raw_input("target>")) error = target - theta a_error = abs(error) if a_error >= 90: error = normalize_angle(180 - error) a_error = abs(error) ...
############################################################################### # Computer Project #8 # # Algorithm # prompt for a file containing hurricane information # form a dictionary using the names, years, and data of the hurricane # update the dictionary for every name & ...
# find the largest number in an array def find_largest(alist): if len(alist) == 1: return alist[0] elif alist[0]>find_largest(alist[1:]): return alist[0] else: return find_largest(alist[1:]) list = [5, 1, 8, 7, 2] print(find_largest(list))
class Day1: def __init__(self): self.inputs = [] with open("inputs/1.txt") as f: for line in f: self.inputs.append(int(line.strip())) def part1(self): seen_nums = set() for num in self.inputs: if (2020 - num) in seen_nums: ...
#!/usr/bin/env python import sys sys.path.append( '../' ) from rtfng import * SAMPLE_PARA = """The play opens one year after the death of Richard II, and King Henry is making plans for a crusade to the Holy Land to cleanse himself of the guilt he feels over the usurpation of Richard's crown. But the crusade must be ...
import random def r11_is_multiple(n: int,m: int): return n/m == int(n/m) def r12_is_even(k): return divmod(k,2)[1] == 0 def r13_minmax(data): sorteddata = sorted(data) return (sorteddata[0],sorteddata[-1]) def sq_of_num(num): return num ** 2 def r14_sq_less_n(n): sumOfSquares = 0 while n...
class Point: """Represents a point in a 2 dimensional space """ def __init__(self, x=0, y=0): self.x = x self.y = y def __str__(self): return '(' + str(self.x) + ', ' + str(self.y) + ')' def __add__(self, self1): return Point(self.x + self1.x, self.y + se...
import numpy as np def load_data(mode='train'): """ Function to (download and) load the MNIST data :param mode: train or test :return: images and the corresponding labels """ from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot...
import tensorflow as tf import numpy as np # Create input data # Lets say you have a batch of two examples, one is of length 10, and the other of length 6. # Each one is a vector of 8 numbers (time-steps=8) X = np.random.randn(2, 10, 8) # [batch_size, max_time (or length), input_dim] # The second example is of...
import numpy as np def loss_surface(model_parameters, target_weights, target_ix, model, y): """ Function to return the cost surface between two chosen weights in a model and its L2 loss surface. Parameters ---------- model_parameters: tuple containing the parameters to compute the model ...
def quickSort(aArray): quickSortHelper(aArray, 0, len(aArray)-1) def quickSortHelper(aArray, first, last): if first < last: splitpoint = partition(aArray, first, last) quickSortHelper(aArray, first, splitpoint-1) quickSortHelper(aArray, splitpoint+1, last) def partition(aArray, fir...
def champion_search(api,summoner_id,active=False): if not active: print 'This program is inactive' print 'Exiting...' return stat_ranked = api.get_stats_ranked(summoner_id) #won't work if you haven't played ranked before ranked_champions={} count=1 for champion in stat_ranked['...
from tkinter import * root = Tk() root.title("simle calculator") e = Entry(root, width=60, borderwidth=5) e.grid(row=0, column=0, rowspan=2, columnspan=5, padx=10, pady=10) def button_click(number): current = e.get() global expr expr = str(current)+str(number) e.delete(0, END) e.insert(0, expr)...
## Accepts a list of numbers as an argument and returns the smallest number on list. number_list = [10, 4, 35340, -3, 16, 75, 82, 0] def smallest(list): ## Define function that returns smallest number. small_number = number_list[0] ## Must set intial check number to first number in list. ## Loop interate troug...
#!/usr/bin/env python3 dic = { '\\' : b'\xe2\x95\x9a', '-' : b'\xe2\x95\x90', '/' : b'\xe2\x95\x9d', '|' : b'\xe2\x95\x91', '+' : b'\xe2\x95\x94', '%' : b'\xe2\x95\x97', } def decode(x): return (''.join(dic.get(i, i.encode('utf-8')).decode('utf-8') for i in x)) def input1(text): print(decode('+-------------...
print('Common Multiples') def ismultiple(num_a, num_b):# Takes two numbers as arguement if num_b % num_a == 0: # if num_b divided by num_a returns a number with a remainer of 0 return True # return true else: return False # otherwise return false def commonmultiple(num_a, num_b, num_c)...
print('Trip Distance Calculator') import math first_city = [0,0] second_city = [0,0] choice = "" distance = 0.0 first_city[0] = int(input('Enter x coordinate of first city: ')) first_city[1] = int(input('Enter y coordinate of first city: ')) while choice != 'q': second_city[0] = int(input('Enter x coordina...
import random def create_sorted_list(range_of_nums): numslist = [] for x in range(range_of_nums): if random.randint(0,100) > 75: numslist.append(x) return numslist def create_unsorted_list(length, maxval): numslist = [] for x in range(length): nums...
import listmaker def merge_lists(list1, list2, merged=[]): if len(list1) == 0: merged.extend(list2) return merged elif len(list2) == 0: merged.extend(list1) return merged if list1[0] <= list2[0]: merged.append(list1[0]) return merge_lists(list1[1:]...
print('Number of Digits') def numDigits(num): # takes a string as an arguement num = str(num) # converts string to integer value count = 0 # variable to hold the count of digits for x in num: # for every character in the num string count += 1 # increase count by 1 return count # return t...
largest, smallest, average, total, positive, negative = 0,0,0,0,0,0 num = input('Enter an integer: ') if num == 'q': print('Largest number: ' + str(largest)) print('Smallest number: ' + str(smallest)) print('Average: ' + str(average)) print('Number of positives: ' + str(positive)) print('Numb...
""" 14. mimic Neste desafio você vai fazer um gerador de lero-lero. É um programa que lê um arquivo, armazena a relação entre as palavras e então gera um novo texto respeitando essas relações para imitar um escritor de verdade. Para isso você precisa: A. Abrir o arquivo especificado via linha de comando. B. Ler o ...
"""Utility module""" def list_to_dict(items: list) -> dict: """Transform a list to a dict with keys derived from indexes""" dict_values = {} for idx, value in enumerate(items): dict_values[idx] = value return dict_values
#!/usr/bin/env python import os #import numpy #import csv myfilename = "housing.data.txt" # if os.path.isfile(myfilename): # print("yay, I have a file") # if sky == blue: # print('yay the sky is blue') # else: # print ('boo, no files for me') with open(myfilename, 'r') as file_handle: housinglist = [] fo...
import numpy as np import os import copy def basic_tokenized(): ''' Counts the number of unique words in a given input text And converts the text into sequences of numbers that correspond to words Arguments: (none) Return: word_dict - A list of words where the index correspondin...
# -*- coding: utf-8 -*- """ Created on Mon May 6 2019 @author: Seahymn, Daniel Lin """ import pickle import csv import os import pandas as pd # Separate '(', ')', '{', '}', '*', '/', '+', '-', '=', ';', '[', ']' characters. def SplitCharacters(str_to_split): #Character_sets = ['(', ')', '{', '}', '*', '/', '+', '...
#send email through python through tls #reference: https://realpython.com/python-send-email/ import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart sender_email = "sender@domain.com" receiver_email = "receiver@gmail.com" password = input("Type your password and press enter:...
# Programá una función ord_burbujeo(lista) que implemente este método # de ordenamiento. ¿Cuántas comparaciones realiza esta función en una lista de largo n? lista_1 = [1, 2, -3, 8, 1, 5] lista_2 = [1, 2, 3, 4, 5] lista_3 = [0, 9, 3, 8, 5, 3, 2, 4] lista_4 = [10, 8, 6, 2, -2, -5] lista_5 = [2, 5, 1, 0] # Agrego otra ...
''' Las columnas en camion.csv corresponden a un nombre de fruta, una cantidad de cajones cargados en el camión, y un precio de compra por cada cajón de ese grupo. Escribí un programa llamado costo_camion.py que abra el archivo, lea las líneas, y calcule el precio pagado por los cajones cargados en el camión. ''' impor...
#http://projecteuler.net/problem=7 #By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. #What is the 10 001st prime number? #bruteforce power primes = [] num = 2 def is_prime(n): for prime in primes: if n % prime == 0: return False retur...
# A Dictionary is a collection which is unordered, changeable and indexed. No duplicate members. # similar to an object literal # Create dict person = { 'first_name': 'John', 'last_name': 'Doe', 'age': 30 } # trying to access a key they doesn't exist ex: 'gender' returns KeyError # Use constructor # per...
"""Draws echograms of NumPy ndarrays as used in the echonix library. """ import matplotlib.pyplot as plt import matplotlib.colors as colors import numpy as np import numpy.ma as ma import math def ek500(): """ek500 - return a 13x3 array of RGB values representing the Simrad EK500 color table """ rgb = ...
''' This is the python solution for the following hackerrank question: https://www.hackerrank.com/challenges/merge-the-tools/problem ''' def merge_the_tools(string, k): substrs = list() substr = list() final_s = list() for i in range(0,len(string),k): substrs.append(string...
#/usr/bin/python class Employee: raise_amount = 1.04 No_of_emps = 0 def __init__(self, first, last, salery): self.fname = first self.lname = last self.pay = salery self.email = first + last + '@netmagic.com' Employee.No_of_emps += 1 def fullname(self): ...
#!C:\Python27\python.exe # -*-coding: utf-8 -*- import math var1 = raw_input("eneter the value?. ") def factorial(n): if int(n) < 0: print "Factorial is only defined for positive integers." return -1 elif int(n) == 0: return 1 elif int(...
##Fibonacci series program ##a series of numbers in which each number ( Fibonacci number ) is ##the sum of the two preceding numbers. The simplest is the series ##1, 1, 2, 3, 5, 8, etc. ## Program to display the Fibonacci sequence up to n-th term ##where n is provided by the user. x = int(input("enter the n-th ...
WHITE = "WHITE" BLACK = "BLACK" GREY = "GREY" TIME = 0 class Vertex: def __init__(self, key): self.key = key self.adjlist = {} def display(self): print "Key = %s\tEdges = %s" % (self.key, str(self.adjlist.keys())) def __repr__(self): return "%s: %s" % (str(self.key), str(...
import random def get_data(): """返回0到9之间的3个随机数""" return random.sample(range(10), 3) def consume(): """显示每次传入的整数列表的动态平均值""" running_sum = 0 data_items_seen = 0 while True: data = yield #生成器接收点 关键点 data_items_seen += len(data) # 每次调用值将会保留,下次执行的时候将会调用该值 running_sum...
#!/usr/bin/python3 # 功能:登陆login/register user_data = {} '提示' def tip(): print("###### 新建用户:N/n ######") print("###### 登陆用户:E/e ######") print("###### 登陆用户:Q/q ######") '注册模块' def reg(): name = input("请输入注册名用户名") while True: if name in user_data: name = input("用户名已被占用,请重新输入:") ...
#!/usr/bin/python3 #功能:内嵌函数与闭包使用 #""" 内嵌函数 """ def fun1(): print("Fun1 主函数被调用") def fun2(): print("Fun2 内嵌函数正在被调用\n") fun2() #内部函数(内嵌函数),只能由fun1()调用 fun1() #"""闭包""" def funX(x): def funY(y): return x * y return funY i = funX(8) print("i的类型 :",type(i)) print("8 * 5 =",i(5)) # 4...
#!/usr/bin/python3 #功能:递归汉诺塔 def haoni(n,x,y,z): if n == 1: print(x,'-->',z) else: haoni(n-1,x,z,y) #前n-1从x移动到y上 print(x,'-->',z) #将最底下盘子从x移动到z上 haoni(n-1,y,x,z) #将y上的n-1盘中移动到z上 haoni(3,'a','b','c') print(list('123456799')) print(tuple([1,2,3,5])) #冻结集合(使其不能正常添加与删除元素) nu...
#!/usr/bin/python3 #功能:课后作业 # try: # for i in range(3): # for j in range(3): # if i == 2: # raise KeyboardInterrupt('') # print(i,j) # except KeyboardInterrupt: # print("异常中断结束") try: f = open('My_File.txt') # 当前文件夹中并不存在"My_File.txt"这个文件T_T (而且是一个局部变量) ...
class Counter: def __init__(self): self.counter = 0 # 这里会触发 __setattr__ 调用 def __setattr__(self, name, value): self.counter += 1 # 既然需要 __setattr__ 调用后才能真正设置 self.counter 的值,所以这时候 self.counter 还没有定义,所以没法 += 1,错误的根源。””” super().__setattr__(name, value) ...
#!/usr/bin/python3 #功能:课后作业03 import random name = input("请输入您的姓名:") num = input('请输入一个1~100的数中:') num = int(num) if num > random.randint(0,100): print("恭喜您:" + name,"您输入的数字"+ num +"大于随机数") else: print("不能恭喜您了",name) #所见即所得 string = """ WeiyiGeek, Python, 脚本语言. """ print(string) #需要进行转义才行 string = ( "我爱鱼C,\n...
#!/usr/bin/python3 #功能: import random as r class Fish: def __init__(self): self.x = r.randint(0,10) self.y = r.randint(0,10) def move(self): self.x -= 1 print("我得位置是:",self.x,self.y) class Shark(Fish): def __init__(self): super().__init__() #方法1:只需要传入父类...
#!/usr/bin/python3 #coding:utf-8 #功能:分支与循环 #-----------if 语句----------------- guess = 8 temp = int(input("请输入一个1-10数值:")) if guess == temp: print("恭喜您,输入的数值刚好") elif guess > temp: print("太遗憾了,输入的数值小于它") else: print("太遗憾了,输入的数值大于它") x,y = 1,3 print("#三元运算符 :",end="") print( x if x > 3 else y ) #----------...
#!/usr/bin/python3 #min 内置函数的实现 与 sum bug 解决 def min(x): initvalue = x[0] for each in x: if each < initvalue: #实际采用的ASCII进行比对的 initvalue = each else: print("计算成功") return initvalue print(min('178546810')) def sum(x): result = 0 for each in x: if isinstance...
# -*- coding: utf8 -*- origin = (0,0) legalx = [-100,100] legaly = [-100,100] def create(posx=0,posy=0): def moving(direction,step): # direction参数设置方向,1为向右(向上),-1为向左(向下),0为不移动 # step参数设置移动的距离 nonlocal posx,posy newx = posx + direction[0] * step newy = posy + direction[1] * step ...
#!/usr/bin/python class MyDes: def __init__(self, value = None): self.val = value def __get__(self, instance, owner): return self.val ** 2 class Test(MyDes): x = MyDes(3) test = Test() print(test.x)
#!/usr/bin/python3 #功能:Python对象编程学习 # #/***类封装**/# # class Person: # name = 'Weiyigeek' # age = 20 # msg = 'I Love Python' # def detail(self): # print('姓名 :',self.name,"年龄:",self.age, "爱好:",self.msg) # oop = Person() # oop.detail() # #/***类继承**/# # class mylist(list): # pass # list2 = my...
#!/usr/bin/python3 #功能:课后作业04 count = input("请输入显示*号的个数:") count = int(count) while count: print(' ' * (count - 1),'*' * count) count = count - 1 else: print("打印结束")
class Solution(object): def searchMatrix(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ r=len(matrix) if matrix: c=len(matrix[0]) else: c=0 l=r*c start=0 ...
class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ st=str(x) f=0 if st[0]=='-': f=1 st=st[1:] st=st[::-1] if f==1: x= int('-'+st) else: x= int...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None from collections import deque class Solution(object): def zigzagLevelOrder(self, root): """ :type root: TreeNode :rtype: L...
# Definition for an interval. # class Interval(object): # def __init__(self, s=0, e=0): # self.start = s # self.end = e class Solution(object): def eraseOverlapIntervals(self, intervals): """ :type intervals: List[Interval] :rtype: int """ intervals=sorte...
arr = [8,5,2,6,9,3,1,4,0,7,3,6,7,89,4,2,34,33333,1,3,5,67,78,6,0,0,1,3] def insertionSort(arr): for i in range(1, len(arr)): k = arr[i] j = i - 1 while j >= 0 and arr[j] > k: arr[j + 1] = arr[j] j = j - 1 arr[j + 1] = k return arr print(insertionSort(arr)...
class Comment(object): """ Youtube Comment class """ def __init__(self, text, comment_id, video_id, sentiment =''): """Method for initializing a Comment object Args: text (str) video_id (int) comment_id (str) Attributes: text : comment text video_id : unique video_id associated with the comm...
"""Reuben Koshy""" password = input("Enter a Password: ") while len(password) >= 0: if len(password) >= 8: print("Valid Password") print('*' * len(password)) break else: print("Invalid password. Must be at least 8 characters in length") password = input("Enter a Passwor...
import keras from keras import Sequential, Input # NNのモデルを作る際に使用 from keras.layers import Conv2D, MaxPooling2D # NNの部品 from keras.layers import Activation, Dropout, Flatten, Dense # NNの部品 Denseは全結合層 from keras.utils import np_utils # import numpy ...
""" Using Python 2.7, or 3.3-3.5 syntax/semantics, please fill out the bodies of the included functions to include implementations of what is described in the docstrings. You can test your answers against the __basic__ included unittests by running: `python -m doctest questions.py` """ from scipy.spatial.distance impo...
from gfxhat import lcd; from gfxhat import backlight; from time import sleep; import random; #CREATE A VERTICAL LINE def createVerticalLine(): lcd.clear(); lcd.show(); y = 0; x = int(input('Set the x cordinate for the vertical line: ')); while (y <= 63): lcd.set_pixel(x,y,1); y = y...
# -*- coding: utf-8 -*- """ Created on Mon Dec 09 21:45:18 2013 @author: Alejandro """ class Movilidad(object): """ Se define la movilidad de los agentes. """ def __init__(self, agentId): self.id = agentId self.agentId = agentId def getAgentId(self): return self....
#Make sure to un-comment the function line below when you are done. #Remember to name your function correctly. def bigger_guy(a, b): if a < b: return b else: return a #DO NOT remove lines below here,return max(1, 2, 3) #DO NOT remove lines be #this is designed to test your code. def test_bigger_...
class Mobil: def warna(self): print("Mobil x memiliki warna merah") class Xenia(Mobil): def warna(self): print("Mobil Xenia memiliki warna hitam") # Overriding digunakan untuk mengganti method induknya a = Xenia() a.warna() """ ========================================================== ================== ...
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ] tinylist = [123, 'john'] print list print list[0] print list[1:3] tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 ) list = [ 'abcd', 786 , 2.23, 'john', 70.2 ] print "3rd value in touple : ",tuple[2] tuple[2] = 1000 # Invalid syntax with tuple print "3rd value in...
########################################################################################### # Name: Garrett Miculek # # Date: 9-30-19 # # Description: Asking for a name and an a...
#!/usr/bin/env python # HW04_ex08_11 # The following functions are all intended to check whether a string contains # any lowercase letters, but at least some of them are wrong. For each function, # describe what the function actually does (assuming that the parameter is a # string). # Do not merely paste the output...
import numpy as np #np.linalg.norm returns one of seven different norms of a vector a=np.arange(9)-4 b=a.reshape((3,3)) L1=np.linalg.norm(a,1) L2=np.linalg.norm(a,2) print(L1) print(L2)
a=['first','second'] for index, item in enumerate(a): print(index) print(item)
import numpy as np import matplotlib.pyplot as plt a=[5,7,3,4,5] #by default there are gonna be 10 bins his,bins=np.histogram(a) #print(his) #print(bins) plt.hist(his,bins) plt.show() his,bins=np.histogram(a,density=True) plt.hist(his,bins) plt.show() his.bins=np.histogram(a,bins=[3,4,5,6,7],density=True) plt.hist(his...
import numpy as np x=np.array([8,1,3,5,2,9,6,4]) index=np.argsort(x) print(x) #argsort result in the index in ascending order print(index)
def wrap(string, max_width): chars = [] output = "" i = 0 j = max_width while j < len(string)+max_width : chars.append(string[i:j]) i += max_width j += max_width for i in chars: if chars.index(i) != len(chars)-1: output += (i + "\n") ...
f = raw_input('Enter file name :') fhand = open(f, "r") text = fhand.read() words = text.split() newDict = dict() for word in words: newDict[word] = None print newDict g = raw_input('Enter Key value :') print g in newDict
def listNumber(): b = 0 empList = [] while True: a = raw_input('Enter the number : ') if a == 'done': floatList = map(float, empList) print 'Maximum : ', max(floatList), "Minimum : ", min(floatList) break else: try: #b += float(a) empList.append(a) except: print('Invalid Input') ...
file1 = raw_input('Enter the file name: ') def fileName(file1): fh = open(file1, "r") el = [] for line in fh: f = line.split() el.extend(f) el.sort() print el fileName(file1)
""" // Time Complexity : o(n) // Space Complexity : o(n), dictionary // Did this code successfully run on Leetcode : yes // Any problem you faced while coding this : no // Your code here along with comments explaining your approach """ from collections import defaultdict """ # Definition for a Node. class Node: ...
from turtle import * import turtle speed(0) bgcolor("black") pensize(3) for x in range (5): for colors in ["red","pink","blue","cyan","green","yellow","white"]: color(colors) left(12) for i in range(4): forward(200) left(90) turtle.done()
import turtle turtle.title("@happy_coding") s = turtle.Screen() t = turtle.Turtle() def move_to(x,y): t.penup() t.goto(x,y) t.pendown() def draw_rectangle(a,b): t.begin_fill() t.forward(a) t.left(90) t.forward(b) t.left(90) t.forward(a) t.left(90) t.forward(b)...