text
stringlengths
37
1.41M
from tkinter import * root=Tk() root.title("Calculator") #creating title of gui root.geometry("500x500") #dimension of gui root.minsize(500,500) root.maxsize(500,500) root.iconbitmap('D:\pes.ico') #icon strvalue=StringVar() #string variable strvalue.set("") #value is intial...
#Program that Remove Duplicates from the Array #Here are the Names original_names = ["Alex", "John", "Mary", "Steve", "John", "Steve"] #Loop through each Name, drop that name into a new array if the new array does not already contain that name (value). final_names = [] for i in original_names: if i not in final...
from cards import Card from deck import Deck deal_amount = [] def lucky_card(): d = Deck() d.shuffle() try: user = input("Hello! What's your name? ") deal_amount = int(input(f"How many random cards would you like to be dealt {user}? ")) if deal_amount >= 53: print("The...
file_name = "emails.txt" duplicate_free_emails = [] with open(file_name) as file_object: content = file_object.read() # print(content) emails = content.split(", ") # print(emails) for email in emails: if email not in duplicate_free_emails: duplicate_free_emails.append(email) print(duplicate_free_...
i1=input('enter radius:') r=float(i1) c=2*3.14*r print('circumference of circle=',c)
""" 1281. Subtract the Product and Sum of Digits of an Integer """ def sum_product(nums): sum=0 product = 1 final_op=0 for i in nums: sum = sum + i product = product * i final_op=sum + product return final_op if __name__ == '__main__': nums = 234 op = sum_product(num...
def binary_search(elem,val,low,high,mid): while(low <=high): mid = low + high // 2 if mid == val: return val elif mid < val : low = mid + 1 else: high = mid -1 return -1 if __name__=="__main__": elem = [22,1,45,78,25] low =0 mid =0 val =10 ...
""" 1304. Find N Unique Integers Sum up to Zero """ class Solution: def sumZero(self, n: int): if n==1: return [0] elif n%2==0: result=[] for i in range(1,n//2+1): result.append(i) result.append(-i) else: resul...
""" Design an OrderedStream """ class OrderedStream: def __init__(self, n: int): self.n=n def insert(self, idKey: int, value: str) -> List[str]: res=[] for i in range(self.value): if idkey==i: if len(res)>0: return ...
""" 9. Palindrome number """ def palindrome_check(n,x): if n==x: return True else: return False class Solution: def isPalindrome(self, x: int) -> bool: rev,pop=0,0 y=x if x < 0: return False while x > 0: pop =...
""" 1403. Minimum Subsequence in Non-Increasing Order """ class Solution: def minSubsequence(self, nums): temp=[] nums.sort(reverse=True) for i in range(len(nums)): if sum(nums[:i+1]) > sum(nums[i+1:]): temp.append(nums[:i+1]) return temp[0] s=Solution() ...
""" 10. Regular Expression Matching """ def all_check(s): for i in s: if i == '*': class Solution: def isMatch(self, s: str, p: str) -> bool: if len(s) < 0 or len(s) > 20: return 'false' if len(p) < 0 or len(p) > 30: return 'false' if s.isup...
#program to rotate array by n index print("Enter the index rotation value") n = 2 array_no = [1,2,3,4,5] ar_len = len(array_no) print(ar_len) last = array_no[-1] for i in range(ar_len-1): array_no[i+1] = array_no[i] array_no[0] = last print(array_no)
""" There are n flights, and they are labeled from 1 to n. We have a list of flight bookings.The i-th booking bookings[i] = [i, j, k] means that we booked k seats from flights labeled i to j inclusive. Return an array answer of length n, representing the number of seats booked on each flight in order of their label. ""...
""" divisor Game """ class Solution: def divisorGame(self, N: int) -> bool: return N%2==0 s=Solution() print(s.divisorGame(3))
""" Three Sum Problem """ class Solution: def threeSum(self, nums): nums.sort() res=set() for i in range(len(nums)-2): x=i+1 y=len(nums)-1 while x<y: if nums[x]+nums[y]+nums[i]==0: res.add((nums[x],nums[y...
""" 1299. Replace Elements with Greatest Element on Right Side """ class Solution: def replaceElements(self, arr): res=[] for i in range(1,len(arr)): sort_ele=max(arr[i:]) res.append(sort_ele) print(sort_ele) res.append(-1) return res...
class Node: def __init__(self,data): self.data =data self.next = None class Queue: def __init__(self): self.head = None def push_ele(self,data): newnode = Node(data) if self.head = None: self.head = newnode else: newnode.next = self.head self.hea...
""" Trie Data Structure """ class TrieNode: def __init__(self): self.children=None self.iswordend=False class Trie: def __init__(self): """ Initialize your data structure here. """ self.root=TrieNode() def insert(self, word: str) -> None: """ ...
""" 1078. Occurrences After Bigram """ class Solution: def findOcurrences(self, text: str, first: str, second: str): text=text.split(" ") res=[] for i in range(len(text)-2): if first==text[i] and second==text[i+1]: res.append(text[i+2]) return res s=So...
""" Heap and operation """ import heapq arr=[1,1,1,2,2,3,-2,-3] k=3 heapq.heapify(arr) print(heapq.nlargest(k,arr)) print(heapq.nsmallest(k,arr))
#Create an Array of Five Students #Name, Age, GPA - Unique GPAs ''' testArray = [["Adam", 25, 3.0], ["Carl", 24, 4.0], ["Bart", 23, 3.5], ["Deng", 22, 2.5], ["Eden", 21, 2.0]] ''' #Name, Age, GPA - GPA gets repeated. Sorting on Name ''' testArray = [["Adam", 25, 3.0], ["Bart", 24, 4.0], [...
#Student Class class Student(object): #Defining the Init Method def __init__(self, name, gpa, age): self.name = name self.gpa = gpa self.age = age #__str__() def __str__(self): print "_str__ Invoked" return "Data is: {" + str(self.name) + "," + str(self.gpa) + "," + str(self.age) + "}" #__lt__ def __...
from lib.tree import BinaryTree def height(node): height = 0 while node.parent is not None: node = node.parent return height def lowest_common_ancestor(node1, node2): h1, h2 = height(node1), height(node2) if h1 > h2: h1, h2 = h2, h1 node1, node2 = node2, node1 for _ in range(h2 - ...
# -*- coding: utf-8 -*- """ Created on Mon Nov 25 13:54:13 2019 @author: AbeerJaafreh """ print('Q1------------------------------------------------') class Employee(): def __init__(self, EmpNumber, Name,Address,Salary,jobTitle): self.empNumber=EmpNumber self.__name=Name sel...
# The deal_cards function deals a specified numberr of cards from the deck def deal_cards(deck, number): # Initialize an accumulator for the hand value. hand_value = 0 # Make sure the number of cards to deal is not geater tham the number of cards in the deck. if number > len(deck): num...
""" ###function_demo #This program demonstates a function. #First, we define a function named message. def message(): print('I am Arthur.') print('King of the Britons.') #call the message function. message() """ """ ##two_functions #This program has two functions. First we define the main functi...
"""A função soma_lista(lista) recebe como parâmetro uma lista de números inteiros e devolve, usando recursão, um número inteiro correspondente à soma dos elementos desta lista.""" def soma_lista(lista): if len(lista) == 1: return lista[0] else: return lista[0] + soma_lista(lista[1:]) ...
# The data we need to retrieve. # 1. The total number of votes cast # 2. A complete list of candidates who received votes # 3. The percentage of votes each candidate won # 4. The total number of votes each candidate won # 5. The winner of the election based on the popular vote # Import the datetime dependency. # impor...
### one code one day ### 两个排序数组 找第 K大的数字 ### 二分 def K_of_two_sorted_arr(arr1, arr2, K): start, end = 0, len(arr1)-1 while(start <= end): mid = (start + end) // 2 if(mid >= K): end = mid - 1 elif(mid == K - 1): if(arr1[mid] <= arr2[0]): return arr...
### one code one day ### 2020/04/10 ### leetcode 109 有序链表转换二叉搜索树 # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # s...
### one code one day ### 2020/05/08 ### leetcode 6 Z字形变换 def convert(self, s: str, numRows: int) -> str: def helper(word, row, flag): if(word != ''): arr[row].append(word[0]) if(flag): row += 1 if(row == numRows-1): flag = False ...
### one code one day ### 2020/05/02 ### leetcode 695 岛屿的最大面积 ### 栈实现深度优先搜索 def maxAreaOfIsland(self, grid: List[List[int]]) -> int: stack = [] res = 0 rows = len(grid) if(rows == 0): return 0 columns = len(grid[0]) walked = [[False] * columns for _ in range(rows)] for i in range(ro...
### one code one day ### 2020/03/03 ### leetcode 61 旋转列表 def rotateRight(self, head: ListNode, k: int) -> ListNode: ### 判断head是否为空和是否不用旋转 if(not head or k == 0): return head ### 变为循环链表,并求出链表长度 length = 1 p = head while(p.next != None): length += 1 p = p.next p.next = ...
arr = [3,1,1,2,5,4,2,10,41,12,51,5,4,1] def merge(left, mid, right): temp = [] l = left r = mid + 1 while(l <= mid and r <= right): if(arr[l] <= arr[r]): temp.append(arr[l]) l += 1 else: temp.append(arr[r]) r += 1 if(l == mid+1): ...
#!/usr/bin/env python # coding: utf-8 # In[1]: def add(n1,n2): print(n1+n2) # In[2]: add(10,20) # In[3]: number1 = 10 # In[4]: number2 = input("Please provide a number: ") # In[17]: add(number1,number2) print("Something happened!") # In[24]: try: # WANT TO ATTEMPT THIS CODE # MAY HAV...
#!/usr/bin/env python # coding: utf-8 # In[28]: class Animal(): def __init__(self): print("ANIMAL CREATED") def who_am_i(self): print("I am an animal") def eat(self): print("I am eating") # In[35]: class Dog(Animal): def __init__(self): ...
import numpy as np from .imputation import imputer class emulator: """Class to make predictions from the trained DGP model. Args: all_layer (list): a list that contains the trained DGP model produced by the method 'estimate' of the 'dgp' class. """ def __init__(self, all_layer): ...
import unittest from credential import Credential class TestCredential(unittest.TestCase): ''' Test class that defines test cases credential class behaiour Args: unittest,Testcase:Testcase that enable in creating testcases''' def setUp(self): self.new_application = Credential("github","Maureen1998","33...
import pyperclip import shelve import os import dev_deckmaker ''' TODO: Change the format so that python exports the pokemon cards as a list or a data structure then zip that data for saving, and unpack it for use. This way you can continue where you left off, and also to allow for sorting to happen. Also l...
from pointsandrotations import * from sidesandprinting import * from scramblecube import * from solvingstatecheck import * """Temporary user interface. To be replaced with a graphical version.""" print('Give the colors of the stickers in your cube as follows:') print('') print('Each side is represented as a 9 charact...
import sub.mailing as mailing def send(email): ID = input("ID>>") r = mailing.mail(email, 1, 0, ID) while (r == -1): print("輸入錯誤") ID = input("ID>>") r = mailing.mail(email, 1, 0, ID) return 0 email = input() send(email)
''' Input: a List of integers as well as an integer `k` representing the size of the sliding window Returns: a List of integers ''' # Create an array max_upto and a stack to store indices. Push 0 in the stack. # Run a loop from index 1 to index n-1. # Pop all the indices from the stack, which elements (array[s.top()]) ...
# Description: The file names.txt contains a list of names, one per line. Write a program that reads in this list and prints the longest name. # Source: http://zarkonnen.com/python_exercises with open('names.txt', 'r') as f: longest_name = "" while True: name = f.readline() if name == "": break if len(name)...
import collections test = input("") d = True freq = collections.Counter(test) l = len(test) if "@" in test and '.' in test: diff = test.index('.') - test.index("@") for x,y in freq.items(): if(x== '@' and y!=1): print("NO") break elif(x == '.' and y!=1): print...
import sys from typing import List from shared import get_exact_rows if __name__ == '__main__': grid = list(get_exact_rows(sys.argv[1], strip=False)) current_position = [0, grid[0].index('|')] direction = 1, 0 letters_encountered = [] # type: List[str] current_character = None steps = 0 ...
#!/usr/bin/env python3 # !-*-coding:utf-8 -*- # !@File : $[name].py #该文件中是二分法的例子 #涉及到的题目,均来自于leetcode #在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素, #而不是第 k 个不同的元素。 #题目链接:https://leetcode-cn.com/problems/kth-largest-element-in-an-array/ import random from typing import List def findKthLargest(nums: List[int], k...
from abc import ABC, abstractmethod class AbstractData(ABC): def __init__(self): super().__init__() @abstractmethod def get_type(self): pass @abstractmethod def generate_data(self): pass class String(AbstractData): def __init__(self, string=""): super().__in...
plate = int(input()) detergent = int(input()) * 2 limit = plate if plate < detergent else detergent i = 0 while i < limit: plate -= 1 detergent -= 1 i += 1 if(plate > detergent): print('Моющее средство закончилось. Осталось', plate, 'тарелок') elif(detergent > plate): print('Все тарелки вымыты. Осталось'...
# Problème : Réaliser une table de multiplication de taile 10x10 en utilisant la liste fournie. # Résultat attendu : un affichage comme ceci : 1 2 3 4 5 6 7 8 9 10 # 1 1 2 3 4 5 6 7 8 9 10 # 2 2 4 6 8 10 12...
row=int(input("enter the num of row")) col=int(input("enter the num of column")) sum_mat=[[0,0,0],[0,0,0],[0,0,0]] matrix1=[] print('enter the value in matrix1') for i in range(row): a=[] for j in range(col): a.append(int(input())) matrix1.append(a) matrix2 = [] print('enter the value in matrix2') f...
def myfun(str_1,str_2): str_1=str_1.replace(' ','') str_2=str_2.replace(" ",'') if len(str_1)!=len(str_2): return False for char in str_1: if char in str_2: str_2=str_2.replace(char,'') return len(str_2)==0 str_1=input('enter the string first') str_2=input('enter the str...
# Author : Jayavardhan Bairabathina # 2. PROBLEM DEFINITION # ---------------------------------------------- # Sentence:You really cannot repeat three times the word 'because' because 'because' is a conjunction that should not be used in such a way. # Question: Write a program logic to reverse the word "because" an...
from lib.enums import enum import properties class Task: """Represents a single task""" def __init__(self, title, notes = None, parent = None): if title is None: raise ValueError("Task cannot be created without a Title") self.title = title self.children = [] self.notes = notes self.complete = False ...
def loading(file_name): print("Loaded weather data from",file_name[0].upper()+file_name[1:-4],"\n") def daily(file_name): date = input("Give a date (dd.mm): ") #06.10 search="2019-"+date[3:]+"-"+date[0:2] with open(file_name, "r") as weather_file: weather_file.readline() for line in wea...
from tkinter import * window = Tk() # Get buy/sell data here buy = True if buy: txt = "Buy" color = "green" else: txt = "Sell" color = "red" label = Label(window, text=txt, bg=color, font=("Arial", 50), padx=20, pady=20) label.pack() window.mainloop()
""" Create a fibinacci sequnce, which takes nth starting number,nth ending number and nth number of times repeated. """ def Fibonacci(start,end,step): print(start, end,end=" ") for i in range(step-2): sums = start + end print(sums,end=" ") end = start start = sums def get_numb...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- height=1.75 weitht=80.5 bmi=weitht/(height*height) print('小明的BMI指数为:%.2f' % bmi) if bmi <18.5: print('过轻') elif bmi>=18.5 and bmi <25: print('正常') elif bmi>=25 and bmi <32: print('过重') else: print('严重肥胖')
#!/usr/bin/env python #Write a Python program to test whether all numbers of a list is greater than a certain number. num = [1, 4, 5] #list of numbers print str("This many items:"),(len(num)) print "Roll Call!" if 4 in num: print str("yes 4 is here") print "Height Check!!" print str("Anyone taller t...
#!/usr/bin/env python # user's first and last name and #print them in reverse order with a space between them first = input() second = input() print (second,str(","), first)
#!/usr/bin/env python # 66. Calculate body mass index #BMI = kg/m2 #Added print options to practice classifications again w = (float(input("Input Weight in kg: "))) #weight h = (float(input("Input Height in meters: "))) #height n = round(w / (h * h), 2) print "underweight: ", n <= 18.5 print "normal weig...
#Python problem 4 #This is a solution to the python poblem 4 where the prgram displays the factorial for the number 10 and adds all the numbers in the answer. #Created by Robert Kiliszewski #01/10/2017 #Import the maths library into the program import math print() #10 Factorial print ("10! = ",math.factorial(10)) pr...
import numpy as np def djisktra_slow(): #Initialize largest value of shortest distance to large number maxDist = 1000000 #Load graph from file and populate Path weight matrix #Note that if weight for a path is equal to maxDist it means given path is not connected f = open("djikstra.txt","r") lines = [line.rstrip...
b = 8 B = "Earth" #B will not overwrite b because variables in python are case sensitive print(B) print(b)
# 대입 연산자란 변수에 값을 연산자대로 처리한 다음 반영하는 # 연산자를 의미 # = 은 특정 변수에 값을 대입할 때 사용하며 # += 은 더한 결과 저장, -= 은 뺀 결과 저장, *= 은 곱한결과 저장 # /= 은 나눈 결과 저장, %= 은 출력된 나머지값을 저장 a = 5 a +=1 # a = a + 1 print(a) a -= 3 print(a) a *= 4 print(a) a /= 3 print(a) a %= 5 print(a)
import pickle def save(): f = open('savefile.dat', 'wb') pickle.dump(myPlayer, f, protocol = 2) f.close def load(): global myPlayer f = open('savefile.dat', 'rb') myPlayer = pickle.load(f) f.close def saveprompt(): print("do you wish to save?\n") s = input("> ") while s.lower() not in ("yes", '...
# User enters as many races as he/she wants # Program returns the media of the times and the number of races races = 0 timings = [] media = 0 print("Please enter your race timings (minutes) separated by spaces and then press enter.") timings = input() for time in timings: if time == ' ': pass else:...
MENU = { 'sandwich': 0.99, 'coffee': 0.87, 'salad': 3.05 } def user_imput(): print("-- Welcome to the restaurant --") total = 0 option = None found = False while option != '': found = False option = input("Please enter your desired meal: ") if o...
# Script gets a string as input and prints the word with more repeated letters def letters(sentence): print(f'Your sentence is: {sentence}') letter_list = [] for letter in sentence: print(word) letter_list_aux = [] letters(input())
def add(a, b): return a+b def min(a,b): return a-b sum = add(5, 6) min = min(5, 6) print(sum, min)
""" Week 2, Day 3: Flood Fill An image is represented by a 2-D array of integers, each integer representing the pixel value of the image (from 0 to 65535). Given a coordinate (sr, sc) representing the starting pixel (row and column) of the flood fill, and a pixel value newColor, "flood fill" the image. To perform a ...
""" Week 2, Day 4: Single Element in a Sorted Array You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. Find this single element that appears only once. Example 1: Input: [1,1,2,3,3,4,4,8,8] Output: 2 Example...
""" LeetCode 30-Day Challenge, May 2020, Week 1, Day 4 Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation. Example 1: Input: 5 Output: 2 Explanation: The binary representation of 5 is 101 (no leading zero bits), and i...
""" A node type for singly linked lists. """ class ListNode: def __init__(self, val=0, next_=None): self.val = val self.next = next_ def __str__(self): s = [f'{self.val} -> '] walker = self.next while walker is not None: s.append(f'{walker.val} -> ') ...
#Will continue tomorrow at '8.4 Skriv transaktioner till filen' # Planning : # Imports from functions import * # Functions check_file_exists() read_file() # Variabler # Main loop # Input of text # Write it in a file # Read the file # Complete the program while True: meny = ("\n#######################" ...
"""Argument parser""" """Command : status, start [prog_name], stop [prog_name], restart [prog_name], reload, shutdown""" class CmdParser(): """ A class which parse arguments of our program. """ def __init__(self): """ Initialize attibute for the Parser """ self.command = [] self.multi...
#warning print "*** POUR LE BON FONCTIONNEMENT DU JEU, VERIFIEZ QUE " print " VOTRE TOUCHE VER.MAJ EST DESACTIVE ***" print "-----------------------------------" import sys def clear(): sys.stdout.write('\033[2J') sys.stdout.write('\033[H') sys.stdout.flush() raw_input("Appuyez sur [ENTRER] pour demmarer") c...
import queue class merged_sort: def __init__(self, x1, x2): self.x1 = x1 self.x2 = x2 def __lt__(self, other): return self.x1 < other.x1 n = int(input()) left = [] l = int(input()) for _ in range(l): x,y = map(float, input().split()[:2]) left.append((x,y)) r = int(input()) right = [] for _ in range(r...
import random class Chromosome: """ Class, representing a chromosome. Each chromosome is 10 bits long: 1 bit for sign, 2 bits for integer part and 7 bits for fractional part. Since numbers not larger than 127 can be encoded with 7 bits and in my chromosome representation the fractional part i...
import random class Point: """ Sert à définir un point pour et sans le training coord,label """ #Constructeur def __init__(self,canvas_width,canvas_height): #Assigne des coordonnées random selon la width et l'height données self.coord = (random.uniform(0,canvas_width),r...
def romanToInt(s: str) -> int: r_dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} i = 0 res = 0 while i < len(s): #getting the number equivalent to the roman number num1 = r_dict.get(s[i]) if (i+1 < len...
''' Neighbourhood Data Object Purpose: - Creates a 3 x 3 cell instance from the terrain Filename: - neighbourhood.py Input: - Terrain surface Raster data (excluding headers) - Terrain resolution / cell size - Terrain processing cell row number - Terrain processing cell column number ...
from tkinter import * root = Tk() #create an object that is a blank window topFrame = Frame(root) #make invisible container and put it in the main window (root) topFrame.pack() #place somewhere in main window bottomFrame = Frame(root) bottomFrame.pack(side = BOTTOM) button1 = Button(topFrame, text="Button 1", fg="re...
from functools import reduce #1.map def function1(list): list = list[0].upper() + list[1:].lower() return list L1 = ['adam', 'LISA', 'barT'] L2 = list(map(function1, L1)) print(L2) #2.prod def prod(list): return reduce(lambda x, y: x*y,list) L3 = [1,2,3,4] print(prod(L3))
from src.state import State, Turn import chess def init_board(): """ Initialize checkers board (8x8) """ board = ['w', '-', 'w', '-', 'w', '-', 'w', '-', '-', 'w', '-', 'w', '-', 'w', '-', 'w', 'w', '-', 'w', '-', 'w', '-', 'w', '-', '-', '-', '-', '-', '-', '-'...
import sys class GarageHeap: ''' Garage Heap that orders jobs by a given comparison function. ''' __slots__ = 'data', 'size', 'above_fn' def __init__(self, above_fn): ''' Constructor takes a comparison function. :param above_fn: Function that takes in two heap ob...
import openning as open import guess import guess2 import time open.show_robot()#显示机器人 print('接下来我会对你稍微有个了解') time.sleep(2)#程序暂停5秒 name=open.ask()#询问年龄 print('-------------------------') print('''您可以输入: 几点了?------用来查询当前时间 你好----------可以向你问好 天气----------查询当前天气 猜数字--------进入小游戏猜数字 高级猜数字-----进入小游戏高级猜数字 关于作者-------可了解Ba...
# Released to students: validator for README import sys def main(argv): if len(argv) == 1: print(processReadMe(argv[1])) elif len(argv) == 0: print(processReadMe()) else: print("Usage Error: python readme_validator.py [*optional* path_to_readme]") def processReadMe(path="README"):...
s=raw_input('enter a string') s1="" x=len(s) for i in s: s1+=s[x-1] x-=1 print s1
n=input('enter no of even numbers') count=0 for i in range(0,n,2): print i count=count+1 print count
x = 123456 epsilon = 0.01 step = epsilon**2 numGuesses = 0 ans = 0.0 while abs(ans**2 - x) >= epsilon and ans*ans <= x: ans += step numGuesses += 1 print 'numGuesses =', numGuesses if abs(ans**2 - x) >= epsilon: print 'Failed on square root of', x else: print ans, 'is close to square root of', x
#write a program which uses previousely defined funciton in # problem 2 & 3 to print the reverse of a string and number after a swapping import swapping from stringReversal import reversestring swapping.swappingNumbers(124,36) print reversestring("best government")
i=raw_input('enter a number ') print type(i) print 5*int(i) print str(5)+ '*' + str(i) + '=' + str(5*i)
n=input('enter a number to print backwards ') for i in range(1,n): if n%i!=0: print i else:
n=input('enter a number') x=input('enter a number') y=input('enter a number') def fun(n): if (n%2==0): print n,'is even' elif(n%2!=0): print n,'is odd' fun(n) def swap(x,y): print x,y temp=0 temp=x x=y y=temp return x,y #swap(x,y) print swap(x,y)
y=float(raw_input('enter a number')) epsilon =0.01 guess=y/2.0 while abs(guess*guess-y)>=epsilon: guess=guess-(((guess**2)-y)/(2*guess)) print (guess) print 'Square root of',y,'is about ',guess
n=input('enter a number') def fun(n): if (n%2==0): print n,'is even' elif(n%2!=0): print n,'is odd' fun(n)
# @Author: Antero Maripuu Github:<machinelearningxl> # @Date : 2019-07-15 17:55 # @Email: antero.maripuu@gmail.com # @Project: Coursera # @Filename : Homework_1.py import numpy as np import pandas as pd df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}) print(df) print() print(df.rename(index=str, columns={"A": "a...
#Write your code below this row 👇 sum = 0 for n in range (2,101,2): sum += n print (sum) sum2 = 0 for n in range (1,101): if n % 2 == 0: sum2 += n print (sum2)
import math def is_prime(n): """ from an answer # https://stackoverflow.com/questions/18833759/python-prime-number-checker # bruteforce check """ if n <= 2: return True if n % 2 == 0: return False return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2)) # from an ...