text
stringlengths
37
1.41M
# https://leetcode.com/problems/two-sum/description/ # Input: nums = [2,7,11,15], target = 9 # Output: [0,1] # Input: nums = [3,2,4], target = 6 # Output: [1,2] def twoSum(nums, target): print (nums) sum_map = {} for i in range(len(nums)): dif = target - nums[i] print ("[%s] %s=%s" % (i,nums[i], dif)) comp_n...
""" https://leetcode.com/problems/maximum-subarray/description/ Input: nums = [-2,1,-3,4,-1,2,1,-5,4] Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6. Input: nums = [1] Output: 1 Input: nums = [0] Output: 0 Input: nums = [0] Output: 0 Input: nums = [-100000] Output: -100000 """ def maxSubArray(nums): s...
""" https://www.geeksforgeeks.org/sort-a-stack-using-recursion/ """ def insert(x, n): print ('x=%s n=%s' % (x, n)) if not x or (x and n >= x[-1]): print ('** x=%s n=%s **' % (x,n)) x.append(n) return y = x.pop() print ('y=%s' % y) insert(x, n) x.append(y) print ('after x=%s' % x) def sortstack(arr): x ...
""" Implement Insertion Sorting Algorithm """ def insertion_sort(a): l = len(a) print (a) for i in range(l-1): #print ('********%s********' % i) for j in range(i, -1, -1): #print (a[j], a[j+1]) if a[j+1] < a[j]: a[j], a[j+1] = a[j+1], a[j] else: break #print (a) print (a) a = [99, 44, 6, 2...
""" https://leetcode.com/problems/valid-palindrome/ Example 1: Input: "A man, a plan, a canal: Panama" Output: true Example 2: Input: "race a car" Output: false Constraints: s consists only of printable ASCII characters. """ """ def isPalindrome(s): s = [i for i in s if i.isalnum()] s = ''.join(s).lower() r...
a=0 if a>10 print("a value is greater than 0") else: print("a is less")
#!/usr/bin/env python # coding: utf-8 # In[3]: import pandas as pd Location = "C:/Users/sarai/OneDrive/Desktop/Business Intelligence/axisdata.csv" df = pd.read_csv(Location) df # In[4]: # Average cars sold per month df['Cars Sold'].mean() # In[5]: # Maximum cars sold per month df['Cars Sold'].max() # In[6]...
def count_substring(string, sub_string): co=0 set=0 for i in range(0,len(string)): #print(set) #print(count) string=string[set:] num=string.find(sub_string) #print(num) set=num+1 co+=1 if set<=0: break #print (co) ...
# Define Text Cleaning function which eliminates punctuation and figures def TextCleaning(Text): Text = str(Text) Text = Text.replace('_', ' ') Text = Text.replace('-', ' ') Text = Text.replace('+', ' ') Text = Text.replace("'", ' ') Text = Text.replace('"', '') Text = Text.replace('”', '') Text = Text...
# # A simple demonstration of using Bond for spying and mocking # an application for monitoring temperature and sending alerts # # See a full explanation of this example at # http://necula01.github.io/bond/example_heat.html # # rst_Start import time import re import urllib, urllib2 from bond import bond class HeatWat...
number = int(input("number : " )) factorial = 1 if number < 0: print("factorial of negative numbers is not calculated") elif number == 0: print("result = 1 ") else: for i in range(1,number + 1): factorial = factorial * i print("result = ", factorial)
from twython import Twython APP_KEY = "h0rZYPs6iDq4orLJzBLJ0iFYl" APP_SECRET = "y6A4U5QsfdIRzbbUNY493d696BmSVZdb4NPHRvPNp8jFpzduI4" twitter = Twython(APP_KEY, APP_SECRET, oauth_version=2) ACCESS_TOKEN = twitter.obtain_access_token() twitter = Twython(APP_KEY, access_token = ACCESS_TOKEN) tag = raw_input("Enter the t...
# autor: zhumenger ''' 一.Message组件: 是Label组件的变体, 用于显示多行文本消息 可以自动换行,并调整文本的尺寸 ''' # 17_7_1.py # # from tkinter import * # # root = Tk() # # w1 = Message(root, text = "这是一则消息", width = 100) # w1.pack() # # w2 = Message(root, text = "我祈祷拥有一颗透明的心灵和会流泪的眼睛", width = 100) # w2.pack() # # mainloop() ''' ...
import math import numpy as np import random from constants import * from move import * class Human(): def human_turn(self,board_obj): board_obj.printBoard(board_obj) print("It's your turn," + HUMAN + ".Move to which place?") while(True): move = int(input()) ...
#!/usr/bin/env python3 # -*- coding: utf-8 -* """ COMS W4701 Artificial Intelligence - Programming Homework 2 An AI player for Othello. This is the template file that you need to complete and submit. @author: Shenzhi Zhang sz2695 """ import random import sys import time from heapq import heappush from heapq i...
#!/usr/bin/env python #pyglatin project print ("Welcome to PygLatin") #def run(): original = raw_input("Enter a random word here: ") if len(original) > 0 and original.isalpha(): pyg = "ay" print (original[1:]) + (original[:1]) + pyg else: print ("invalid entry!!") #done
# This file contains all classes used in many features # If you add sth to this file feel free to add yourselves as authors # Authors: Oskar Domingos, Marceli Skorupski import json import sqlite3 from SalesFeature.Discounts.models import DiscountScheme class DB: """ This class has all methods related to Datab...
# required modules from turtle import * from random import randint # classic shape turtle speed(0) penup() goto(-140, 140) # racing track for step in range(15): write(step, align='center') right(90) for num in range(8): penup() forward(10) pendown() forward(10) penup() bac...
from src.tool.struct import ListNode class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: my_head = ListNode(0) my_head.next = head next_node = my_head tmp_list = [] while next_node: tmp_list.append(next_node) if len(tmp_li...
class Solution: def threeSumClosest(self, nums, target): len_nums = len(nums) if len_nums < 3: return 0 # sort nums.sort() closest = 2**31 - 1 result = None for i in range(len_nums-2): left = i + 1 right = len_nums - 1 ...
from src.tool.struct import TreeNode class Solution: def isValidBST(self, root: TreeNode) -> bool: if root is None: return True def is_valid_bst(node: TreeNode, left=None, right=None): if node is None: return True if left is not None and node.va...
from src.tool.struct import ListNode class Solution: def middleNode(self, head: ListNode) -> ListNode or None: if not head: return None mid = cur = head count = 1 while cur.next: cur = cur.next count += 1 if count & 1 == 0: ...
class Stack: def __init__(self): self.__stack = [] self.__min_stack = [] def push(self, value): self.__stack = self.__stack + [value] if len(self.__min_stack) == 0: self.__min_stack = self.__min_stack + [value] elif self.__min_stack[len(self.__min_stack) - 1...
class Node: def __init__(self, data): self.__data = data self.__next = None def get_next(self): return self.__next def set_next(self, next): self.__next = next def set_data(self, data): return self.__data def get_data(self): return self.__dat...
#josephus problem in mathematics #we are doing the modular counting ! import string def remove_matching_letter(l1,l2): for i in range(len(l1)): for j in range (len(l2)): if (l1[i]==l2[j]): c=l1[i] l1.remove(c) l2.remove(c) l=l1+['...
from funcs import * def main(): letters = input() words = input().split() rows = get_rows(letters) #rows is basically the puzzle columns = get_columns(letters) backwards = ''.join([row[::-1] for row in rows]) upwards = ''.join([column[::-1] for column in columns]) print('Puzzle: ') prin...
# dict d = {'one':1, 'two':2} #{key:value, key:value} print(d['one']) print(type(d)) print(dir(d)) print(d.values()) print(d.keys()) print(d.items()) ''' 1. dict 안에는 다른 object 들이 들어갈 수 있다. 2. 값(주소값)을 변화시킬 수 없습니다. 3. 순서가 있습니다. 참고. dict를 JSON 형식으로 쓰기도 함 '''
# -*- coding: utf-8 -*- #WhileLoop counter = 5; while counter > 0: print ("Broiach = ", counter) counter = counter - 1 #Break and continue j = 0; for i in range(5): #range (start, end, step) j = j + 2 print ('i = ', i, ', j = ', j) if j == 4: continue print("I will be skipped over i...
# Given a list of integers and a single sum value, return the first two values (parse from the left please) in order of appearance that add up to form the sum. # Ex: [1, 4, 8, 7, 3, 15], 8 => [1, 7] # def sum_pairs(ints, s): # ints_set = set(ints) # result = s # return_arr = [] # for x in ints: # diff = result ...
def candies(s): if len(s) <= 1: return -1 else: s.sort() base = s[-1] total = 0 for x in s: if x < base: diff = base - x total += diff print total return total candies([5,8,6,4])
# Importing all the libraries import numpy as np import copy import math import heapq import time import matplotlib.pyplot as plt import cv2 import pygame # %% # wheel dia = 76mm # full robot dia = 354 mm # distance between the wheels = 317.5mm # clearance = can be given by the user = 5 mm # for solv...
''' Created on May 13, 2015 @author: tekrei Various square root approximations Source: Introduction to Computation and Programming Using Python book ''' import time def newton_raphson(y): ''' Newton-Raphson for square root ''' epsilon = 0.01 ans = y / 2.0 guess_count = 0 while abs(ans * ...
''' Created on May 16, 2015 @author: tekrei ''' class Item(object): ''' Item class for knapsack problem ''' def __init__(self, n, v, w): self.name = n self.value = float(v) self.weight = float(w) def getName(self): return self.name def getValue(self): ...
################################################################################# # Quick Sort # # A quick sort first selects a value, which is called the pivot value # # The actual position where the pivot value belongs in the final sorted li...
s="manjugiri" #s[::2] returns the element on the even position which is divisible by 2. print("Elements of even index position:", s[::2])
# def wash(dry=False, water=8): # print('加水', water, '分滿') # print('加洗衣精') # print('旋轉') # if dry: # print(dry, '烘衣服') # # # wash(True, 10) # # # def say_hi(): # print('hi!') # # # say_hi() # # # def add(x=0, y=0): # print(x + y) # # # add(123, 1223) # # # add() # def average(numbers):...
import os import csv import openpyxl import numpy from tkinter import * import tkinter.filedialog def prompt(): print('This program will calculate the rate constant (k) using two time points with N hellistein,' ' k using two time points with experimental N, binomial distribution, and plateau with corre...
print("This is running") def our_firstfunction(): print("inside our_firstfunction") x = 1 + 2 return x print(our_firstfunction()) def add(n1, n2): return n1 + n2 a = add(3,4) print(a)
def roman(n): if n//10 == 0: value="" elif n//10 == 1: value = "X" elif n//10 == 2: value = "XX" elif n//10 == 3: value = "XXX" elif n//10 == 4: value = "XL" elif n//10 == 5: value = "L" elif n//10 == 6: value ="LX" elif n//10 ==...
def factorial(n): """ Using recusion, return the factorial of the number n Returns:An integer """ if n == 1: return 1 else: res = n*factorial(n-1) return res def my_range(n, m): if n == m: return 0 else: return [n] return -1 def palindr...
symbol = {'0':0, '1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, 'A':10, 'B':11, 'C':12, 'D':13, 'E':14, 'F':15} def hex_dec(hex): power = len(hex) - 1 num = 0 for i in hex: num += symbol[i] * 16 ** power power -= 1 return num hex = input("Hex: ") pri...
x = True y = False z = 12 a = 10 b = not (x or not (x or y)) and True if b: print("Happy") elif b and x: print("Valentines") elif not b and not x and not y: print("day!") else: None ################### #2################# if (z < a): print("C200") elif (2*a<z): print("is bliss") else: No...
import math #question 1 f = lambda r :math.pi*(r**2) print (f(5)) #question 2 lst1 = [1,2,3,4,8] lst2 = [4,1,4,2] k = map(f,lst1,lst2) k = map( (lambda x,y:y if y>x else x), lst1, lst2) for i in k: print(i) for i in k: print(i) #question 3 def filter (x): aa = [1,2,3,4,5,6] if x: kor = ...
class Cola (object): def __init__(self): self.items=[] def encolar (self,dato): self.items.append(dato) def desencolar (self): if self.esta_vacia(): return None else: return self.items.pop(0) def esta_vacia(self): if len(...
# A Simple Bouncer Program age = input('What is your age ') x = int(age) if x < 18: print('Sorry You are too young') elif x >= 18 and x <= 21: print('You are allowed to go') else: print('You are old enough for this')
# #This is a simple guessing game in Python. from random import * number = randint(1,10) while True: guess = input('Pick a number from 1 to 10: ') guess = int(guess) if guess < number: print('Its too low') elif guess > number: print('its to high') else: print('You Won') break
''' Just like a balloon can have multiple ribbons, an object can also have multiple reference variables. Both the references are referring to the same object. When you assign an already created object to a variable, a new object is not created. ''' class Mobile: def __init__(self, price, brand): print ("...
#Static Method continued ''' Since static variable is object independent, we need a way to access the getter setter methods without an object. This is possible by creating static methods. Static methods are those methods which can be accessed without an object. They are accessed using the class name. There are two ru...
''' What happens when we pass an object as a parameter to a function? In the below code, what will be the output? ''' class Mobile: def __init__(self, price, brand): self.price = price self.brand = brand def change_price(mobile_obj): mobile_obj.price = 3000 mob1=Mobile(1000, "Apple") change_...
class node: def __init__(self,value): self.value=value self.leftChild=None self.rightChild=None self.totalChild=0 class binaryTree: def __init__(self): self.rootVal=None def insertLeft(self, val): rootNode=self.rootVal if(rootNode...
#A=int(input("ingrese un para comparar si es mayor numero\n")) #B=int(input("ingrese otro numero para comparar si es mayor\n")) #C=int(input("ingrese un nuemero para comparar si es mayor\n")) def mayor(A,B,C): var = 0 if(A > B and A > C): print("El numero mayor es " + str(A)) var = A else: ...
class Solution: def isMatch(self, A,B): if not len(A) and not len(B): return True if not len(B): return False if len(B) - B.count('*') > len(A): return False A = "@" + A B = "@" + B dp = [[None for j in range(len(B))] for i in range...
# -*- coding: UTF-8 -*- from descontos import Desconto_por_cinco_itens, Desconto_por_mais_de_quinhentos_reais, Sem_desconto class Calculador_de_descontos(object): def calcular(self, orcamento): desconto = Desconto_por_cinco_itens(Desconto_por_mais_de_quinhentos_reais(Sem_desconto())).aplicar(orcamento) ...
import cv2 as cv # 1) Adição de imagens image1 = cv.imread('images/superman.png') image2 = cv.imread('images/batman.png') addedImage = cv.add(image1, image2) #addedImage = image1 + image2 # Assim também é possível, porém não haverá tratamento dos pixels e pode resultar na distorção das cores cv.imshow('Imagem somad...
#!/usr/bin/env python3 """ Copyright 2020, University of Freiburg Author: Marco Kaiser <kaiserm@informatik.uni-freiburg.de> Usage of the Script: This script opend the File kami.txt parses it and prints an ouput which is a problem in pddl. Make sure to have a correct kami.txt file, otherwise the problem wi...
''' This program counts and displays the vowels in a string using two different methods. Input: String(User Input) Output: Number & List of vowels in the string ''' def vowel_count( string, vowel): vowel_num = [each for each in string if each in vowel] print("Number of vowels in your string:%d"%len(vowel_num))...
#!/usr/bin/python3 def search_replace(my_list, search, replace): if my_list is None: return new_list = [0 for i in my_list] for idx, val in enumerate(my_list): if val == search: new_list[idx] = replace else: new_list[idx] = val return new_list
#John Paul Lee #Problem Sheet for Week 3 of Programming and Scripting #Ask user to input a sentance. s = str(input("Please enter a sentence: ")) sliced = s[::-1] #sliced the sentence in reverse. No input between the colons to allow for unlimited length of sentance. print(sliced[::2]) #print every second word of the...
def addition1(): result = 5 + 5 return result def addition(n = 35): result = 5 + n return result def multiply(): return 5 * 5 def get_message(): return "le résulat du calcul est" print(get_message(), multiply()) print("le résulat du calcul est", addition1()) print("le résulat du calcul ...
food1 = input("Please enter a favorite food ") food2 = input("Please enter another favorite food ") print(food1+food2) input("\n\nPress the enter key to exit.")
#Asks person for favorite song #Replaces "m" with "n" when they enter line from song song = input("Please enter a line from your favorite song ") print(song.replace("o","a")) print(song.replace("m","n")) input("\n\nPress the enter key to exit.")
class Czas: """Stwórz klasę Czas, której konstruktor (__init__) będzie brał trzy opcjonalne argumenty, godzine, minuty, sekundy i zapisywal je w odpowiednich zmiennych w klasie.""" def __init__(self, h=0, mins=0, sec=0): self.h = h self.mins = mins self.sec = sec ...
mapdict = {10:'A', 11:'B', 12:'C', 13:'D', 14:'E', 15:'F'} '''def convert(number,n): answer = '' if number // n < 1: remain = number % n if remain >= 10: remain = mapdict[remain] answer = str(remain) + answer while number // n >=1: remain = number % n...
s=''' <35 F 35 to 59 D 60 to 79 C 80 to 89 B 90 to 100 A ''' print(s) m=int(input("\nPlease Enter your Marks:\n")) if(m<35): print("F") elif(m>=35 and m<60): print("D") elif(m>=60 and m<80): print("C") elif(m>=80 and m<90): print("B") elif(m>=90 and m<101): print("A") else: print("Invalid") ...
from PIL import Image def resize(img_names,size=(200,200)): for img_name in img_names: img=Image.open(img_name) img=img.resize(size) img.save("resized"+img_name) img_names=["1.jpg","2.jpg","3.jpg"] resize(img_names) print("____________\n\n") #cropping img=Image.open("1.jpg") img.sh...
#requests library to get the HTML content of the website import requests #urllib library to parse the URL links from urllib.parse import urlparse, urljoin #HTMLParser library is used to parse the HTML content scraped using requests from html.parser import HTMLParser internal_urls = set() hrefs = [] #since all anchor...
prob_failure = .10 three_fails_prob = 1.0 for i in range(0,3): three_fails_prob = three_fails_prob * prob_failure print("Probability of 3 consecutive failures: {}".format(three_fails_prob))
""" Question: Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i. For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], th...
list1 = [int(i) for i in input().split()] x = int(input()) if x in list1: for i in range(len(list1)): if list1[i] == x: print(i, end=' ') else: print('Отсутствует')
#!/usr/bin/python # Haversine formula example in Python # Author: Wayne Dyck import math def distance(origin, destination): lat1, lon1 = origin lat2, lon2 = destination radius = 6371000 # m dlat = math.radians(lat2-lat1) dlon = math.radians(lon2-lon1) a = math.sin(dlat/2) * math.sin(dlat/2) + math.cos(m...
#Comment """ Multiline Comment """ print("Welcome To Our TFP Calc") firstNum = int(input("Enter The First Number")) operator = str(input("Enter The Operator")) secondNumm = int(input("Enter The Second Number")) def Calculator(): if operator == "+": print(firstNum + secondNumm) elif operator == "-...
from collections import namedtuple q = namedtuple('Q', 'question') def line_to_q(line): return q(question=line.rstrip("\n")) def q_to_line(q): return "%s\n" % q.question def csv_to_qs(csv_file): with open(csv_file, encoding='utf-8') as f: qs = f.readlines() qs = [line_to_q(l) for l in...
import math import unittest def statement(invoice, plays): total_amount = 0 volume_credits = 0 result = f'Statement for {invoice["customer"]}\n' def format_as_dollars(amount): return f"${amount:0,.2f}" for perf in invoice['performances']: play = plays[perf['playID']] if pl...
#Предварительная обработка данных import numpy as np from sklearn import preprocessing input_data = np.array([[2.1, -1.9, 5.5], [-1.5, 2.4, 3.5], [0.5, -7.9, 5.6], [5.9, 2.3, -5.8]]) # Применение методов предварительной обработки # Бинаризация data_b...
#break i=1 while i <= 5: if i==4: print('吃够了') break i +=1 #continue i=1 while i<=5: if i==3: print('跳过3') i +=1 continue print(i) i+=1
print('创建⼀个0-10的列表。') print('--------------while循环实现-------------------') list1=[] i=0 while i<=10: list1.append(i) i+=1 print(list1) print('---------------for循环实现------------------') list1=[] for i in range(10+1): list1.append(i) print(list1) print('-----------------列表推导式实现----------------') list2 = [i ...
print('-------创建集合使⽤ {} 或 set() , 但是如果要创建空集合只能使⽤ set() ,因为 {} ⽤来创建空字典。---------------') s1={10,20,30,40,50} print(s1) s2={10,20,30,40,50,30,40,50,}#集合自动去重、无序 print(s2) s3=set('qweew') print(s3) s4 =set() #集合类型 print(type(s4)) s5={} #字典类型 print(type(s5)) print('------------add()当向集合内追加的数据是当前集合已有数据的话,则不进⾏任何操作。--...
import functools list1=[2,3,5,76,8] def func(a,b): return a+b res=functools.reduce(func,list1) print(res)
mystr = "hello world and supertest and chaoge and Python" #count统计出现次数 print(mystr.count('and')) print(mystr.count('ands')) print(mystr.count('and',0,30))
''' How it works? Its the same as homework2 except that every eval function (of the Cexp classes) returns the next command to be executed and the current state. How it prints the command? By an INORDER traversal of the tree recursively. Every class has a printx() function, that calls the printx() function of its chil...
# Basically just a function that uses a "yield" command to return data to the caller, similar to an iterator but without defining a next() method. def reverse(data): for index in range(len(data)-1, -1, -1): yield data[index]
from my_mod import enlarge from pandas import DataFrame print("HELLO") df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) print(df) x = 11 print(enlarge(x))
# coding=utf-8 class Singleton_Lazy(object): __instance = None def __init__(self): if not Singleton_Lazy.__instance: print("I have already got an instance!") else: print("I don't have got an instance!") @classmethod def getInstance(cls): if not cls.__ins...
start = "487912365" # start = "389125467" cups = [int(c) for c in start] mincup = min(cups) maxcup = max(cups) current = cups[0] moves = 100 def pick3(cups,current): # print(cups, current) temp = cups.copy() temp.extend(cups) # print(temp, current) # print(current in temp) curr_index = temp...
# Compute the Powerset of a list # items = [1, 2] # powerset = [[], [1], [2], [1, 2]] import itertools def potenzmenge(items): powerset = [x for length in range(len(items)+1) for x in itertools.combinations(items, length)] return powerset def min_potenzmenge(items): powerset = [x for length in range(len...
__author__ = 'nolanemirot' def gridChallenge(arr): tmp = 'a' for e in arr: if tmp <= e: tmp = e else: return False return True def checkColumn(arr, wl): x = 0 while x < wl: y = 0 tmp = 'a' while y < wl: elemen = arr[...
__author__ = 'nolanemirot' def stringCompression(string): s = "" i = 0 count = 0 end = "" while i < len(string)-1: if string[i] == string[i+1]: count+=1 else : s+= string[i] + str(count+1) count = 0 i+=1 end = string[i] if(str...
__author__ = 'nolanemirot' def traverse(graph, start): traversed = [] stack = [start] while stack: v = stack.pop() if v not in traversed: traversed.append(v) for n in graph[v]: stack += n print(traversed) if __name__ == '__main__': graph = ...
__author__ = 'nolanemirot' import math class Point(): def __init__(self, x, y,z): self.x = x self.y = y self.z = z def __sub__(self, other): xx = self.x - other.x yy = self.y - other.y zz = self.z - other.z return Point(xx, yy, zz) def __mul__(...
def fibonacci(num): i = 0 arr = [] if num == 0: return 0 if num == 1: return 1 while i <= num: if i < 2: arr.append(i) else: arr.append((arr[i-1]) + arr[i-2]) i += 1 return arr[len(arr)-1] def fibonnaci_rec(num): if num ==...
__author__ = 'nolanemirot' nbTestCase = int(input()) def findNbDigit(N): i = 0 a = N rep = "" five = 0 while a > 0: if a % 3 == 0: five = a break a -= 5 trees = N - five if five <= 0 and trees % 5 != 0: return print("-1") while(five > 0)...
def funny_string(s1, s2): #print("s1:",s1) #print("s2:",s2) i = 1 while i < len(s1): if (abs(ord(s1[i-1])-ord(s1[i])) != abs(ord(s2[i-1])-ord(s2[i]))): return "Not Funny" i += 1 return "Funny" if __name__ == '__main__': nb_test = int(input()) for i in range(0, ...
__author__ = 'nolanemirot' def calcGrade(name, dic): arr = dic[name] val = 0.00 for i in arr: val += i print(format(val/len(arr), '.2f')) if __name__ == '__main__': dic = {} nbStudent = int(input()) for i in range(0,nbStudent): line = input() arr = line.split()...
def fill_line(nb_p, nb_s): a = [] for i in range(nb_s): a.append(' ') for i in range(nb_p): a.append('#') return a def print_(arr): for i in arr: for a in i: print(a, end='') print() if __name__ == '__main__': nb_stair_f = int(input()) arr = []...
stack=[] top=None def addbooks(b): stack.append(b) top=len(stack)-1 def removebooks(): if len(stack)==0: return None else: book=stack.pop() return book top=len(stack)-1 def isempty(): if stack==[]: return True def display(): top=len(stack)-1 print(st...
def facto(n): fact=1 for i in range(1,n+1): fact=fact*i return fact print("...Factorial of a nuber...") n=int(input("Enter the nuber :")) print("The factorial is",facto(n))
import unittest import math #importing the required maths libraries import numpy as np from math import factorial operation = int(raw_input("Please select a Function: \n 1: Addition \n 2: Subtraction \n 3: Multiplication \n 4: Division \n 5: Exponents \n 6: Fahrenheit-Celcius \n 7: Factorials \n 8: Square Root \n 9...
while True: x = input("输入x:") y = input("输入y:") x = int(x) y = int(y) if (x == 0) & (y == 0): print("原点") elif x > 0: if y > 0: print("第一象限") elif y < 0: print("第二象限") elif y == 0: print("x轴") elif x < 0: if y > 0: ...
import csv import numpy as np def averagenum(num): nsum = 0 for i in range(len(num)): nsum += int(num[i]) return nsum / len(num) with open("/Users/rockter/test.csv","r",encoding = 'utf-8') as csvfile: reader = csv.DictReader(csvfile) cxsj = [] xbsw = [] slx = [] for row in reader...
import itertools def calling(cb): """Iterfunc which returns its input, but calling callback after every item. In particular, the returned iterator calls cb() after it has been asked for a next element, but before returning it. """ def iterfunc(iterator): for item in iterator: ...