text
stringlengths
37
1.41M
from array import * arr = array('i',[]) asize=int(input('Enter the size of array: ')) for i in range(asize): val = int(input('Enter the next Element: ')) arr.append(val) print(arr) afind = int(input('Enter Element to search:')) k=0 for e in arr: if e == afind: print(k) break k+=1...
class Computer: def __init__(self): self.name = "pratik" self.age = 23 def compare(self, other): if self.age == other.age: return True else: return False c1 = Computer() c1.name = "Navin" c1.age = 21 c2 = Computer() if c1.compare(c2): print("Age i...
MENU = { "espresso": { "ingredients": { "water": 50, "milk":50, "coffee": 18, }, "cost": 1.5, }, "latte": { "ingredients": { "water": 200, "milk": 150, "coffee": 24, }, "cost": 2.5, },...
import os import requests from bs4 import BeautifulSoup from Wiki_parse_1.app import db, Region, Country, DBNAME URL = "https://en.wikipedia.org/wiki/List_of_countries_and_dependencies_by_population" HEADERS = { "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrom...
import time def pow2sum(exp): L = [0] * exp # make a list exp long L[0] = 1 for power in range(exp): carry, add = 0, 0 for index in range(exp): prod = L[index] * 2 + carry if prod > 9: carry = 1 prod = prod % 10 else: carry = 0 L[index] = prod for i in range(exp): print(L[i]) print("...
def sort_by_highest_value(data): text = "" for key in sorted(data, key=lambda x: data[x], reverse=True): text+=("%s: %s, ") % (key, data[key]) return text def merge(d1, d2, merge_fn=lambda x,y: x+y): """ Merges two dictionaries, non-destructively, combining values on duplicate keys as defined by the...
f=int(input()) t=f temp=0 while t!=0: temp=temp*10+t%10 t=t//10 if f==temp: print("yes") else: print("no")
# 8.4 Open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split() method. # The program should build a list of words. For each word on each line check to see if the word is already in the list and if not append it to the list. # When the program completes, so...
def binary_search(x, error): """sqrt via binary search, with error margin""" if x < 0: return -1 else: # watch out for float rounding errors if x > 1: lo = 0.0 hi = x else: lo = x hi = 1 while abs(hi - lo) > error: ...
class Node: def __init__(self, value): self.value = value self.prev = None self.next = None class NLargest: def __init__(self, n): self.n = n self.size = 0 self.head = None self.tail = None def feed(self, x): if self.head and x > self.head.v...
def treepath(root, a, b): path_to_a = path(root, a) path_to_b = path(root, b) i = 0 while path_to_a[i] == path_to_b[i]: i += 1 last_common = i - 1 return path_to_a[-1:last_common:-1] + path_to_b[last_common:] def path(root, a): if root is None: return None elif root == ...
def correctPhrase(string): result = [] punctuations = ['?', '!', ','] result.append(string[0].upper()) for i in range(1, len(string)): char = string[i] if char in punctuations: result.append(char) result.append(' ') elif char != '.' and string[i-1] == '...
# Read data from csv file and put it into xs,ys,zs,vertex list import csv class Dataimport: def __init__(self, file): #init Dataimport program, self.file = file self.__init_xyzs() def read_vertex(self): #read csv file self.vertexs = [] with open(self.file) as...
""" 0-1 Knapsack Problem Given weights and values of n items, put these items in a knapsack of capacity c to get the maximum total value in the knapsack. In other words, given two integer arrays vals[0..n-1] and wts[0..n-1] which represent values and weights associated with n items respectively. Also given an integer ...
#!/usr/bin/env python3 # -*- coding:utf-8 -*- words = ["hello", "world", "spam", "eggs"] counter = 0 max_index = len(words) - 1 while counter <= max_index: word = words[counter] print(word + "!") counter = counter + 1 # Iterating through a list using a while loop requires quite a lot of code # so Python provides t...
#!/usr/bin/env python3 # encoding:utf-8 # Python contains many useful build-in functions and methods to accomplish # common tasks. # join-joins a list of strings with another string as a separator. print(",".join(["spam", "eggs", "ham"])) # prints "spam, eggs,ham" # replace- replaces one substring in a string with a...
#!/usr/bin/env python3 # encoding:utf-8 # To find the maximum or minimum of some numbers or a list, you can use # max or min. print(min(1, 2, 3, 4, 0, 2, 1)) print(max([1, 4, 9, 2, 5, 6, 8])) # To find the distance of a number from zero(its absolute value), use abs print(abs(-99)) print(abs(42)) # To find the total...
#!/usr/bin/env python3 # -*- encoding:utf-8 -*- # import libraries import urllib.request from bs4 import BeautifulSoup # specify the url urlpage = 'https://groceries.asda.com/search/yogurt' print(urlpage) # query the website and return the html to the variable 'page' page = urllib.request.urlopen(urlpage) # parse the...
#!/usr/bin/env python3 # encoding:utf-8 # Before a file can be edited, it must be opened, using the "open" function # if the file is in the current working directory,you can # specify only its name path = "filename.txt" myfile = open(path) # You can specify the "mode" used to open a file by applying a second argume...
# -*- coding: UTF-8 -*- ''' 简化路径。给定一个文档(Unix-style)的完全路径,请进行路径简化。 "/home/", => "/home“ "/a/./b/../../c/", => "/c“ ''' def simplifyPath(path): st = [] pp = path.split('/') for i in pp: if (i == '..') and st: st.pop() elif i and (i != '.') and (i != '..'): st.append(i...
# -*- coding: UTF-8 -*- def twoSum(ll, target): result = [] for i in range(len(ll)-1): for j in range(i + 1, len(ll)): if (ll[i] + ll[j]) == target: result.append((ll[i],ll[j])) break return result l = [2,3,5,7,5,0,9] print(twoSum(l,7))
# -*- coding: UTF-8 -*- ''' 请输入星期几的第一个字母来判断一下是星期几, 如果第一个字母一样,则继续判断第二个字母。 ''' #Monday Tuesday Wednesday Thursday Friday Saturday Sunday while True: l1 = input("请输入第一个字母:") if l1 == 'M' or l1 == 'm': print("Monday") elif l1 == 'W' or l1 == 'w': print("Wednesday") elif l1 == 'F' or...
import math for _ in range(int(input())): n = int(input()) num = n count = 0 while(num>0): k = int(math.sqrt(num)) num = num - pow(k,2) count = count+1 print(count)
def binary_search(arr,low,high,k): if(high>=low): mid = low + (high-low)//2 if(arr[mid]==k): return(mid) elif(arr[mid]>k): return(binary_search(arr,low,mid-1,k)) else: return(binary_search(arr,mid+1,high,k)) else: return(-1) ...
for _ in range(int(input())): arr = list(map(int,input().split())) for i in range(len(arr)): if(arr[i]!=arr[len(arr)-1-i]): print("Not Palindrome Array") break else: print("Palindrome Array")
n = int(input()) a = [ [ 0 for i in range(n)] for j in range(n)] for i in range(n): for j in range(n): if(i==j): a[i][j]==0 else: i,j,a[i][j] = int(input()),int(input()),int(input()) print(a)
#!python import sklearn import matplotlib.pyplot as plt import scipy as sp import pandas as pd import numpy as np from pandas.plotting import scatter_matrix # データ全体をまとめる iris = pd.read_csv( "https://raw.githubusercontent.com/pydata/pandas/master/doc/data/iris.data") # 品種ごとにまとめる setosa = iris[iris["Name"] == "Iris-...
class Pet: allowed = ['cat', 'dog', 'fish', 'horse', 'turtle'] def __init__(self, name, species): self.name = name self.species = species if species not in self.allowed: raise ValueError(f'You can\'t have a {species} as a pet!') def set_species(self, species): if...
# turn nested lists into dictionary key value pairs person = [["name", "Jared"], ["job", "Musician"], ["city", "Bern"]] # use the person variable in your answer answer = {i[0]: i[1] for i in person} # answer = {k : v for k,v in person} # answer = dict(person) print(answer)
# exploring conditionals # ask for age print('How old are you?') age = input() if age != '': if int(age) >= 21: print('normal entry') elif int(age) >= 18 and int(age) < 21: print('you get a wristband') else: print('you\'re too young, sorry') else: print('please enter a string'...
# 遍历循环 # for value = [1, 2, 3, "hello"] for x in value: print(x) # while:定义变量记录索引 # 定义变量保存列表中的元素个数 index = 0 l = len(value) while index < l: value2 = value[index] print(value2) index += 1
# Implementation of Pong in pygame import pygame as pyg import random import math class Pong: def __init__(self, screen_x=300, screen_y=300): pyg.init() pyg.font.init() self.screen_x, self.screen_y = screen_x, screen_y self.screen = pyg.display.set_mode((self.screen_x, self.screen_...
__author__ = 'Sergio' file = open("input2.txt", "r") # r-> read w+->write lines = file.readlines() # print(len(lines)) file.close() def containsxletters(palabra, n): #mayor = 0 for letra in palabra: ans = 0 for temp_letra in palabra: # i += 1 if letra == temp_letra: ...
__author__ = 'Sergio' from random import randint file = open("input4.txt", "r") # r-> read w+->write lines = file.readlines() file.close() class Date: def __init__(self, year, month, day, h, m, msg): self.year = year self.month = month self.day = day self.h = h self.m ...
# construct the polytree def construct_ptree(labelset_list): """ labelset_list: list of labelset in order Return: --------- list of tuples: the edges(where node are the index of the labelset in labelset_list) """ tree = [] # for the ith element, it stores the ith labelset's parent node ids...
import enum def choices(enumeration): """ Convert an Enum to a Django-style "choices" iterator. """ return [(member.name, member.value) for member in enumeration] class ESTATE_TYPE(enum.Enum): appartment = "Appartement" appartment_viager = "Appartement en viager" maison_villa = "Maison/V...
""" How SCOPE works in python? SCOPE determines which variables can be accessed at different points in your code. Names are very useful things. """ x = 7 y = 200 print(x) # What happens if we redefine x inside the function foo()? def foo(): x = 42 print(x) print(y) """in foo() print() statement,...
""" Image that you are throwing a fancy party, and have hired some caterers to provide refreshments for your guests. Before the party starts, the caterers set up tables with food and drinks. Then you and your friends dance, eat, and have a good time. Whe the party is done, the caterers clean up the food and remove the ...
s=int(input("enter the length:")) print (s) list=[] for i in range(0,s): new=input() a=list.append(new) list.sort() print(list)
""" This module is a module that can play the Connect 4 game. It is allow play with computer or play with other human player. This game module can save and load the game. """ from copy import deepcopy # you may use this for copying a board import numpy as np import os def newGame(player1,player2): """...
import turtle from turtle import Turtle, Screen import pandas screen = Screen() screen.title("Iran Provinces Game") img = "iran.gif" screen.addshape(img) turtle.shape(img) #for find location on the map # def get_mouse_click_coor(x, y): # print(x, y) # # turtle.onscreenclick(get_mouse_click_coor) # # turtle.mainlo...
""" QuickSort is a Divide and Conquer algorithm. It picks an element as pivot and partitions the given array around the picked pivot. There are many different versions of quickSort that pick pivot in different ways. 1. Always pick first element as pivot. 2. Always pick last element as pivot (implemented below) 3. Pic...
print("Welcome to my wonderful tip calculator!") bill_total = float(input("What was the total of the bill to split? ")) tip_percentage = int(input("What percentage tip would you like to give your lovely wait staff? ")) people = int(input("And how many are splitting the bill? ")) total_to_split = float((bill...
# # various common snippets # class RomanToDecimal: def __init__(self): self.num = 0 self.rom_val = {'i': 1, 'v': 5, 'x': 10, 'l': 50, 'c': 100, 'd': 500, ...
language=['python'] languages=['python','c','c++','java','perl'] print(language) print(languages) print(languages[0:3]) print(languages[1:4]) print(languages[2]) print(languages[5]) print(languages[0] + " and " + languages[1] + " are quite different!") print("accessing the last element of the list: " + languages[-1])
import random import colorgram from turtle import Turtle from turtle import Screen turtle = Turtle() turtle.speed(10000) screen = Screen() screen.colormode(255) screen.screensize(500, 500) colors = colorgram.extract("/Users/admin/PycharmProjects/turtle_project/images.jpg", 20) color_list = [] for color in colors: ...
def my_find_outlier(integers): arr = list(map(lambda x: x % 2 == 0, integers)) idx = arr.index(False) if arr.count(True) > arr.count(False) else arr.index(True) return integers[idx] def find_outlier(int): odds = [x for x in int if x%2!=0] evens= [x for x in int if x%2==0] return odds[0] if len(...
def bubbleSort(arr): n=len(arr) for i in range (n): for j in range(j+1,n): if arr[i]>arr[j]: arr[i],arr[j]=arr[j],arr[j] return arr
# 집합(set) # 중복안됨, 순서 없음 my_set = {1,2,3,3,3} print(my_set) java = {"유재석","김태호","양세형"} python = set(["유재석","박명수"]) # 교집합 (java 와ㅏ python을 모두 할 수 있는 사람) print(java & python) print(java.intersection(python)) #합집합 print(java | python) print(java.union(python)) #차집합 print(java - python) print(java.difference(python)) #...
try: print("나누기 전용 계산기 입니다") nums = [] nums.append(int(input("첫 번째 숫자를 입력하세요 : "))) nums.append(int(input("두 번째 숫자를 입력하세요 : "))) nums.append(int(nums[0]/nums[1])) print("{} / {} = {} ".format(nums[0],nums[1],nums[2]) except ValueError: print("에러! 잘못된 값을 입력하였습니다.") except ZeroDivisionError as...
'''5. Write a Python program to get the volume of a sphere with radius 6. Tools: input function, math''' from math import pi r = 6 vol_sphere = 4/3 * pi * (r **3) print(f"The volume of sphere with radius 6 is {vol_sphere} m2")
""" Write a Python program to add two objects if both objects are an integer type. """ class Addition: def __init__(self,x,y): self.x = x self.y = y def __add__(self,other): return Addition(self.x+other.x, self.y+other.y) first = Addition(5,7) second = Addition(3,6) result = first + sec...
'''8. Write a Python program to calculate the sum of three given numbers, if the values are equal then return three times of their sum. Tools: math, input function''' def check(n1, n2, n3): if n1 == n2 == n3: return 3 * (n1+n2+n3) else: return n1+n2+n3 print(check(2, 2, 2))
#9. Write a Python program to compute the future value of a specified principal amount, rate of interest, and a number of years. #Test Data : amt = 10000, int = 3.5, years = 7 #Expected Output : 12722.79 amt = 10000 int_rate = 3.5 years = 7 fv = (amt * (1 + (0.01 * int_rate)) ** years) print(fv)
""" Write a Python program to get the least common multiple (LCM) of two positive integers. """ x = int(input("x = ")) y = int(input("y = ")) def lcm(x,y): if x>y: z=x else: z=y while True: if((z%x==0)and(z%y==0)): lcm=z break z+=1 return lcm print...
'''1. Write a Python program to print the documents (syntax, description etc.) of Python built-in function(s). Sample function : abs() Expected Result : abs(number) -> number Return the absolute value of the argument. Tools: help function''' print(abs.__doc__)
'''6. Write a Python program to get the difference between a given number and 17, if the number is greater than 17 return double the absolute difference. Tools: abs function, input function, math''' #num = int(input("Enter a number greater than 17: ")) def num_difference(num): if num <= 17: return 17...
def count_list(lists): count = 0 for num in lists: if num == 4: count += 1 return count new_list = [34, 4, 56, 4, 22] print (count_list(new_list))
""" 10. Write a Python program that accepts an integer (n) and computes the value of n+nn+nnn. Sample value of n is 5 Expected Result : 615 Tools: input function, maths """ n = int(input("Enter an integer:")) sum = n + n**2 + n**3 print("The sum is", sum)
class ChessPieceUnit(object): def __init__(self, name, color): self.name = name assert color in ["Red", "Black"] self.color = color class ChessPosition(object): def __init__(self, position_x, position_y): self.position_x = position_x self.position_y = position_y cla...
import abc import typing class Message(object): def __init__(self, msg): self.msg = msg class Subject(abc.ABC): observers: typing.List['Observer'] = [] def __init__(self): self.observers = [] def register_observer(self, observer: 'Observer'): self.observers.append(observer...
def nextline(): next_line = False while next_line == False : next = input("go to next line?(yes or no)") next = next.lower().strip() if next == "yes": next_line = True else: next_line = False nextline() print("next line")
from graphics import * from random import randint from math import atan, sin, cos, pi white = color_rgb(255, 255, 255) red = color_rgb(255, 0, 0) green = color_rgb(124, 252, 0) class Node: def __init__(self, text, rad, x=0, y=0): self.center = Point(x, y) self.radius = rad self.circle =...
# -*- coding: utf-8 -*- """ @file @brief Complex joins with pandas. """ import pandas def df_crossjoin(df1, df2, **kwargs): """ Make a cross join (cartesian product) between two dataframes by using a constant temporary key. Also sets a MultiIndex which is the cartesian product of the indices of the input ...
# coding: latin-1 """ @file @brief contains a class which iterations on rows of a text file structured as a table. """ import re import os import decimal from pyquickhelper.loghelper import noLOG from pyquickhelper.loghelper.flog import GetPath from .file_text_binary import TextFile class TextFileColumns(TextFil...
from matplotlib import pyplot as plt from numpy import asarray import os from os import path import numpy as np import math import cv2 as cv # Method for thresholding the gray level image. # Accepts gray level image file object, threshold value, threshold method "threshmode defaults to binary" # threshmode...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jan 28 17:09:55 2019 Implementation of the Discrete Model Synthesis algorithm 3.4 from Paul Merrell's discrete model synthesis chapter of his dissertation. (2D) @author: Renato Barros Arantes """ import cv2 import itertools import numpy as np import m...
""" pythonSort.py just runs the basic python sort funtion for educational purposes. It uses timsort which is a hybrid of merge sorting and insertion sorting. It is considered a fairly effective sorting method for almost all real world datasets. Author: Joseph Tate Version: 1.0 """ nums = input("What numbers would y...
"""by MSKF""" """edited by ASHKAN""" import string # Import and use this instead from random import choice # List of avalable words, numbers, symbols words_list = [x for x in string.ascii_letters] numbers_list = [x for x in string.digits] symbols_list = [x for x in string.punctuation] characters_list = ...
# Python基本構文の学習用 #この課題は初学者さん用に基礎文法の理解度チェックするためのものです。 #ある程度理解している方は飛ばしてもかまいません。 ## 1 変数の使い方 #変数を使って、「ねずこ」と「ぜんいつ」 は仲間ですとprint文を使って表示させてみよう #なお、ねずこをname1、ぜんいつをname2として定義してください。 print("課題1") name1 = 'ねずこ' name2 = 'ぜんいつ' print (name1 + 'と' + name2 + 'は仲間です') ## 2 if文の使い方 #1のソースを改造して、name2が敵キャラの「むざん」だった場合に ...
import re def readLineFromFile(fileName): f = open(fileName, encoding="utf-8") line = f.read() return line def numberIt(line): result = re.split('(?<=[.?!])\s+', line) for i in range(len(result)): result[i] = result[i] + '[' + str(i + 1) + ']' print(result) if __name__ == '__mai...
# your code goes herexasdfghsjkfdz; a=input() if(a==1): print("123A456") if(a==2): print("1211") print "3\n3\n2"
import sys import sqlite3 # @app.route('/') # def hello(): # return 'Hello, World!' def connect_database(database_name): db_connection = sqlite3.connect(database_name) return db_connection def database_test_population(cursor, table_name, username, password, email, number, pcm, pt, pmg): cursor.exec...
class Pessoa(): def __init__(self, nome="", idade=0, peso=0): self.nome = nome self.idade = idade self.peso = peso # FUNÇÕES -> MÉTODOS def repirar(self): print(self.nome + " respirando") def comer(self): print(self.nome + " comendo")
def top_words(text): from collections import Counter split_it = text.lower().split() new_list = list() for word in split_it: if word[0] == "'" or word[len(word)-1] == " ' " or not word: continue else: new_word = ''.join([x for x in word if x.isalpha() or x == "'"...
a=int(input("Enter 1st Number")) b=int(input("Enter 2nd Number")) print("the sum of 2 numbers is equal to",a+b) print("the difference of 2 numbers is equal to",a-b) print("the product of these numbers is equal to",a*b) print("the quotient of these numbers is equal to",a/b)
import crypt senha_shadow = raw_input("Digite o hash a ser quebrado:\n") info = senha_shadow.split(":") #1 usuario = info[0] #2 hash = info[1] #3 salt = hash[:hash.find("$",3)+1] #4 with open("lista.txt", "r") as lista: while True: senha = lista.readline().strip("\n") if not senha: ...
# -*- coding: utf-8 -*- num1 = 666 print "Variável NUM1:", type(num1) num1 = str(num1) print "Variavel NUM1:", type(num1)
""" 21. Counting to Twenty: Use a for loop to print the numbers from 1 to 20, inclusive. """ for i in range(1, 20): print(i, end='\n')
""" 27. Cube Comprehension: Use a list comprehension to generate a list of the first 10 cubes. """ list_1 = [x**3 for x in range(1, 11)] print(list_1)
""" 9. Write a Python program to find the second smallest number in a list. """ list_1 = [3, 5, 1, 7, 15, 9] min1 = min(list_1) list_1.remove(min1) min2 = min(list_1) print("Second largest:", min2)
""" 2. Write a Python program to get the smallest number from a list """ list_1 = [1, 5, 3, 10, 11, 15, 12] print(min(list_1))
print(1,2,3,4,5) # Output: 1 2 3 4 print(1,2,3,4,sep='&') # Output: 1&2&3&4&5 print(1,2,3,4,5,sep='#',end='\n') # Output: 1#2#3#4& x = 3; y = 5 print('The value of x is {} and y is {}'.format(x,y), end='\n') #Output: The value of x is 3 and y is 5 print('I love {0} and {1}'.format('Me','Myself')) # Ou...
class Animel: def __init__(self, color, legs): # init constructor self.color = color self.legs = legs def eats(self): print("I eats dear") tigers = Animel('yellow', 4) print("I am tiger, My color is {}, I have {} legs." .format(tigers.color, tigers.legs)) tigers.eats() class...
# declaration list_1 = [] list_2 = ["python", "python", 1, 3.6, True, False] list_3 = list(("python", "python", 1, 3.6, True, False)) list_1.append(5) # when insert single data at any position print(list_1) list_1.extend([list_2]) # when insert full list use extend print(list_1) list_1.extend(list_2) print(list_1) ...
#Dump():- Dump() method python objects ko json file mai store karane ke liye use hota hai. Dump() method json files par hi kaam karta hai aur python objects ko ek argument ki tarah store karta hai. *Example:-*python object(dictionary) ko hum json file mai dump. import json dict1 ={ "emp1": { "name": "Lisa...
def number_gen(): for i in range(5): yield (i) for x in number_gen(): print (x) #return will not go back to function once it came out #yeild will be able to get values from function which is incrementally done
li=[1,2,3] index=int(input("enter the index")) try: print(li[index]) raise ArithmeticError except IndexError as err: print(err) except Exception as err: print(err) finally: print("this is neha") #we can have multiple except in try block #try block for handling exception handling #Exception is super...
li=[1,2.3,"neha",True] print(li) li.append("vivek") print(li) li.insert(2,"ansh") print(li) li_1=[18,90,] li.extend(li_1) print(li) li.pop() print(li) li.pop(1) print(li) li.remove(1) print(li) del(li[0]) print(li) li.clear() print(li)
def sum(n): sum=0 while(n!=0): temp=n%10 sum=sum+temp n=n//10 return sum def length(n): l=0 while(n!=0): l=l+1 n=n//10 return l num=1234 while(length(num)!=1): num=sum(num) print(num)
if __name__=='__main__': ''' a=9 b=8 c=a+b print("Answer " + str(c)) print(c) ''' a=input("enter value of a ") b=input("enter value of b ") c=int(a) + int(b) print("answer " + str(c))
if __name__=="__main__": name="This is Neha" change=name.swapcase() print(change) r="" i=0 while(i<=len(name)-1) : if name[i].islower(): r=r+name[i].upper() else : r=r+name[i].lower() i=i+1 print(r)
from cs50 import get_string from sys import argv if len(argv)!=2: print("Usage: python caesar.py k") exit(1) s = get_string("plaintext: ") outstr="" k = int(argv[1]) k=k%26 for i in range(len(s)): #for small if ord(s[i])>=97 and ord(s[i])<=122: if ord(s[i])+k>122: outstr += chr(o...
# -*- coding: utf-8 -*- """ Created on Tue Sep 15 14:48:57 2015 @author: Britt """ # This is a program to convert W/m^2 to mm/day initialevap=float(raw_input('What is your energy flux in W/msquared?')) w_msq=1 js_w=1 kg_j=0.00000044248 mcu_kg=0.001 s_hr=3600 hr_day=24 mm_m=1000 evap=initialevap*w_msq*js_w*kg_j*mcu_...
import math as math import numpy as np from sympy import * def f(x): return math.cos(math.cos(math.cos(math.cos(x**2)))) a = 0 b = 2 aproxValue = 1.447977898105671 # Valor obtido com erro inferior a 1.5e-15 def Simpson(): print('Valor absoluto usado é %.14f:' % aproxValue) print() for j in...
import time import functools def greeting_before_and_after_call(greeting): """ A decorator to greeting. """ def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): print('Hi {}'.format(greeting)) res = func(*args, **kwargs) print('Bye...
def identify_spammers(data,n_spam=10): ''' Function to automatically identify potential spammers and return it on a list data = the dataset to identify spammers n_spam = number of minimum tweets a day to be identified as spammers Author : Juan L Date : 8 Sept 2021 ...
from Account import BankAccount class User: accounts = [] def __init__(self, accountOwner, accountNumber): self.Owner = accountOwner self.accNumber = accountNumber self.balance = BankAccount(int_rate=3, balance=0) User.accounts.append(self) def withdraw(se...
import csv """ For this code to work for whatever CSV file is being used, some of the information below will need to be altered because this code works for the small sample CSV file that comes along with it. """ with open(r'C:\Python27\ENES100.CSV','rb') as csvfile: contents = csv.reader(csvfile) var = r...
list1 = [] n = int(input("Enter number of elements : ")) for i in range(0, n): ele = int(input()) list1.append(ele) print("The list is:") print(list1) print("The positive numbers in the list are:") for num in list1: if num>=0: print(num)