text
stringlengths
37
1.41M
n = int(input()) arr = [] for i in range(n): number = str(input()) arr.append(number) repeat = arr[0] count = 1 for i in range(1, len(arr)): if arr[i] != repeat: count += 1 repeat = arr[i] print(count)
import queue MAX = 100 INF = int(1e9) # Create node (vertex) class in which each vertex will # carry a distance cost class Node: def __init__(self, id, dist): self.dist = dist self.id = id # compare method def __lt__(self, other): return self.dist <= other.dist def Dijkstr...
import queue class PQEntry: def __init__(self, value): self.value = value def __lt__(self, other): return self.value > other.value n = int(input()) arr = list(map(int, input().split())) pq = queue.PriorityQueue() for x in arr: pq.put(PQEntry(x)) second = 0 third = 0 result...
def binarySearch(a, left, right, x): while left <= right: mid = (left + right) // 2 if x == a[mid]: return mid elif x < a[mid]: right = mid - 1 else: left = mid + 1 return -1 def binarySearchRecursive(a, left, right, x): if left <= right:...
class Node: def __init__(self): self.countLeaf = 0 self.child = dict() def addWord(root, s): tmp = root global flag global res for i in range(len(s)): ch = s[i] if ch in tmp.child: tmp = tmp.child[ch] if tmp.countLeaf > 0 or i == len(s) - 1: ...
class Node(): def __init__(self, data): self.data = data self.next = None class LinkedList(): def __init__(self): self.head = None self.tail = None def insert_tail(self, value): if self.tail is None: self.head = self.tail = Node(value) return...
arr = [] result = [] from collections import Counter as co class Node(): def __init__(self, data = 0): self.data = data self.next = None class LinkedList(): def __init__(self): self.head = None self.tail = None def insert_tail(self, value): if self.tail == None: ...
n = int(input()) arr = list(map(int, input().split())) new_arr = [] def insertion_sort(array): for i in range(1, len(array)): key = array[i] j = i - 1 while j >= 0 and key < array[j]: array[j + 1] = array[j] j -= 1 array[j + 1] = key return array new_...
n = int(input()) def check_first(num): if num < 10: return num return check_first(num // 10) if n < 0: print(check_first(-n)) else: print(check_first(n))
class Node: def __init__(self): self.countLeaf = 0 self.child = dict() def addWord(root, s): tmp = root global flag for i in range(len(s)): ch = s[i] if ch in tmp.child: tmp = tmp.child[ch] if tmp.countLeaf > 0 or i == len(s) - 1: ...
class Student(object): def __init__(self, name): self._name = name def __str__(self): return 'Student object (name : %s)' % self._name __repr__ = __str__ print(Student('Michael')) # Student object (name : Michael) class Fib(object): def __init__(self): self.a, self.b = 0, ...
from threading import Thread, Lock, Event import time, random mutex = Lock() #Interval in seconds MinIntervalOfCustomer = 2 #It is the minimum duration of customer MaxIntervalOfCustomer = 7 #It is the maximum duration of customer MinimumDurationOfHairCut = 3 #It is the minimum duration of customer MaximumDurationO...
""" data_tracker.Controller is a class for manipulating scraper objects. The idea is to have a single controller running that can use many scraper objects at different time intervals to keep track of various data. """ class Controller: class ControlledScraper(scrapers.BaseScraperClass): """ ControlledScr...
import sqlite3 conn = sqlite3.connect('submission1.db') with conn: cur = conn.cursor() cur.execute("CREATE TABLE IF NOT EXISTS tbl_filelists( \ ID INTEGER PRIMARY KEY AUTOINCREMENT, \ file_name TEXT \ )") conn.commit() conn.close() conn = sqlite3.connect('submission1.db') fileL...
#learning python commands print "Hello World" print "my name is Josie" print "lets count somethings" print "Boys", 25 + 30 / 6 print "Girls", 100 - 25 * 3 % 4 print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
""" household_power_consumption.txtの日時のフォーマットを変更する dd/mm/yyyy -> yyyy/mm/ddd """ import re class ReformException(Exception): pass def reform_date(date_string: str): """ >> reform(21/10/2020) 2020/10/21 >> reform(05/01/2020) 2020/01/05 """ result = re.search(r'(?P<day>\d+)\/(?P<month>\...
class Node: def __init__(self, value): self.left = None self.right = None self.value = value class BST: root: Node = None def __init__(self): pass def addNode(self, element): if self.root is None: self.root = Node(element) return ...
import re def get_inheritance_number(file): """Finds all the uses of inheritance from a file.\n :arg file: The file to be analyzed. :return: Count of inheritance usage """ regex = re.compile("class.*([^\\s]+).*:\\s*(virtual)?.*(public|private).*([^\\s]+)") file = open(file, mode="r", encoding=...
from sys import argv script, input_file = argv def print_all(f): print(f.read()) def rewind(f): f.seek(0) #将读写位置移动到文件开头 def print_a_line(line_count, f): print(line_count, f.readline()) #readline()会扫描文件的每一个字节,直到找到\n为止,然后停止读取文件,并返回此前发现的文件内容 #文件f会记录每次调用readline()后的读取位置,以便下次调用时读取下一行 current_file = open...
class Bag: def __init__(self, line): if line.count('contain no other bags.') > 0: # line = 'faded blue bags contain no other bags.' self.bag_name = line.split('bags')[0].strip() # 'faded blue' self.bags = {} else: # "shiny gold bags contain 1 dark oli...
# Traveling Salesman Problem # Pseudocode in tsp_pseudocode.txt from math import sqrt from numpy import inf from itertools import chain, combinations import time def subsets_with_first_element(lst): # input is a list # output: set of frozensets of all possible combinations of elements from input (**must incl...
#given a string of 0's and 1's, output a list of strings that have hamming distance 1 away def hDisOne(bit_string): res = set() for i in range(len(bit_string)): if bit_string[i] == '1': if i < len(bit_string) - 1: changed = bit_string[:i] + '0' + bit_string[i+1:] ...
'''Scrieti o functie care converteste in sir de caractere scris UpperCamelCase in lowercase_with_underscores. ''' string="haiSaVerificam" new=string for i in range(0,len(string)): if string[i].isupper(): new=new.replace(string[i],"_"+string[i].lower()) print new
# The function is expected to return an INTEGER. # The function accepts following parameters: # 1. INTEGER_ARRAY a # 2. INTEGER_ARRAY b # def getTotalX(a, b): # Write your code here total = 0 for i in range(max(a), min(b)+1): good = True for f in a: if i % f != 0...
if __name__ == '__main__': s = input() bools = [False] * 5 for c in s: if c.isalnum(): bools[0] = True if c.isalpha(): bools[1] = True if c.isdigit(): bools[2] = True if c.islower(): bools[3] = True if c.isupper(): ...
def minion_game(string): # your code goes here st = 0 kv = 0 vowels = 'AEIOU' for i in range(0, len(string)): c = string[i] if c in vowels: kv += len(string) - i else: st += len(string) - i if st > kv: print("Stuart {score}".format(score=s...
# This is essentially a brute force approach. It takes too long to run so a # more efficient algorithm is used in 071_ordered_fractions2.py from fractions import Fraction MAX_DENOMINATOR = 1000000 def main(): # Generate all the fractions and put them in order fractions = sorted(list(set(Fraction(n, d) ...
from datetime import date, timedelta def main(): start_date = date(1901, 1, 1) end_date = date(2000, 12, 31) # Start on the first sunday cur_date = start_date answer = 0 while cur_date != end_date: if cur_date.strftime("%A") == "Sunday" and cur_date.day == 1: print(cur_dat...
from helpers import helpers def is_abundant(n): # - n is to remove n as a factor return sum(helpers.factors(n)) - n > n def get_abundant_numbers(): return [n for n in range(12, 28124) if is_abundant(n)] def main(): abundant_numbers = get_abundant_numbers() sums_of_abundant_pairs = set() # C...
# This code will work, but it is too inefficient (will take an hour to run # probably). A better solution is implemented in 072_counting_fractions2.py # which uses a totient sieve. # # The number of extra fractions each denominator gives (that wasn't provided # by the previous denominators) is equal to d-1 if d is prim...
from helpers import helpers def is_lychrel(n): palindrom_candidate = n # Attempt the process 50 times for _ in range(50): # Add the reverse of the number palindrom_candidate += int(str(palindrom_candidate)[::-1]) # If we are left with a palindrome if helpers.is_palindrome(...
import itertools def generate_pentagonal(num_to_generate): for n in range(1, num_to_generate): yield n * (3*n - 1) // 2 def get_min_distance(): pentagonals = list(generate_pentagonal(10000)) set_pentagonals = frozenset(pentagonals) # For each pair of pentagonal numbers for i, pentagonal1 ...
from helpers import helpers UPPER_BOUND = 1000000 # Primes were stored as both a list and a set because lists are better for # iterating over whereas sets are better for determining if an element is a # member of that set. Both types were chosen as a significant amount of # iterating and using the "in" keyword were co...
MAX_RANGE = 1000000 def is_palindrome(n): string = str(n) return string == string[::-1] def is_double_palindrome(n): return is_palindrome(n) and is_palindrome(str(bin(n))[2:]) def main(): double_palindromes = [n for n in range(MAX_RANGE) if is_double_palindrome(n)] answer = sum(double_palindrome...
import itertools from helpers import helpers NUM_CONSECUTIVE = 4 def satisfies_criteria(candidate): for num_consecutive in range(NUM_CONSECUTIVE): cur_factors = set(helpers.prime_factors(candidate + num_consecutive)) # If there aren't the right number of factors if len(cur_factors) != NUM...
from datetime import date, datetime def check_func(year): current_year = date.today().year birth_year = int(year) age = current_year - birth_year if age < 18: return 'Minor' elif age == 18 or age <= 36: return 'Youth' elif age > 36: return 'Elder' if __name__ == '__...
# x is re-defined in scope of f # different x objects def f(y): x = 1 x += 1 print(x) x = 5 f(x) print(x) # x from outside g # x inside g is picked up from scope that called function g def g(y): print(x) print(x + 1) x = 5 g(x) print(x) # Local variable 'x' referenced before assignment def h...
# Conversion interger to binary num = 3602879701896397 # Add Flag if num < 0: isNeg = True num = abs(num) else: isNeg = False result = '' if num == 0: result = '0' while num > 0: result = str(num % 2) + result print(result) num = num//2 print(num) if isNeg: result = '-' + resu...
# TUPLES def quotient_and_remainder(x, y): q = x // y r = x % y return (q, r) (quot, rem) = quotient_and_remainder(4, 5) def get_data(aTuple): nums = () words = () for t in aTuple: nums = nums + (t[0],) if t[1] not in words: words = words + (t[1],) min_nums = ...
#comma reader #enter number of commas expected per line def findNumberCommasPerLine(numberOfCommasPerLine, filename): linenumber = 0 errorLines = [] with open(filename, 'r') as file: for line in file: linenumber = linenumber + 1 numCommas = line.count(',') if not...
#Задание1 a = 1 b = 2.2 c = 'Almaty' print(a, b, c) a = int(input("Введите целое число: ")) b = float(input("Введите дробное число: ")) c = (input("Введите слово: ")) print(a, b, c) #Задание2 a = int(input("Введите количество секунд: ")) if a >= 60: b = a // 60 a = a % 60 if b >= 60: ...
## Working with paths from pathlib import Path # Where am I? cwd = Path.cwd() print(cwd) # Combine parts to create full path and file name new_file = Path.joinpath(cwd, 'new_file.txt') print(new_file) # Dies this exist? print(new_file.exists()) ## working with...
num1 = 10 num2 = 10 print(num1) answer = num1 + num2 print("the answer is", answer) print("nice", answer)
# Numbers can be stored in vaiables pi = 3.14159 print(pi) # You can do math with numbers first_num = 6 second_num = 2 print(first_num + second_num) print(first_num ** second_num) # If you combine strings with numbers, Python get confused days_in_feb = 28 #print(days_in_feb + ' days in February') print(s...
## Syntax error ''' # This code won't run at all x = 42 y = 206 if x == y print('Success!!') ''' ## Runtime errors ''' # This code will fail when run x = 42 y = 0 print(x / y) ''' ## Catching runtime errors x = 42 y = 0 try: print(x / y) except ZeroDivisionError as e: # Optional...
import re code = input() pattern = r'(\d+\.)|(\.\d+)' for s in code.split(): if re.findall(pattern, s): print(s)
''' \d - a digit file_\d\d file_25 \w - alphanumeric \w-\w\w\w A-b 1 \s - white spaces a\sb\sc a b c \D - non digit \D\D\D ABC \W - non alphanumeric ...
#try, except, finally def add(n1,n2): print(n1+n2) add(10,20) number1=10 number2=input('please provide a number : ') add(number1,number2) print('something happened!') #this will not print because after an error it will stop executing ,so for that try: #want to attempt this code may have an error ...
def ran_check(num,low,high): if num in range(low,high): return print(f'{num} is in range of {low},{high}') else: return False #or def ran_bool(num,low,high): return num in range(low,high)
stock_prices=[('APPLE',200),('GOOGLE',400),('MICROSOFT',100)] for items in stock_prices: print(items) for items,prices in stock_prices: print(items,prices) print(prices+(0.1*prices)) #2 print('\n2 >\n') work_hours=[('ujjwal',40),('vishal',0.5),('mishra',1)] def employee_check(work_hours): cu...
game_list=[0,1,2] def display_game(game_list): print('Here is the game list : ') print(game_list) def postion_choice(): choice='WRONG' while choice not in ['0','1','2']: choice=input('Pick a postion (0,1 or 2) : ') if choice not in ['0','1','2']: print('Sorry ,in...
#by Poupae and Uzair vegetables = [ {"name": "eggplant", "color": "purple"}, {"name": "tomato", "color": "red"}, {"name": "corn", "color": "yellow"}, {"name": "okra", "color": "green"}, {"name": "arugula", "color": "green"}, {"name": "broccoli", "color": "green"}, ] #read in the csv file import csv with open(...
a = int(input("mutqagrel erankyan himqy: ")) b = int(input("mutqagrel erankyan bardzrutyuny: ")) print(a*b*0.5,"erankyan makeresy")
name = raw_input("Please enter your name: ") print ("Hi " + name) print "How are you"
from myqueue import queue class node: def __init__(self, data): self.data = data self.children = set() self.parent = None def setParent(self, parentNode): self.parent = parentNode def getParent(self): return self.parent def addChildren(self, newChildren): ...
def a(): x = 5 yield x x += 1 yield x example = a() print(next(example)) print(next(example))
class Animals: def __init__(self, name, size, noise, color, num_of_legs): self.name = name self.size = size self.noise = noise self.color = color self.num_of_legs = num_of_legs def describe(self): print('The {} is {} and makes the noise: {}'.format(self.name,...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import pygame, math WIDTH = 400 HEIGHT_WINDOW = 650 HEIGHT = 600 FPS_CAP = 60 class Color: BLACK = (0, 0, 0) GREY = (125, 125, 125) RED = (255, 0, 0) WHITE = (255,255,255) BLUE = (0, 0, 255) GREEN = (0, 255, 0) YELLOW = (255,255,0) ORANGE...
from enum import Enum class Weekday(Enum): MONDAY = 1 TUESDAY = 2 WEDNESDAY = 3 THURSDAY = 4 FRIDAY = 5 SATURDAY = 6 SUNDAY = 7 weekdays = (Weekday.MONDAY, Weekday.TUESDAY, Weekday.WEDNESDAY, Weekday.THURSDAY, Weekday.FRIDAY) weekends = (Weekday.SATURDAY, Weekday.SUNDAY) ...
""" @author:"zzg" @file:recursive_method.py @time:2020/7/8 9:46 递归/栈的调用(栈是先进后出) """ def fact(x): if x == 1: return 1 else: return x * fact(x - 1) def sum(arr): if len(arr) == 0: return 0 return arr[0] + sum(arr[1:]) if __name__ == '__main__': res = fact(5) p...
# bicycles = ['trek','cannondale','red','specializde'] # message = 'My first bicycle was a ' + bicycles[0].title() + '。' # print(bicycles) # print(bicycles[0]) # print(bicycles[0].title()) # print(bicycles[1]) # print(bicycles[3]) # print(bicycles[1].title()) # print(bicycles[3].title()) # print(bicycles[-1]) # print(m...
# magicians = ['alice','david','carolina'] # for magicians in magicians: # # print(magicians) # print(magicians.title() + ", that was a great trick!") # print("I can't wait to see your next trick," + magicians.title() + ".\n") # # print("Thank you, everyone. That was great magic show!") ''' 作业 1、用for打印...
class Car: def __init__(self, gas_level): self.gas_level = gas_level def add_gas(self, fl): return self.gas_level + fl def fill_up(self): if self.gas_level < 13.0: gas_left = self.gas_level - 13.0 self.add_gas(gas_left) else: return 0
favorite_language = ' python ' #while executing this line, it prints out 'python ' with an white space in terminal favorite_language.rstrip() # while executing this line, white space is removed only for this line of code favorite_language # prints out result similar to line 1 native_language = " Nepali " native_langua...
def nb_digit(val, nb_sig_digit=2): """ compute the number of digit after the point that needs to be considered to get 2 significant digits. """ val = abs( val ) nb_digit = nb_sig_digit-3 if val == 0. : return 2 while True: nb_digit +=1 if val/10 >=1.: retur...
from sys import exit """ Coleman-Liau index The formula for this is 0.0588 * L - 0.296 * S - 15.8 where L is the average number of letters per 100 words in the text, and S is the average number of sentences per 100 words in the text """ def coleman_liau_index(l, s): return 0.0588 * l - 0.296 * s - 15.8 def ma...
'''array manipulation class module''' import array from random import randrange class Board(): '''array manipulation class''' def __init__(self, cols=4, rows=4): '''object creation''' self.cols = cols self.rows = rows self.board = array.array('I', [0 for ...
# create class import platform x = dir(platform) print(x) class MyClass: x = 5 pi = MyClass() print(pi.x) # dengan __init__() class Person_1: def __init__(self, name, age): self.name = name self.age = age # create class method def greet(self): print('halo nama saya adalah:', ...
# day 31 2019-06-09 Sun # 124. Binary Tree Maximum Path Sum # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None # From 花花酱 https://www.youtube.com/watch?v=9ZNky1wqNUw class Solution(object): def _...
# day 37 2019-06-15 Sat # 169. Majority Element # Approach 1 class Solution: def majorityElement(self, nums) -> int: length = len(nums) if length < 2: return nums[0] nums.sort() count = 1 for i in range(length-1): if nums[i] == nums[i+1]: ...
import random import timeit import HeapSort import InsertionSort import MergeSortIterative import MergeSortRecursive import QuickSortDeterministic import QuickSortRandomized A = [] print("Total comparisons, exchanges and running time for value = 1000 are:") current_value = 100 for i in range(5): print("Calculat...
mail = input("Write down your e-mail...") a = input("Are you sure, that all is right?(Y/N)") base = ["a", 'b', 'c', 'd', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] if a == "Y": print("OK") elif a == "N": mail = input("Write your e-mail again.."...
def snail(snail_map): new_list = [] while len(snail_map) != 0: new_list.extend(snail_map[0]) snail_map.remove(snail_map[0]) if len(snail_map) == 0: break for i in snail_map: new_list.append(i.pop()) new_list.extend(reversed(snail_map[len(snail_map...
from random import * from tkinter import * # defining Window properties root = Tk() root.title("Rock Paper Scissors") choices = ["rock", "paper", "scissors"] messages = ["You Win", "Draw", "You Lose"] player_score = 0 cpu_score = 0 def win_check(player_input): global messages, choices, player_score, cpu_score ...
"""Module evaluating cards.""" from typing import Union from .card import Card from .hash import hash_quinary from .tables import ( BINARIES_BY_ID, FLUSH, NO_FLUSH_5, NO_FLUSH_6, NO_FLUSH_7, SUITBIT_BY_ID, SUITS, ) MIN_CARDS = 5 MAX_CARDS = 7 NO_FLUSHES = {5: NO_FLUSH_5, 6: NO_FLUSH_6, 7:...
#!/usr/bin/python #sorting list = [1,8,3,4,7,6,2,5,10,9] list.sort() print list ############################### rev = 0 a = (911,12,10,121,199,125) #print rev.sorted(a)
objectlist = [] def parse(sentence,noun,verb,adverb1): wordlist = sentence.split(" ") thisword = wordlist[0] #if thisword is 'on', then next word is the noun if thisword == 'on': noun = wordlist[1] #if wordlist is greater than 2 then we must have a verb if len(wordlist) > 2: trash,verb,adverb1 = parse(" "...
#!/usr/bin/env python # coding: utf-8 # In[ ]: # Author: Ram vriksh # #GRIP @The Sparskfoundation # # TASK 1:Prediction using supervised Machine learning # prediction of precentage of a student based on the number of study hours # # this is simple linear regression task as it involve only two variables # In[...
import numpy as np def vectorize(img, window_size): """ Slice image into blocks of size window_size and flatten them. Check this diagram: https://i.imgur.com/wycSwR3.png Args: img: numpy array with image values window_size: size of window. Length of vectors will be window_size ** 2 ...
#!/usr/bin/env python #Employer (mostly)endless loop import random import time fuckyou = random.randrange(1000000) answer = "Fuck you." while (fuckyou != 1): print("Employer: We need you to do 'X'.") print("Employee: Ok, I need 'Y' to do that.") print("Employer: ", answer) print("Employer: we need you to do 'X'."...
"""Functions that retrieve or are related to elemental or isotopic data.""" import numpy as np import re from astropy import units as u, constants as const from .elements import atomic_symbols_list, atomic_symbols_dict, Elements from .isotopes import Isotopes # The code contained within element_symbol(), isotope_sym...
class Conta: def __init__(self, titular, saldo): self.titular = titular self.saldo = saldo def sacar(self, valor): self.saldo -= valor return self.saldo def depositar(self): valor = float(input("Digite o valor a depositar: ")) self.saldo += valor def...
# class Mamifero(): # # Criando o método construtor, ele vai servir para já passar todos # # os atributos para os objetos que eu for criando # def __init__(self, nome, pelo, cor, idade, tamanho = "pequeno"): # self.nome = nome # self.pelo = pelo # self.cor = cor # self.taman...
# A basic program for learning if a number prime number number =int(input("Please enter a number: ")) def Is_Prime(number): if number > 1: for i in range(2,number): if number % i ==0.0: print("Not a prime number") break else: ...
paranoid_android = "marvin" # for sting for i in paranoid_android: print("\t", i) print('\t') print(paranoid_android) # for list of character objects phrase=list(paranoid_android) for ch in phrase: print("\t",ch) print(phrase) #for list to iterate over slice paranoid_android="Marvin, the Android Marvel ...
#Creating a date time object and extract the minute attribute before assigning it to the variable from datetime import datetime time_now = datetime.today() print(time_now) right_this_minute = time_now.minute print(right_this_minute)
#linear regression # uses least squares - minimises squared error # between each point and the line # A GOOD GUIDE TO FORMULA # https://www.dummies.com/education/math/statistics/how-to-calculate-a-regression-line/ # line is a slope value and a y intercept #slope intercept equation of a line y=mx+b #(ie in example -...
# ax**2 + bx + c = 0 import math a = eval(input('a : ')) b = eval(input('b : ')) c = eval(input('c : ')) d = (b**2) - (4*a*c) sol1 = (-b-math.sqrt(d)) /(2*a) sol2 = (-b+math.sqrt(d)) /(2*a) print('The solution are %f and %f '%(sol1,sol2))
#!/usr/bin/python3 """ Module: 5-island_perimeter""" def island_perimeter(grid): """island_perimeter [Find the perimeter of the island in grid] Args: grid (matrix): is a list of list of integers Returns: [int]: [perimeter of the island in grid] """ perimeter = 0 if grid ...
nums = [4,2,3] nums = [4,2,1] nums = [3,4,2,3] nums = [1,2,3,1] # mine class Solution: def checkPossibility(self, nums): for i in range(len(nums)): nums_copy = nums.copy() nums_copy[i] = nums_copy[i-1] if i>0 else float('-inf') if nums_copy == sorted(nums_copy): ...
from __future__ import division from common import approx_eq, improve def newton_update(f, df): def update(x): return x - f(x) / df(x) return update def find_zero(f, df): def near_zero(x): return approx_eq(f(x), 0) return improve(newton_update(f, df), near_zero) def sqrt_newton(a)...
# Задание 4: # Пользователь вводит целое положительное число.' # Найдите самую большую цифру в числе.' # Для решения используйте цикл whilе и арифметические операции') user_var = int(input('---> введите любое число ')) print('# Вы ввели',user_var ) count = 0 while user_var > count: digit = user_var % 10 ...
# create a function which accept a list you need to find how many list inside list #[1,2,3,[1,2],["4,5,6"]]-------->2 def listcount(l): s=type(l) i=0 for x in l: if type(x)==list: i+=1 return i num=[1,2,3,[1,2],["4,5,6"],['a','x']] print(listcount(num))
#list : ordered collection of items # we can store anything in list int float string..... a=[1,2,3,4,5] print(a) word=["raj", "Kumar",'Thakur'] print(word) mixed=[1,2,3,'raju','chaha',4,6,None] print(mixed) #to access element of list print(mixed[4]) print(mixed[3:5]) mixed[2]=3.0 #change element 3 with 3...
#for loop with range function #Print hello word with 10 times for i in range(1,11): # or we can write for i in range(10): 10 ---> 0 to 9 print(f"Hello World{i}")
import tkinter as tk class TopFrame(tk.Frame): def __init__(self, master=None): tk.Frame.__init__(self, master) self.grid(row=0, column=0, sticky="nsew") self.BottomFrame = tk.Frame(master=master) self.BottomFrame.grid(row=1, column=0, sticky="nsew") self.f1 = tk.Frame(ma...
# Ask name from user. # find the occorance of each character and count # for vimal Lohani v:1 i:2 m:1......... # actual solution is at last my solution is leangthy name=input("Please provide your full name :") i=j=0 k=len(name) print(k) count=1 val='' while i<k: val=name[i] j=i+1 # print(val) # pri...
name='Harshit' #center method is used to apply delemeter at front and end. but start from end # end ->start->end->start...... print(name.center(9,"*")) #*Harshit* here 9=length of name (7)+two starts(2) print(name.center(8,"*")) #Harshit* print(name.center(12,"*")) #**Harshit*** #Q: Input name...
#use snake case naming convention although camel case also works but prefer snake case # name_second_name -> snake case & nameSecondName->camelcase #no special symbol #firstcharacter is either character or _ only _name="vimal lohani" number1 =5 print(_name) print(number1) print(_name *3) name,age ="vimal",28 p...
first=0 last=1 add=0 print (first,"\n", last) for i in range(1,10): add=last+first first=last last=add print(add)