text
stringlengths
37
1.41M
import math num1 = int(input("ENter the number : ")) #legend method flag = 1 num2 = int(math.sqrt(num1))+1 for each in range(2,num2): c = num1%each if c==0: flag =0 print ("divisible by", each ) break if flag==1: print ("Number is prime ") else : print ("Number is not prime")
list1 = [1,21,31,1,41,5,101,0,0,4,1,5,6,0,0,1,4,5] #[21,4,4,5,5....... 0, 0,0,0,0] def fun1(a,b): #1,21,31,41,5,0,0,4,5,6,0,0,4,5 c = a-b if a ==0 or b==0: return 1 else : return c list1.sort(cmp=fun1) print (list1)
import re import urllib url = "http://www.thapar.edu/faculties/category/departments/computer-science-engineering" html = urllib.urlopen(url) text=html.read() p1 = r'\b[\w.-]+?@\w+?\.\w+?\b' #34h-u.lk_123@marvel.com p1 = re.compile(p1) m1 = re.findall(p1, text) for email in m1: print (email)
str1 = "waht we think we we become" for n in range(len(str1)): if str1.find('we',n)==n: print n #print [n for n in xrange(len(text)) if text.find('la', n) == n]
list1 = [("Mohit", 80, 31),("Ravender", 80,30),("Bhaskar narayan das", 70,34)] for k,v,i in list1: print (k.ljust(20," "),v,i)
str1 = "What we think we become" i = 0 for each in str1: if each== 'e': i = i +1 print (i)
marks = int(raw_input("Please enter the marks\t")) grade = "" if marks>89: grade = 'A' elif marks > 70: grade = "B" elif marks > 60: grade = 'C' else : grade ='D' print "Grade of the student is ", grade
#from collections import namedtuple import collections emp1 =collections.namedtuple("Learntek", 'name age empid', rename= False ) # creating own data type record1 = emp1('shankar',28, 123456) print (record1) print (record1.name) print (record1.age) record1= record1._replace(age=25) print (record1.age) print ...
list1 = [1,2,3,4,5,6,7,67,34,12] ''' def fun1(a): t = a%2 if t ==1: return 0 else : return 1 ''' final_list = filter(lambda a: a%2,list1) print final_list
list1 = [1,2,3,4,5,"a",1.1,5,6] for each in list1: print (each)
import re pattern = "this" text = " in this world nothing is permanent this is last number this" for match in re.findall(pattern,text): print "found", match for match in re.finditer(pattern,text): print match s = match.start() e = match.end() print "Found", match.re.pattern, s, "from", e pri...
#variables #list_of_number = [0, 1, 2, 'blue', 4, 'green'] #list of numbers and strings # for loops #for elem in list_of_number: # print(elem) #Another for loop example #for elem in list_of_number: #Goes through each element in the list # if type(elem) == str: #checks if there is a string element # co...
PI = 3.14 def some_function(x, y, z): final = x + y + z return(final) output = some_function(5, 6, 7) print(output) def greet_friend(name, greeting, sentence): output = "{2}, {0}! {1}".format(greeting, name, sentence) return(output) greeting = greet_friend("Jazsmin", "Hey", "How are you do today?")...
from urllib.request import urlopen from bs4 import BeautifulSoup #访问网站时的异常处理 from urllib.error import HTTPError #判断两种错误的方法(服务器不存在;获取界面发生错误/不存在) def getTitle(url): try: html = urlopen(url) except HTTPError as e: return None try: bsObj = BeautifulSoup(html.read()) title = bsObj...
''' List comprehensions ''' # e.g. import random my_list = [random.randint(1, 1000) for i in range(1, 13)] print(my_list) ''' Decorators ''' ''' What if we want to add some further functionality in certain function by using another function? Here we can use a decorator function to get through the pr...
print("Icount:") print("hens", 25.0 + 30.0 / 6.0) # gibt ergebnis von 100 - (75 % 4) 1.* 2.% 3.- print("roosters", 100.0 - 25.0 * 3.0 % 4.0) #gibt eggs: aus print("eggs:") #gibt das ergebnis aus 1.1/4 2.4%2 3.strichrechnungen print(3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6) print("is it true that 3 + 2 < 5 -7?") #gibt in true...
types_of_anus = 10 x = f"there are {types_of_anus} types od anus." #gives binary the string binary binary = "binary" do_not = "dont't" y = f"one know {binary} one {do_not}" print(x) print(y) #give out the string in x which givs out the 10 from types of anus print(f"i said : {x}") print(f"i also said: '{y}'") #set hi...
""" 1. Write a program that asks the user for their name, then opens a file called “name.txt” and writes that name to it. 2. Write a program that opens “name.txt” and reads the name (as above) then prints, “Your name is Bob” (or whatever the name is in the file). 3. Create a text file called “numbers.txt” (You can crea...
""" Create a series of widgets for a list of names """ from kivy.app import App from kivy.lang import Builder from kivy.uix.label import Label from kivy.core.window import Window class NameListApp(App): """Main program. Create a series of labels for a list of names.""" _names = ["Adam", "Bill", "Charlie", "D...
'''This Programme Takes Random Number And Genrates given no. of triangles. It also finds the incircle and calculates the area of maximum cirlce possible. At the end it generates a parallelogram parallel to y-axis and having the minimum area that covers all the triangles.''' import sys import random import math import ...
print('hello') num =0 for (num < 100 print("hello", num)
"""OOP examples for module 2""" import pandas as pd class MyDataFrame(pd.DataFrame): """Inheriting from Pandas DataFrame Class proof of concept""" def num_cells(self): return self.shape[0] * self.shape[1] # returns number of cells in df class BareMinimumClass: """Basic proof of concept""" p...
#'intersection (commune) de deux Sets et supprimez ces éléments du premier Set set1 = {23,11,3,4,13,8,34,54,6,29} set2 = {11,4,2,36,345,78,23,867,788} intersection = set1 & set2 #l'intersection de set 1 et de set 2 print("intercection",intersection) set1 = set1 - intersection #set 2 apres la suppression print("Se...
#e un programme pour itérer une liste donnée et compter l'occurrence de chaque élément et créer un dictionnaire pour montrer le nombre de chaque élément List= [7,8,45,7,234,5,21,678,1,345,234,1,1,1,7] dict={} #la dictionnaire for i in List: List.count(i) dict[i]=List.count(i) print (dict)
# let's write a script that tells us the most common character in # adventures of sherlock holmes. with open("english/adventures_of_sherlock_holmes.txt", 'r', encoding="utf8") as rf: text = rf.read() unique_characters = set(text) # current most common character most_common_character = [] # how often ...
# let's write a script that tells us the most common character in # adventures of sherlock holmes. with open("english/adventures_of_sherlock_holmes.txt", 'r', encoding="utf8") as rf: text = rf.read().lower() # tokenize the text into words words = text.split(" ") print(words[100:110]) unique_word = set(wo...
# lists! # an ordered container for information/python objects # create a list with square brackets and each item is seperated # with a comma name_list = ["Juan", "Rogier", "Ying", "Cindy"] # a list can be empty empty_list = [] # can contain basic data types int_list = [1, 2, 3, 4, 5, 6, 7] float_list = ...
""" Integers vs. Strings 0 Write a script that displays the sum and product of two numbers. This script uses 4 variables. Your script should do the same with 2. """ x = 10 y = 20 print(x+y) print(x*y)
""" Integers vs. Strings 1 1. How many variables are used in this script, and what are their names? 2. What does Python say the types of these variables are? 3. Fix the spacing between the words, and describe how you did it. """ someText = 'Oh happy day.' otherText = "I'm on my way." together = ('someText + otherT...
# To-do: How do I add integers to fractions etc? # Is it okay to use in-place modification for binary operations? class breuk: def euclidesalg(self, a, b): while a > 0 and b > 0: if a > b: a -= b else: b -= a return a def __...
# The quicksort code won't be commented, since it's a common algorithm. from random import randint from time import time_ns as time def quicksort(list, left=0, right=-1): """Sorts a list L by using quicksort. Fails for lists that have more than 1000 elements of the same value.""" if right == -1: rig...
# This is a sample Python script. # Press Shift+F10 to execute it or replace it with your code. # Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings. def print_hi(name): # Use a breakpoint in the code line below to debug your script. print(f'Hi, {name}') # Press ...
import tkinter as tk class PongLogicGui: """ Den här klassen skickar information mellan de olika widgetarna. Den innehåller också gameLoop som styr rörelser i PongArea. Den här klassen hämtar information från en widget genom att definiera en funktion som tilldelas widgeten och den skickar information ...
# 内部函数对外部函数作用域里变量的引用(非全局变量)则称内部函数为闭包 def counter(start=0): count=[start] def incr(): count[0]+=1 return count[0] return incr c1=counter(10) print(c1()) # 结果:11 print(c1()) # 结果:12 # nonlocal访问外部函数的局部变量 # 注意start的位置,return的作用域和函数内的作用域不同 def counter2(start=0): def incr(...
#!/bin/python # 1.1 Are all symbols in string unique? def sym_unique(str): symbols = [] unique = True for e in str: if unique is False: break if e in symbols: unique = False break else: symbols.append(e) print(unique) # 1.3 Are two strings anagrams? def anagrams(str1, str2): t1 = sorted(tuple(...
#OUTPUT #1 #1 2 #1 2 3 #1 2 3 4 #1 2 3 4 5 #1 2 3 4 5 6 n = int(input("select number of rows:", )) def num_patt1(n): for i in range(0, n): for j in range(0, i+1): print(i+1, end=" ") print("\r") if __name__ == '__main__': num_patt1(n)
import random import colorama from termcolor import colored GUESS = 'Guess #{}: ' PROMPT = 'Pick a number between 1 and {}' LESS = 'My number is LESS THAN (<) {}' GREATER = 'My number is GREATER THAN (>) {}' def difficulty_output(): print('Guessing Game') print('Choose your difficulty') print('1 - Easy (...
name = input("*****:enter the god name:*****") print(len(name)) print()
from random import randint INITIAL_POPULATION = 1000 def main(): print("Welcome to the Gopher Population Simulator") print("Starting Population:", INITIAL_POPULATION) population = INITIAL_POPULATION for x in range(1, 10): gophersBirth = randint(int(population * 0.1), int(population ...
from excecoes import LanceInvalido class Usuario: def __init__(self, nome, carteira): self.__nome = nome self.__carteira = carteira def propoe_lance(self, leilao,valor): if not self.__valor_eh_valido(valor): raise LanceInvalido('O usuário não pode propor lances...
"""Module that handles displaying of adventure-games story""" import curses import textwrap class StoryScreen: """Story Screen Class, can display parts of the games' story""" def __init__(self, screen): """StoryScreen's init function""" # hold current screen self.screen = screen ...
""" Interfaces for Monster from utility """ class Monster: """ Interfaces class for Monster """ def __init__(self, str_monst, room, item, name): self.str = str_monst self.item = item self.room = room self.name = name # Monsterkampf, von Monster-Event aufgerufe...
#!/usr/bin/python import time import datetime class Singleton: """ A python singleton """ class __impl: """the actual singleton implementation """ def __init__(self): """ Save a timestamp of when created """ self.ts = datetime.datetime.fromtimestamp(time.time()).strfti...
# Program by Muhammad Bagus Zulmi # Url to problem : https://open.kattis.com/problems/modulo # http://www.mbaguszulmi.com def main(): distinct = [] for i in range(10): mod = input()%42 if mod not in distinct: distinct.append(mod) del i print len(distinct) if __name__ == '__main__': main()
# Program by Muhammad Bagus Zulmi # Url to problem : https://open.kattis.com/problems/boatparts # http://www.mbaguszulmi.com def main(): inputStr = raw_input().split() p = int(inputStr[0]) n = int(inputStr[1]) day = 0 partName = [] for i in range(n): name = raw_input() if name not in partName: partName.ap...
# Program by Muhammad Bagus Zulmi # Url to problem : https://open.kattis.com/problems/beavergnaw # http://www.mbaguszulmi.com def main(): pi = 3.141592653589793238462643383279502884197169399375105820974944592307816406286 dInner = [] while 1: inputStr = raw_input().split() if inputStr[0] == ...
import os import json file_source = 'data/words.json' score_source = 'data/scores.txt' file_length = 0 """ Get the length of the word list """ def get_file_length(): return file_length """ Set the length on the word list """ def set_file_length(length): global file_length file_length = length """ Get th...
#!/usr/bin/env python # Name: # Student number: ''' This script scrapes IMDB and outputs a CSV file with highest rated tv series. ''' import csv from pattern.web import URL, DOM TARGET_URL = "http://www.imdb.com/search/title?num_votes=5000,&sort=user_rating,desc&start=1&title_type=tv_series" BACKUP_HTML = 'tvseries....
#!usr/bin/python/ # -*- coding: utf-8 -*- #list列表 classmates = ["aa","bb","cc"] print(len(classmates)) print(classmates[-1]) #tuple元祖 区别 tuple一旦初始化就不能修改 classmatess = ("aa","bb","cc") print(classmatess) print(classmatess[1]) L = [ ['Apple', 'Google', 'Microsoft'], ['Java', 'Python', 'Ruby', 'PHP'], ['Ada...
''' 2048实现方法 ''' list_merge = [2, 2, 2, 0] map = [ [2, 0, 2, 0], [4, 4, 2, 0], [0, 4, 0, 4], [2, 2, 0, 4], ] # 1.定义函数,将list_merge列表中的零元素移动到末尾 # 例如2 0 2 0 ——> 2 2 0 0 # 0 0 2 0 ——>2 0 0 0 # 0 0 2 0 ——>2 0 0 0 # 4 0 2 4 ——>4 2 4 0 # def move_zero_end(zero): # for k in range...
print('Hello World') salse = 'tomato' if salse.startswith('toma'): print("it's probably tomato...") else: print("not tomato") order_description = """ The client ask for a pizza with less cheese. Intead of cheese, he would like to have more jam """ print(order_description)
import sqlite3 from socket import * class sql: def __init__(self): try: self.db = sqlite3.connect('ip_table') cursor = self.db.cursor() # Check if table users does not exist and create it cursor.execute('''CREATE TABLE IF NOT EXISTS ...
from typing import List from rl.agent import DiscreteAgent from rl.environment import DiscreteEnvironment from rl.episode import Episode from rl.experience_tuple import ExperienceTuple class SequentialGame: """ Game where the agent takes decisions sequentially. At every step, the Agents see the Environme...
# coding=utf-8 print("Hello World") # Listas fruits = ["Apple","Orange","Watermelon"] print(fruits[0]) print(fruits[1]) print(fruits[2]) print(fruits[-1]) print(fruits[-2]) print(fruits[-3]) numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] from_2_to_6 = numbers[2:7] print(from_2_to_6) greater_than_4 = numbers[5:] print(great...
""" A base class for different point location algorithms """ from abc import ABC, abstractmethod from node import dist, ch, rel import functools class PointLocation(ABC): def __init__(self, tree): self.tree = tree self.basictouchno=0 self.splittouchno=0 self.mergetouchno=0 ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # pythonCalculIMC.py # # Copyright 2014 yves Mercadier <yves.mercadier@ac-montpellier.fr> # def entree(): #Les entrees du programme print ("Votre IMC \n") poid = int(input("Quelle est ton poid? ")) taille = float(input("Quelle est ta taille? ")) return poid,taille de...
# Chain of resposibility from __future__ import annotations from abc import ABC, abstractmethod from typing import Any, Optional class AutomationHandler(ABC): """The Handler interface declares a method for building the chain of handlers. It also declares a method for executing a request.""" @abstractmethod ...
#列表 print([i for i in range(5)]); print("------------------------------------------------"); print([(i,j) for i in range(3) for j in range(2)]);
import random import sys import time from os import path import textwrap from player import * from tiles import * from settings import * from combats import * import pickle class Game: def __init__(self): self.game_solved = False self.moved = False def title_screen(self): ...
def binary_search(value, array): mid = len(array) / 2 if value == array[mid]: return True elif value < array[mid]: return binary_search(value, array[0:mid-1]) else: return binary_search(value, array[mid+1:-1])
''' Created on Mar 19, 2014 @author: Daniel Corroto A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given: 1/2 = 0.5 1/3 = 0.(3) 1/4 = 0.25 1/5 = 0.2 1/6 = 0.1(6) 1/7 = 0.(1428...
''' Created on Mar 20, 2014 @author: Daniel Corroto Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits: 1634 = 1^4 + 6^4 + 3^4 + 4^4 8208 = 8^4 + 2^4 + 0^4 + 8^4 9474 = 9^4 + 4^4 + 7^4 + 4^4 As 1 = 1^4 is not a sum it is not included. The sum of these...
''' Created on Mar 19, 2014 @author: Daniel Corroto Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). If d(a) = b and d(b) = a, where a != b, then a and b are an amicable pair and each of a and b are called amicable numbers. For example, the proper divisors of 2...
''' Created on Mar 19, 2014 @author: Daniel Corroto The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... Let us list the factors of the first seven triangl...
from enum import Enum from random import choice class Methods(Enum): NN = 0 NV = 1 VV = 2 NC = 3 class Types(Enum): "Types of words that can occur in dictionaries" NOUN = 0 VERB = 1 CUSS = 2
#HackerRank #Print Function #Solution #For PYTHON 3 n = int(input()) for i in range(1,n+1): print(i,end="")
"""String Methods .strip() #removes spaces at the ends of the string .split() #changes on string into a list of strings .join() #puts together a list of strings into one string .center() #centralizes a string by adding spaces at the sides .replace() #exchanges one type of word with another in a string .lower() #changes...
# program to check if a number is even or odd # 25.02.21 """Hi! Welcome to my even or odd number checker. To begin please enter a number below... """ num1 = int(input('Enter a number: ')) if num1%2 == 0: print('The number entered is even') elif num1%2 !=0: print('The number you entered is odd')
#We will use our made classifier to predict the features :[4,2,1,1,1,2,3,2,1],[4,9,7,6,8,5,4,9,7]; #We will also get the accuracy of our classifier #NOTE; # 1- We recreate our data by framing it into dictionary format; # 2- We split the data ourselves into training and testion set; # 3- We train the training data and ...
from nltk.stem import PorterStemmer from nltk.tokenize import word_tokenize ps=PorterStemmer() example_words=["python","pythoner","pythoning","pythoned"] # for w in example_words: # print(ps.stem(w)) new_text="it is very important to be pythonly while pythoning with python." words=word_tokenize(new_text) for w in ...
#!/usr/bin/env python3.6 from Credentials import Credentials from User import User def create_account(user_name,password): ''' Function to create a new account ''' new_account = User(user_name,password) return new_account def save_user_detail(user): ''' Function...
import pygame import common, graphics from pygame.locals import * pygame.init() def spawn_mob(): # to_spawn=0 if common.round<=5: to_spawn=common.round*2 elif common.round<=10: to_spawn=common.round*3 elif common.round<=20: to_spawn=common.round*2 else: to_spawn=common.round # class Zombie(object): de...
def cipher(string): result = '' for char in string: if char.islower(): result += chr(219 - ord(char)) else: result += char return result if __name__ == '__main__': s = 'Test Stringa' print s print '\nEncode' print cipher(s) print '\nDecode' pr...
#1.Write a program that uses input to prompt a user for their name and then welcomes them. name = input('Enter your name') print('Welcome',name) #2.Write a program which prompts the user for a Celsius temperature, convert the temperature to Fahrenheit, and print out the converted temperature.""" celsius = float(in...
''' [linha 45] Deveria trabalhar com k[i+1] e k[i] pois quando i=0, k[i-1] = k[-1] = 20 (primeiro teste). Essa também é a causa da lentidão do programa. ** Nesse caso, precisaria adicionar 1 ao k final pois o último a ser testado foi o k[i+1]. [linha 53 e 58] 'if' e 'else' desnecessários. [linha 76] Precisa adic...
''' Gabriella - [linha 45] Erro na condição para o programa não rodar para um x inicial com derivada próxima de zero: usou '>' em vez de '<' (feito) - [linha 52] Erro na função para o valor da raíz: usou 'dxi' em vez de 'derivada(xi)' (corrigido) 2.5/5 ''' # -*- coding: utf-8 -*- """NR Automatically gene...
def quick_sort(nums): """ Быстрая сотрировка""" n = len(nums) if n < 2: return nums low, same, high = [], [], [] pivot = nums[n // 2] for i in range(n): if nums[i] < pivot: low.append(nums[i]) elif nums[i] > pivot: high.append(nums[i]) ...
from sklearn.feature_extraction.text import CountVectorizer #一个语料库 corpus = [ 'This the the first document.', 'This document is the second document.', 'And this is the third one.', 'Is this the first document?', ] vectorizer = CountVectorizer(ngram_range=(2,2)) X = vectorizer.fit_transform(corpus) prin...
# -*- coding:utf-8 -*- # python解释器查找变量顺序:L > E > G > B def get_pass_100(val): print('%x' % id(val)) # local passline = 60 if val >= passline: print("pass") else: print("fail") def in_func(): # (val, ) print(val) in_func() # 返回函数名(函数对象入口地址) return in_func ...
""" Directories module contains directory specific manipulation rules. Please note that those rules which can be used for files and directories are located in other modules like :mod:`hammurabi.rules.operations` or :mod:`hammurabi.rules.attributes`. """ import logging import os from pathlib import Path import shutil ...
file = open("output_data.txt", "w") with open("file_data.txt", "r") as myfile: data = myfile.readlines() rev_data = data[::-1] file.writelines(rev_data) print(rev_data) if file.mode=="r": contents = file.read() print(contents) print(len(contents)) print(type(contents)) fil...
import turtle name = [] marks = [] students = [ {"name":"charan","marks":[213]}, {"name":"mitra","marks":[321]}, {"name":"rahul","marks":[123]}, {"name":"nithin","marks":[202]}, {"name":"shreeya","marks":[316]}, {"name":"sai","marks":[167]}, {"name":"adithya","marks":[234]}, {"name":"kaushik","marks":[300]...
#To use the functions in another file in python import arithmetic_functions x = int(input("Enter the first number: ")) y = int(input("Enetr the second number: ")) # ADD z = arithmetic_functions.add(x,y) print("The sum of x and y is : %d"%(z)) # DIFFERENCE z = arithmetic_functions.sub(x,y) print("The differnc...
def basiccalculator(s): if not s: return 0 num = 0 stack = [] sign = '+' for i in range(len(s)): if s[i].isdigit(): num = num*10 + int(s[i]) elif (not s[i].isdigit() and not s[i].isspace()) or i == len(s)-1: if sign =='-': st...
num="90" if(num===90): print("number is greater than 100") else: print("number is less than 100")
# # December 4 import time T1 = time.time() import numpy as np # Import input with open('dec4_input.txt','r') as fin: lower_limit,upper_limit = fin.read().split('-') # Initialise password counters to 0 pw_counter = 0 pw_counter2 = 0 # Loop through all numbers which fulfill the "no decreasing digits" rule for k...
''' 349. Intersection of Two Arrays DescriptionHintsSubmissionsDiscussSolution Given two arrays, write a function to compute their intersection. Example 1: Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2] Example 2: Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [9,4] Note: Each element in the result must...
list1 = [] x = 0 count = 0 limit = int(input("How many numbers would you like to sort?")) while x < limit: if x == 0: num = float(input("Please input your numbers")) list1.append(num) x = x + 1 else: num = float(input()) list1.append(num) x = x +...
import random import operator class Student(object): def __init__(self, name, age, marks, rollNumber): self.name = name self.age = age self.marks = marks self.rollNumber = rollNumber def __str__(self): return "Name - {0}, Age - {1}, Marks - {2}, Roll Number - {3}".forma...
names = ["Alex","John","Mary","Steve","John", "Steve"] name_check=[] for n in names: if not n in name_check: name_check.append(n) names= name_check print(names)
list =[] def display3(): print("Here is your list of stores: ") for i in range(0,len(list)): print(f'{i+1} - {list[i].title}') def display2(): print("Here is your shopping List") for i in range(0,len(list)): print(f"{list[i].title}") for m in range(0,len(list[i].item_list)): ...
""" Code Challenge Name: Webscrapping ICC Cricket Page Filename: icccricket.py Problem Statement: Write a Python code to Scrap data from ICC Ranking's page and get the ranking table for ODI's (Men). Create a DataFrame using pandas to store the information. Hint: #https://www.icc-cr...
"""File for storing the Coordinate class""" from math import sqrt class Coordinate: """Class for storing the x and y coordinates of a region""" def __init__(self, xray, yankee): """Creates a cordinate from a given x and y""" self.xray = xray self.yankee = yankee @classmethod de...
"""File for storing the Police class""" from random import randint from .fightable import Fightable from .fleable import Fleable from .forfeitable import Forfeitable class Police(Fightable, Fleable, Forfeitable): """The police npc""" def __init__(self, target_region, target_fuel_cost): self.name = "Po...
#!/usr/bin/env python # -*- coding: utf-8 -*- def func ( x ) : return x*x print func(3) #Делаем присваивание имени A = func print A(3) #Делаем присваивание имени функции func = u"This is not function" print func print A(3) #Работа функции как объекта 1-ого типа def oper( L, function ) : Res = []...
subjectEntities=[] def addSubject(id, subjectName, stream): "store the subject inside the subject data list. return True if operation is successful" for subject in subjectEntities: if subject["id"]==id: return False; if subject["subjectName"]==subjectName : print("Two ...
from StudentDataCenter import* from StudentSubjectRelation import getRelationshipsByStudentId ########################################################################### def isValidStudentId(studentId): if studentId[:2]!="ST" or not(studentId[2:].isdigit()): print("Student Id is invalid") return...
def multiply(number, otherNumber) : """ Takes two integers and returns product """ if otherNumber == 0 : return 0 product = number + multiply(number, otherNumber - 1) return product print(multiply(4, 5)) print(multiply(1, 2)) print(multiply(4, 1)) print(multiply(10, 8)) print(multiply(0, 6)) print(mult...
def ones (number): result="" if number==1: result=" One" if number == 2: result= " Two" if number == 3: result= " Three" if number == 4: result= " Four" if number == 5: result= " Five" if number == 6: result= " Six" if number == 7: result= " Seven" if number == 8: result= " Eight" if number =...
a=1 b= int (input ("Enter a number:")) while a<=10: print ( b, "x", a, "=", (a*b)) a=a+1