text
stringlengths
37
1.41M
''' Sudoku is a number-placement puzzle. The objective is to fill a 9 × 9 grid with numbers in such a way that each column, each row, and each of the nine 3 × 3 sub-grids that compose the grid all contain all of the numbers from 1 to 9 one time. Implement an algorithm that will check whether the given grid of numbers...
# Definition for singly-linked list: # class ListNode(object): # def __init__(self, x): # self.value = x # self.next = None # def mergeTwoLinkedLists(l1, l2): if(l1 == None): return l2 if(l2 == None): return l1 newlist = ListNode(0) temp = newlist prev = temp while(l1 ...
''' Given a binary tree t and an integer s, determine whether there is a root to leaf path in t such that the sum of vertex values equals s. ''' # # Definition for binary tree: # class Tree(object): # def __init__(self, x): # self.value = x # self.left = None # self.right = None # def hasPathUtil(ro...
#Problem : Matching Datasets #Language : Python #Compiled Using : py_compile #Version : Python 2.7.8 #Input for your program will be provided from STDIN #Print out all output from your program to STDOUT from __future__ import print_function import sys from copy import copy data = sys.stdin.read()...
# Define your compute function here. # run python -m unittest test.hamming_test to ensure the # unit tests pass and your code meets all of the conditions. # def compute(str1, str2): if len(str1) == len(str2): #string must be the same length return sum(x != y for x, y in zip(str1, str2)) #iterate over and c...
#/usr/bin/python #-*- coding:utf-8 -*- from random import randint def RandomizedPartition(a, p, r): i = randint(p, r) a[i], a[p] = a[p], a[i] return Partition(a, p, r) def Partition(a, p, r): i, j, x = p+1, r, a[p] while True: while a[i] < x and i < r: i += 1 while a[j] > x: j -= 1 if i >= j...
def main(): infile = open("WORDS2.txt","r") data = infile.readlines() infile.close() templist = [] wordlist = [] numberlist = [] for i in data: templist.append(i[:-1]) for i in templist: if i.isnumeric(): numberlist.append(int(i)) else: ...
class Stack_front(object): def __init__(self): self.array = [] def __str__(self): text = '' for i in self.array: text += "|{0:^10}|\n".format(i) return text def isEmpty(self): if len(self.array) == 0: return True else: ...
class Organism(): '''A living thing that lives in a tide pool''' def __init__(self,name,x,y): '''A living thing that is at location (x,y) in the tide pool.''' self.name = name self.x = x self.y = y def __str__(self): '''Return a string representation of this Or...
# Name: Tan Tze Guang # Class: 13S28 # Date: 4 April 2013 # This program calculates retail prices using data from input file def gatherData(file): # Receives data and creates the lists needed for output quantityList = [] priceList = [] discountList = [] subtotalList = [] total = 0 for line in ...
# Name: Tan Tze Guang # Class: 13S28 # Date: 29 April 2013 # program: HIGHEST.py # This program compares the day's scores to get the highest score # Then it compares the highest score so far to the best of the day # overwrites the highest score if defeated def highest(compare): if compare[0][1] > compare[1][1]: ...
def main(): infile = open("HIGHEST.txt","r") data = infile.readline() current_name,current_highscore = data.split(',') new_highest = '' new_highscore = 0 more = True while more: name = input("Enter player name: ") valid = False while not valid: score = ev...
def main(): number = eval(input("Input a number: ")) number = str(number) digits = number.split() digits = digits.reverse() print("The reversed number is: ",digits) main()
class Stack(object): def __init__(self): self.data = None self.top = None def Create(self): self.data = [] self.Top = 0 def Push(self,item): self.data.append(item) self.Top += 1 def Pop(self): if self.Top == 0: return "No ite...
# Name: Tan Tze Guang # Class: 13S28 # Date: 11 April 2013 # This program to store the employee data. def validate_dept(dept): if len(dept) > 6: print("Department name is only 6 characters long.") return True return False def validate_ID(ID,List): if not len(ID) == 6: print("ID sho...
size = input("Start from: ") intSize = int(size) myArray = [i for i in range(intSize,intSize+10)] reversal = [] for num in myArray[::-1]: reversal.append(num) print("Generated array of 10 elements") print(myArray) print(reversal)
#File: convert distance for km to miles def main(): print("This is a program to convert km to miles") dist_km = eval(input("What is the distance in km? : ")) dist_miles = dist_km * .62 print("The distance is",dist_miles,"miles") main()
# Name: Tan Tze Guang # Class: 13S28 # Date: 28 March 2013 # This program determines a person's BMI and determines # whether they are healthy or not def main(): weight = eval(input("What is your weight in Kilograms: ")) height = eval(input("what is your height in Metres: ")) BMI = weight / height**2 ...
class Stack(object): def Create(self, data = [],top = None): self.data = data self.length = 0 self.top = top def isEmpty(self): return self.length == 0 def Push(self,item): self.data.append(item) self.length += 1 self.top = self.length - ...
# Name: Tan Tze Guang # Class: 13S28 # file: DISPLAYEMPLOYEE / UPDATEEMPLOYEE import os.path def validateSalary(salary): if salary >= 600.00 and salary <= 5000.00: return False else: print("Salary is out of range") return True def validateRate(rate): if rate >= 5.00 and rate <= 12...
# Power digit sum # Problem 16 # 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. # # What is the sum of the digits of the number 2^1000? import time t = time.time() num = 2**1000 num_str = str(num) length = len(num_str) somme = 0 for i in range(length): somme += int(num_str[i]) print(somme) pr...
# Largest palindrome product # Problem 4 # A palindromic number reads the same both ways. The largest palindrome made from # the product of two 2-digit numbers is 9009 = 91 × 99. # Find the largest palindrome made from the product of two 3-digit numbers. import time t = time.time() palin = [] for i in range(100, 10...
# Fibonacci Init Function def initFib(n): if n == 1: return 1 elif n == 0: return 0 else: return initFib(n-1) + initFib(n-2) # Fibonacci Generator Function def generate(x): for i in range(x): print(initFib(i+1))
# -*- coding:utf-8 -*- ''' Created on 2017年2月9日 @author: xiang ''' # Dictionary # key : value # Create a dictionary phone_book = {'Tom' : 123, 'Jerry' : 456, 'Kim' : 789} # no any constrain for type mixed_dict = {'Tom' : 'boy', 11 : 23.5 } print("Tom has phone number: " + str(phone_book['Tom'])) # alter value of "To...
# -*- coding:utf-8 -*- ''' Created on 2017年2月10日 @author: xiang ''' # File IO # 1. Write file # 2. Read file some_sentences = '''\ I love learning python because python is fun and also easy to use 床前明月光, 疑是地上霜, 举头望明月, 低头思故乡。 ''' # 1. Write a file # Open for 'w'riting f = open('sentences.txt', 'w') # file is create...
import random WORDS_FILE = "words.txt" def getWords(): print("Loading word list from file...") data = open(WORDS_FILE, 'r') line = data.readline() wlist = line.split() print(" ", len(wlist), "wWrds loaded.") return wlist def pickWord(wordlist): return random.choice(wordlis...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jan 28 14:20:42 2019 @author: carlosponce """ """ Implement a function that calculates the probability of rolling exactly two 3’s in k rolls of a fair die. Use this function to plot the probability as k varies from 2 to 100. """ import math import p...
def computeminrefill(distance, tank, stops): num=0 before=0 i=0 stops.append(distance) print(stops) while i<len(stops): if stops[i]-before<=tank : i+=1 continue elif stops[i]-stops[i-1]>tank or i==0: re...
def is_pallindrome(s): s=s.lower() if s==s[::-1]: return "Pallindrome" else: return "Not pallindrome" print(is_pallindrome("abaa"))
"""Sum of all mersenne numbers present in an array Given an array of integers arr[], the task is to nd the sum of all the Mersenne numbers from the array. A number is a Mersenne number if it is greater than 0 and is one less than some power of 2. First few Mersenne numbers are 1, 3, 7, 15, 31, 63, 127, … Examples: Inpu...
def palindrome_permute(a): a=a.lower() s=dict() count=0 for i in a: if i!=" ": if i in s: s[i]+=1 else: s[i]=1 for i in s: if s[i]%2!=0: count+=1 print(s) if count==1: return "pallindrome permutation Allowed" else: retu...
"""Bastin once had trouble finding the numbers in a string. The numbers are distributed in a string across various test cases. There are various numbers in each test case you need to find the number in each test case. Each test case has various numbers in sequence. You need to find only those numbers which do not conta...
# this module is responsible for reading a csv file and storing it in a list import csv def read(file): categories = [] with open(file, 'r', encoding='utf-8') as csvfile: archive = csv.reader(csvfile, delimiter=',') next(archive) for column in archive: aux = {"Category": st...
from math import ceil def calculate_remainder(target, num): return ceil(target / num) * num - target def calculate_closest_multiple(target, nums): lowest = nums[0] remainder = calculate_remainder(target, lowest) for num in nums[1:]: r = calculate_remainder(target, num) if r < remain...
def rotate_waypoint(x, y, direction, amount): if amount == 180: # Flip the waypoint return -x, -y if amount == 270: direction = 'L' if direction == 'R' else 'R' if direction == 'L': return -y, x if direction == 'R': return y, -x def move_waypoint(x, y, direction, am...
#Martian's Technology Dictionary import csv from tkinter import * import tkinter.messagebox as box master = Tk() #First Interface - earch entry label0 = Label(master, text = 'Number', relief = 'groove', width = 40) Number = Entry(master, relief = 'groove', width = 40) label1 = Label(master, text = 'Word', relief =...
a=int(input()) l=list() i=0 for i in range(a): x=int(input()) l.append(x) c=sum(l) avg=c/a print(avg)
''' if выражение: --->тело_условия else: --->тело_условия_2 ''' a = int(input('Введите число: ')) b = int(input('Введите число: ')) if a % 2 == 0 and b % 2 == 0: print('Оба числа четные!') else: print('Одно число не является четным!') ''' Task 1. Напишите программу, которая сравнивает два числа и пишет, как...
"""Task 3. Факториал числа""" # 3! = 1 * 2 * 3 n = int(input('Вводите число: ')) res = 1 for i in range(1, n + 1): res *= i print(f'{n}! = {res}')
'''Task 5. Количество нулей''' zeros = 0 for i in range(int(input('Сколько чисел вводить будем? '))): if int(input(f'Введите число {i + 1}: ')) == 0: zeros += 1 print(f'Вы ввели {zeros} нулей.')
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import random QUOTES = ["Without sugar.", "With one sugar.", "With too many sugar.", "With a pinch of sugar.", "With three spoon of salt because I hate you. Really.", "With a bit of milk.", "Wait did I put a sugar? I'm not sure...", ""] def quote(): ...
# calculate remaining balance after each month and output remainder after a year balance = 999999 annualInterestRate = 0.18 def interestAfterMonths(balance, annualInterestRate, payment, numberOfMonths): for i in range(numberOfMonths): balanceAfterPayment = balance - payment interestDue = (annual...
import unittest from binary_search_tree import * class TestPriorityQueue(unittest.TestCase): def test_tree_minimum(self): t = BinarySearchTree() t.tree_insert(Node(key=5)) t.tree_insert(Node(key=6)) t.tree_insert(Node(key=2)) t.tree_insert(Node(key=3)) t.tree_inse...
money = 1000 - int(input()) coin = [500,100,50,10,5,1] cnt = 0 for i in coin: cnt += money // i money %= i print(cnt)
"""A number-guessing game.""" import random number = random.randint(1,100) # Put your code here print('Howdy, Whats your name?') #input the name and save it to a variable name = input("type in your name:") # we need to generate a random number between 1 and 100 print("I am thinking of a number between 1 and 100") ...
import cv2 #Import the selected image from main import img # Default image #img = cv2.imread("Resources/FotosMangoReducidas/IMG_0359.jpg") # Dimensions of the image (h, w, d) = img.shape # Clean resize without afecting the ascpect ratio print("Put a new dimension of the width to resize the image: ") r = 0 try: ...
precision = 100000 sum = 0 for number in range(1, precision): term = (1 / (number ** 2)) sum += term pi = ((sum * 6) ** (1/2)) print(pi)
# Python Variables # These are containers for storing data values # Creating variables x = 5 y = "Jhon" print(x) print(y) # Variable do not need to be declared with any particular type and even change type after they have been set # x set to String from integer x = "Sam" # x set to Integer from String again x = 10 ...
#My magic 8 ball program def main(): import random ballanswers = ['It is certain', 'It is decidedly so', 'Without a doubt', 'Yes Definitely', 'You may rely on it', 'As I see it yes', 'Most likely', 'Outlook good', 'Yes', 'Signs point to yes', 'Reply Hazy, try again', 'Ask me later', 'Better not tell...
import pandas as pd grades_dict = { "Wally": [87, 96, 79], "Eva": [100, 87, 90], "Sam": [94, 87, 90], "Katie": [100, 81, 82], "Bob": [83, 65, 85], } # keys in a dictionary become the columns and the values become the rows # there would be 5 columns for each student and 3 rows for each test grades ...
# Faça um Programa que pergunte quanto você ganha por hora e o número de horas trabalhadas no mês. Calcule e mostre o total do seu salário no referido mês, sabendo-se que são descontados 11% para o Imposto de Renda, 8% para o INSS e 5% para o sindicato, faça um programa que nos dê: # salário bruto. # quanto pa...
def maxcontsub(A): '''Maximum Value Contiguous Subsequence.''' M=[None for x in A] for i in range(len(A)): if i == 0: M[i] = A[i] else: M[i] = max( M[i-1] + A[i] , A[i] ) return M print maxcontsub([1, -3, 5, -2, 9, -8, -6, 4])
def merge(a, b): ''' Merges two sorted lists. ''' indexA = 0 indexB = 0 c = [] while indexA < len(a) and indexB < len(b): currA = a[indexA] currB = b[indexB] if currA < currB: c.append(currA) indexA += 1 else: c.append(currB) indexB += 1 if indexA < len(a): c += a[indexA:] elif indexB < l...
import unittest from bst_v import * class TreeTest(unittest.TestCase): def runTest(self): a = BST(1) a.insert(2) a.insert(2) a.insert(3) a.insert(0) self.assertEqual(str(a), "[[None, 0, None], 1, [None, 2, [None, 3, None]]]") a = BST(7) a.insert(5) a.insert(10) a.insert(4) a.insert(6) a.insert...
n = int(input("How many values would you like to take?")) sum = 0 while n < 0: n = int(input("I said how many... n can only take a positive value, try again")) for i in range(0, n, 1): val = int(input("Input value: ")) sum += val print(sum)
def add_two_largest(a_list): '''(list) -> number Returns the addition of the two largest numbers in a list received as argument. ''' max1 = max(a_list) index_max1 = a_list.index(max1) a_list.remove(max1) max2 = max(a_list) MAX = max1 + max2 a_list.insert(index_max1, max1) ...
a = [1,2,3,4,5,4,3,3,2,1,1] b = [] for i in a: if not i in b: b.append(i) print(b)
def zip(a, b): if len(a) != len(b): return 0 i = 0 c = [] while i < len(a): c.append([a[i], b[i]]) i += 1 return c print(zip([1, 2, 3], ["a", "b", "c"]))
""" class mit: def __init__(self): print("in const") def cs(self): print("cs") m1=mit() print(mit.__doc__) m1.cs() class mit: def __init__(self,a,b): self.a=10 self.b=20 def cs(self): print("cs") m1=mit(10,20) print(mit.__doc__) class mit: def __init__(s...
class Test: def sum(self,a=None,b=None,c=None): if a!=None and b!= None and c!= None: print('The Sum of 3 Numbers:',a+b+c) elif a!=None and b!= None: print('The Sum of 2 Numbers:',a+b) else: print('Please provide 2 or 3 arguments') t=Test() t.su...
"""" a=input("enter the value of a:") b=input("enter the value of b:") c=a+b print(c) a=bool(input("enter the value of a:")) b=float(input("enter the value of b:")) d=a+b print(d) a=10 b=bytes(a) print(b) lst=[10,20,3.9,"gaurang"] print(lst) lst[1]=100 print (lst) lst[-1]=100 print (lst) lst=[10,3.9,True] print(ls...
""" a=10 b=bin(a) b1=oct(a) b2=hex(a) print(b) print(b1) print(b2) a=bin(2) b=a<<1 print(b) a=10 b=bin(a) b=a<<2 print(b) a=10 b=20 x=a y=b print("a's value is",a,"and","b's value is",b) print("a's value is {} and b's value is {}".format(a,b)) print("a's value is {0} and b's value is {1}".format(a,b)) print("hello\...
a=-10 b=10.063 c="gaurang" d=True e=["car","bike"] f={ "car","bike"} g=4.0+4.0569j print("the type of a ",(type(a))) print("the type of b ",(type(b))) print("the type of a ",(type(c))) print("the type of a ",(type(d))) print("the type of a ",(type(e))) print("the type of a ",(type(f))) print("the type of a ",(type(g)...
# a ={"key1":"arpit1","key2":"arpit2","key3":"arpit3"} # print(a['key1']) # print("Enter value1 :") # a=input() # print("Enter value2 :") # b=input() # try: # print("sum=", # int(a)+int(b)) # except exception as e: # print(e) # print("this line is very impportant")
def next_palindrome(n): n=n+1 while not is_palindrome(n): n+=1 return n def is_palindrome(n): return str(n)==str(n)[::-1] if __name__=="__main__": size=(int(input("Enter size of the list ="))) numlist=[] for i in range(size): numlist.append(int(input("Enter the number of...
import random def rohanmultiplication(number): wrong=random.randint(0,9) table=[i*number for i in range(1,11)] table[wrong]=table[wrong]+random.randint(0,number//2) return table def iscorrect(table,number): for i in range(1,11): if table[i-1]!=i*number: return i-1 return ...
def linha(): print('='*50) def espaco (): print ('') linha () print ('Bem vindo!!Neste jogo você se tornara o investigador e salvará o carnaval!') linha() print ('Onde está o ChameGIT?') print('O cantor Promp Pyano escreveu um forró eletrônico que irá estourar no carnaval pós pandemia.\n\ Porém na sua ida ao...
# Author :lixinhao import random def roll_s(numbers = 3,s_list = None): print('<<<Roll大小>>>') if s_list is None: s_list = [] while numbers > 0: s = random.randrange(1,7) s_list.append(s) numbers = numbers - 1 return s_list def roll_b(tt): big = ...
import sys words = sys.stdin.readlines()[0].split(" ") players = int(words[0]) marbles = int(words[6]) current_player = 0 board = [0] position = 0 score = [0] * players for marble in range(marbles): marble += 1 if len(board) == 1: board.append(marble) position += 1 elif marble % 23 == 0: a = (positio...
################################### # ファイル ################################### # 書込 file = open("file.txt","w") file.write("line1\n") file.write("line2\n") file.close() # 読込 filename = "file.txt" file = open(filename, "r") for line in file: print(line) # line1 line2 file.close() # 存在確認 import os.path if os.path....
""" 移除某个时间点之后提出的问题, 以及它们的答案. 在程序出问题时使用 """ from datetime import datetime import pymongo t = datetime(2016,3,11,18,0,0) db = pymongo.MongoClient('127.0.0.1', 27017).zhihu_data q_colls = ["19550517_q", "19551147_q", "19561087_q", "19553298_q"] for q_coll in q_colls: coll = db.get_collection(q_coll) acoll = d...
# insertion sort with two for loops def insertion_sort(A): for i in range(1, len(A)): for j in range(i-1, -1, -1): if A[j] > A[j+1]: A[j], A[j+1] = A[j+1], A[j] else: break A = [1, 3, 6, 4, 2, 7, 0] insertion_sort(A) print(A) # insertion sort with ...
# !/usr/bin/python3 """ http://adventofcode.com/2017/day/9 autor: Martin Javorka """ class Day9: def __init__(self): self.input = list() self.registers = list() self.max = 0 self.read_file() self.parse_input() def read_file(self): with open("input", 'r') as f...
# !/usr/bin/python3 """ http://adventofcode.com/2017/day/10 author: Martin Javorka Used axial coordinates: NW|N | --+--+-- SW| |NE --+--+-- |S |SE Distance from the center is just (abs(x) + abs(y) + abs(x+y)) / 2 TODO Study hexagonal grids: https://www.redblobgames.com/gr...
# -*- coding: utf-8 -*- # @Time : 2021/6/17 20:35 # @Author : Hu-y # @File : 7_isValid.py # 有效的括号 class Solution: def isValid(self, s: str) -> bool: # 判断字符串长度 if len(s) % 2 == 1: return False pairs = { ")": "(", "]": "[", "}": "{", ...
import pyttsx3 engine = pyttsx3.init() rate = engine.getProperty('rate') print('The current rate is: ', rate, ' Which is the default rate') rateInput = input('Change Rate? Y/N: ') if rateInput == 'Y' or rateInput == 'y': # change the rate of speech newRate = input('Enter New Rate: ') engine.set...
#!/usr/bin/env python """Nicely indent XML read from STDIN or a file.""" from os.path import basename from sys import argv, exit, stdin from xml.dom.minidom import parseString def read_data(fn): """Read data from STDIN or a file.""" if fn == '-': f = stdin else: f = open(fn, 'rb') re...
class Car: max = 20000 def __init__(x, speed=0, color=''): x.speed = speed x.color = color def run(self, speed): self.speed = speed def query(self): return self.speed @classmethod def getMax(cls): return cls.max * 0.8 @staticmethod def insuran...
data1 = [[1, 2, 3, -4, 5], [6, 7, 9, 0, 10], [1, 3, 5, 7, 9], [2, 4, -6, 8, 10]] for r in data1: sum = 0 for c in r: if c < 0: print('got an outlier:%d' % c) # continue break # else: sum += c else: print('summatio...
def foo(): y = "local" print('inside y=%s' % y) foo() # print(y) x = 5 def bar(): x = 10 print("local x=%d" % x) bar() print("x=%d" % x) def outer(): x2 = "local" def inner(): nonlocal x2 x2 = "non local" print(f"inner:{x2}") print(f"outer1:{x2}") inner() ...
persons_1 = int(input()) persons_2 = int(input()) persons_3 = int(input()) desks_1 = persons_1 // 2 + persons_1 % 2 desks_2 = persons_2 // 2 + persons_2 % 2 desks_3 = persons_3 // 2 + persons_3 % 2 print(desks_1 + desks_2 + desks_3)
num = int(input()) sum_ = 0 sum_ += num % 10 num //= 10 sum_ += num % 10 num //= 10 sum_ += num % 10 print(sum_)
CHICKEN_PRICE = 23 GOAT_PRICE = 678 PIG_PRICE = 1296 COW_PRICE = 3848 SHEEP_PRICE = 6769 money = int(input()) if money < GOAT_PRICE: if money < CHICKEN_PRICE: print("None") else: chickens = money // CHICKEN_PRICE print(chickens, "chicken" if chickens == 1 else "chickens") elif money < C...
# Author: Bishal Sarang # Import Visualiser class from module visualiser from visualiser.visualiser import Visualiser as vs """ Given an array of numbers, find all the subsets: eg: nums = [1, 2, 3] Output: [[], [1], [2], [2, 1], [3], [3, 1], [3, 2], [3, 2 , 1]] You can find my explanation here...
import pandas as pd class Data_Lookup(): def __init__(self): pass def getData(self): sheetdata = input("Enter 1 if data is in 2 excel files, 0 if data is in same excel file with in 2 sheets : ") # sheetdata = 0 if int(sheetdata) == 1: filename1 = str(input("Enter File1 Name : ") + "....
import sys input_filename = sys.argv[1] with open(input_filename) as f: input = f.read() password = list('fbgdceah') def rotate(l, n): n %= len(l) return l[-n:] + l[:-n] for line in reversed(input.split('\n')): if line.startswith('rotate left'): offset = int(line.split()[2]) passw...
import sys input_filename = sys.argv[1] with open(input_filename) as f: input = f.read() def support_tls(line): inside = False tls = False for i in range(len(line) - 3): if line[i] == '[': inside = True elif line[i] == ']': inside = False elif line[i] ...
import turtle import random def screenLeftClick(x, y) : global r, g, b turtle.pencolor((r, g, b)) turtle.pendown() turtle.goto(x, y) def screenRightClick(x, y) : turtle.penup() turtle.goto(x, y) def screenMidClick(x, y) : global r, g, b tSize = random.randrange(1, 10) turtle.shapesi...
import pygame from colors import Colors class Track: def __init__(self, roads): self.roads = roads self.colors = Colors() def draw_vert_finish_line(self, screen): x_val = self.roads[-1].corners[-1][0] y_val = max([self.roads[-1].corners[-1][-1], self.roads[-1].corners[-2][-1]])...
x = 50 def func(): global x print('x equal', x) x = 2 print('Replace global value of x to', x) func() print('The value x is', x)
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Wed Oct 30 11:44:41 2019 @author: felipe 1 Do arquivo carros, imprima as primeiras e as últimas cinco linhas. Faça uma versão que abre o arquivo a partir do csv e outra que abre a partir da url. 2 Encontre o nome da empresa de carros mais cara ...
#!/usr/bin/env python # #*****************************************************************************80 def search_serial ( a, b, c ): #*****************************************************************************80 # ## SEARCH_SERIAL searches for a solution to an integer equation. # # Licensing: # # This code ...
n=int(input("enter the number of items :")) for x in range (1,n+1): if (x%2==0): print(x)
num=int(input()) temp=num sum=0 while(num>0): rem=num%10 sum=sum+rem**3 num=num//10 if(temp==sum): print("yes") else: print("no")
print("Write a program which accept number from user and return addition of digits in that number") print("\n") def Addition_Digit(num): idigit=0 while num>0: idigit+=num%10 num=num//10 return idigit num=(int(input("Enter number->"))) Ret=Addition_Digit(num) print("Addition of Digit is->",+Ret)
#!/usr/bin/env python """ Filter out all points in Switzerland """ import csv import sys import os from decimal import * DELIMITER = os.getenv('DELIMITER', ' ') NORTH = Decimal('47.9922193487799') WEST = Decimal('5.99235534667969') EAST = Decimal('11.1243438720703') SOUTH = Decimal('45.6769214851596') def in_switzer...
phrase = "Don't panic!" plist = list(phrase) print(phrase) print(plist) tapStr = plist[1:3:1] for e in plist[5:3:-1]: tapStr.append(e) for e in plist[7:5:-1]: tapStr.append(e) new_phrase = ''.join(tapStr) print(plist) print(new_phrase)
# -*- coding: utf-8 -*- """ Created on Thu Nov 12 13:30:03 2020 @author: babut """ def add(x,y): return x + y def substract(x,y): return x - y def multiply(x,y): return x * y def divide(x,y): return x/y print("select operation.") print("1.add") print("2.substract") ...
x = 65 for i in range(5): for j in range(i+1): print(chr(x+j), end=" ") print()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Sep 21 11:22:51 2021 @author: LaurenPark """ import turtle, math import turtle, random turtle.speed(550) panel=turtle.Screen() #panel set up w=600 h=600 panel.setup(width=w, height=h) #pseudocode initially indicated a while loop of circles, though a...