text stringlengths 37 1.41M |
|---|
def scoresgrades():
print "Scores and Grades"
for i in range(0,10):
score = input("What is your test score?")
if 100 >= score >=90:
print "Score: {}; Your grade is A".format(score)
elif 89 >= score >=80:
print "Score: {}; Your grade is B".format(score)... |
import threading
import time
class MyThread(threading.Thread):
"""
This class will manage a thread.
"""
def __init__(self, thread_no):
"""
Constructor. Get stuff set up, set variables.
"""
super().__init__()
# thread_no is just a label so we can see what thread i... |
import socket
# This is your buffer. You can't receive anything more than this at
# one time.
BUFFER_SIZE = 65535
my_ip_address = '127.0.0.1'
my_ip_port = 5005
# Create a socket for sending/receiving data
my_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Tell the socket it will be listening on my_ip_a... |
import random
import time
def bubble_sort(nums):
""" Bubble sort implementation. """
compare_len = len(nums)
while compare_len > 1:
for i in range(compare_len - 1):
if nums[i] > nums[i + 1]:
nums[i], nums[i+1] = nums[i+1], nums[i]
compare_len -= 1
return nu... |
import survey
import random
"""
Exercise 7.1:
In the NSFG dataset, the difference in mean weight for first births is 2.0
ounces. Compute the p-value of this difference
"""
def weight_p_value():
p_value = 0
i = 0
while i < 100:
if i % 10 == 0: print i
if abs(get_diff_means()) > 2.... |
# base start of inseration is alwasy 2
def insertion_sort(list_a):
indexing_length = range(1, len(list_a))
for i in indexing_length:
value_to_sort = list_a[i]
print(f"v={value_to_sort} l={list_a[i-1]} l={list_a[i]}")
# In need > 0 as python allowed negative indexing
while list_a[... |
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common import keys
options = Options()
options.headless = True
driver = webdriver.Chrome(options=options, executable_path='./chromedriver')
driver.get("https://www.baltimoresun.com/search/mckenna%20oxenden/100-... |
# Python Review Misc Topics
def main():
#problem1()
#problem2()
problem3()
#Given a number n, return ```True``` if n is in the range 1..10, inclusive.
# Unless outside_mode is ```True```, in which case return True if the number is less or equal to 1, or greater or equal to 10.
# Print the result returned ... |
#import matplotlib.pyplot as plt
def deCasteljau(points, u, k = None, i = None, dim = None):
"""Return the evaluated point by a recursive deCasteljau call
Keyword arguments aren't intended to be used, and only aid
during recursion.
Args:
points -- list of list of floats, for the control point coor... |
class Console:
def __init__(self):
pass
def print_jumper(self, jumper):
if jumper.get_life() == 4:
print(' ___\n /___\\\n \\ /\n \\ /\n 0\n /|\\\n / \\\n\n^^^^^^^ ')
elif jumper.get_life() == 3:
print(' /___\\\n \\ /\n \\ /\n 0\n /|\\\n / \\\n\n^^^^... |
# 字符串的驻留机制:仅保留一份相同且不可变字符串的方法,不同的值被存放在字符串的驻留池中,Python的驻留机制对相同的字符串只保留一份拷贝
# 后续创建相同字符串时,不会开辟新空间,而是把该字符串的地址赋给新创建的变量
s1 = 'Python'
s2 = "Python"
s3 = """Python"""
print(s1 is s2, id(s1), id(s2))
print(s2 is s3, id(s2), id(s3))
# 实际上s1和s2和s3指向同一份内存地址,这个内存地址保存的就是Python这个字符串,这就是字符串的驻留机制
# 驻留机制的几种情况(交互模式)
'''
1. 字符串的长度为0或者1
2. ... |
girl_age = 25
count = 0
while count < 3:
age = int(input("猜姑娘的年龄>:"))
if age > girl_age:
print("猜大了,往小了试试...")
elif age < girl_age:
print("猜小了,往大了试试...")
else:
print("猜对了....")
break
count += 1
if count == 3:
cmd = input("你这么笨,是否需要再试一把?(y/n)").strip()
... |
# 列表的操作
# 声明一个列表变量
names = ["Monkey", "BlackGirl", "XiaoBin"]
# 往列表中添加一个元素
names.append("this is append element")
names.insert(2, "this is insert element")
print(names)
# 修改列表中某个位置的元素
names[3] = '哈哈哈哈'
# 获取指定元素在列表中的位置
print("哈哈哈哈在names中的索引为:", names.index("哈哈哈哈"))
# 删除列表中的元素
del names[3]
names.remove("this is ins... |
# 字典数据结构对应的就是Java中的Map 字典是可变的,key不可重复value可重复,无序的序列
dist_obj = {"key": "value"}
print(dist_obj)
# 字典的创建方式
'''使用{}进行创建'''
sources = {"name": "张三", "age": 28}
print(sources)
'''使用dist()创建'''
sources = dict(name='张三', age=28)
print(sources)
print("获取字典中的元素".center(60, "-"))
'''方式一:使用[]进行获取,[]内填写key'''
print(sources['... |
import math
def make_link(G, node1, node2):
if node1 not in G:
G[node1] = {}
(G[node1])[node2] = 1
if node2 not in G:
G[node2] = {}
(G[node2][node1]) = 1
return G
# make an empty graph
G = {}
n = 256
side = int(math.sqrt(n))
# add in the edges
for i in range(side):
for j in range(side):
if i < side-1:
... |
# measuring time as a function of an input
import math
def time(n):
return 3 + 2 * math.ceil(n/5.0)
print time(50)
def countdown(x):
y = 0
while x > 0:
x = x - 5
y = y + 1
print y
print countdown(50) |
# zip функция объединяет отдельные элементы из каждой последовательности в кортежи.
# т.е. она возвращает итерируемую последовательность, состоящую из кортежей.
# 'zip(последовательность, последовательность...'
x = 'qwe'
y = 'asd'
zipped = zip(x, y)
print(zipped)
print(list(zipped))
# [('q', 'a'), ('w', 's'), ('e', 'd... |
# Define Function
def greet():
name = input("Enter your name: ")
print(f"Hello, {name}!")
greet()
# Arguments and Parameters
car = {
"make": "Ford",
"model": "Fiesta",
"mileage": 23000,
"fuel_consumed": 460
}
def calculate_mpg(car):
mpg = car["mileage"] / car["fuel_consumed"]
name = ... |
# Iterate pre-defined number of times
elements = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for index in elements:
print("Hello World")
for _ in elements:
print("Hello World")
# Use range(end)
for index in range(10):
print(index)
for _ in range(10):
print("Hello World")
# Use range(start, end)
for index in r... |
# Add Repeating Numbers
repate_numbers = [5 for number in range(5)]
print(repate_numbers)
# Double Numbers
numbers = [0, 1, 2, 3, 4, 5]
double_numbers = [number * 2 for number in numbers]
print(double_numbers)
# Custom String List
ages = [23, 34, 45, 56, 67]
ages_string = [f"My friend is {age} years old." for age... |
# Define
friends = {"Dhanushka", "Gayashan"}
print(friends)
# Empty Set
friends = set()
print(friends)
# Append - Do not add Dupliates
art_friends = {"Dhanushka", "Gayashan"}
art_friends.add("Chamari")
print(art_friends)
art_friends.add("Chamari")
print(art_friends)
# Compare Sets
art_friends = {"Dhanushka", "... |
dogs = ['Fido', 'Sean', 'Sally', 'Mark']
for dog in dogs:
print(f'{dog}')
for index in range(0, 4):
print(dogs[index])
age = 0
while age < 18:
print(f'New age {age}')
age += 1
|
import time
def is_prime(n):
if n != int(n) or n <2:
return True
if n ==2:
return True
if n%2 ==0:
return False
for i in range(3,int(n**0.5) +1,2):
if n % i ==0:
return False
return True
'''
a,b=eval(input('a,b='))
s =0
pMax=0
t0 = time.time()
for i in range (a,... |
import time
def is_prime(n):
if n != int(n) or n <2:
return True
if n ==2:
return True
if n%2 ==0:
return False
for i in range(3,int(n**0.5) +1,2):
if n % i ==0:
return False
return True
n=eval(input('n='))
s =1
t0 = time.time_ns()
for i in range (3,n+1,2):... |
import fileinput
from collections import Counter
data = list(map(int, fileinput.input()))
def built_in(data):
return max(data) + 3
data = [0] + sorted(data) + [built_in(data)]
deltas = [b - a for (a, b) in zip(data, data[1:])]
ctr = Counter(deltas)
print(ctr)
print(ctr[1] * ctr[3])
|
''' find a pair of numbers that the sum is equal for asked in an sorted array
'''
def find_two_sum(data, sum):
begin_pos = 0
end_pos = len(data) - 1
while begin_pos < end_pos:
if (data[begin_pos] + data[end_pos]) > sum:
end_pos -= 1
elif (data[begin_pos] + data[end_pos]) < sum:
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import time, threading
import os
import time, threading
# 假定这是你的银行存款:
balance = 0
def change_it(n):
# 先存后取,结果应该为0:
global balance
balance = balance + n
balance = balance - n
def run_thread(n):
for i in range(100000):
change_it(n)
t1 = threa... |
import numpy as np
from field.convert_field import Field
class Data:
"""
Data class:
Receives text file with field information.
Imports Numerical Python library & Field Class to process the given information.
Only knows of the file name given to it. Reads it and converts... |
# Georgi Nikolov
# Module Imports:
import sys
# Program Methods:
def create_mapping(keys, values):
'''
:param keys: list, the purpose of which is to be the keys of the resulting structure
:param values: list, the purpose of which is to be the values of the keys for the resulting structure
:return: ret... |
def helper(n):
if n == 1:
return "1"
else:
prev = helper(n - 1)
count = 1
nextnumstring = ""
for index in range(1, len(prev)):
if prev[index - 1] == prev[index]:
count = count + 1
else:
nextnumstring = n... |
tree_height = input("Velikost smrekce : ")
tree_height = int(tree_height)
spaces = tree_height-1
stars = 1
stump_spaces = tree_height-1
while tree_height != 0 :
for i in range(stars):
print('*', end="")
print()
tree_height -= 1
stars += 1
|
class Node:
def __init__(self,data,prio):
self.data = data
self.prio = prio
self.sig = None
def imprimirNodo(self):
print(self.data)
class Cola:
def __init__(self):
self.head = None
self.tam = 0
def insert(self,data, prio):
if self.head == None:
self.head = Node(data,prio... |
def maxCourses(n,p):
result = max(n)
# l = []
# for i in range(1,p+1):
# l.append(i)
# for i in range(1,p+1):
# for j in range(1,n[i-1]+1):
# if j in l:
# l.remove(j)
return p-result
n = input()
for i in range(0,n):
p = input()
l = []
array = ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy
from mlpy import *
# XOR Port example.
input_data = numpy.array([
[0,0],
[0,1],
[1,0],
[1,1],
])
desired_output = numpy.array([
[-1],
[1],
[1],
[-1],
])
# Run the training algorithm.
(hidden_weights, output_weights) = trainni... |
from tkinter import *
import func
# ==================== windows =======================
window = Tk()
window.title("book store")
window.geometry("490x280")
window.resizable(width=False,height=False)
color='#e0e0e0'
window.config(bg=color)
# ==================== static function =======================
def clear_li... |
from abc import ABC, abstractmethod
from const import *
from errors import *
import operator
class Player(ABC):
cards = []
bonuses = [0] * TOKENS.NUMBER
tokens = [0] * TOKENS.NUMBER
visitors = []
points = 0
MOVE_PICK_TOKENS = 1
MOVE_BUY_CARD = 2
MOVE_BOOK_CARD = 3
MOVE_BUY_RESERV... |
from enum import Enum
from geometry import Position
class CellType(Enum):
"""We don't yet know what's in the cell."""
UNKNOWN = 0
"""There's open space in the cell."""
OPEN = 1
"""There's walls around the cell."""
WALL = 2
LOCATION = 3
class GridMap:
"""A map representation with, ... |
from datetime import datetime, timedelta
def clamp(num: int, min_value: int, max_value: int):
return max(min(num, max_value), min_value)
def is_in_range(num, min, max):
return min <= num <= max
class Timer:
def __init__(self, countdown_time):
self.countdown_time = timedelta(seconds=countdown_t... |
#######################################################
# Author: <Dhruv Aggarwal >
# email: <aggarw45@purdue.edu>
# ID: <ee364d01 >
# Date: <2/20/19>
#######################################################
import os # List of module import statements
import os.path
# Mo... |
#######################################################
# Author: <Dhruv Aggarwal >
#######################################################
import os # List of module import statements
import sys # Each one on a line
# Module level Variables. (Write this statement verbatim .)
#################... |
import os
import urllib.request
from concurrent.futures import ThreadPoolExecutor
from concurrent.futures import as_completed
# Create directory to store downloaded data
os.makedirs("data", exist_ok=True)
# add URL array to download.
urls = ['102711', '106360', '106494']
def downloader(url):
try:
response = urlli... |
def valid_parentheses(parens):
"""Are the parentheses validly balanced?
>>> valid_parentheses("()")
True
>>> valid_parentheses("()()")
True
>>> valid_parentheses("(()())")
True
>>> valid_parentheses(")()")
False
>>> valid_parentheses("())"... |
class Lab:
labID = 0
name = ""
courseID = 0
classNumber = 0
time = ""
location = ""
labNumber=0
def getDataBaseID(self, value):
return self.labID
def __init__(self,ID,name,course,classnr,time,location,labnr):
labID=ID
name=name
courseID=course
... |
inversions = 0
def mergeSort(alist):
global inversions
if len(alist)>1:
mid = len(alist)//2
leftlist = alist[:mid]
rightlist = alist[mid:]
#runs recursively on both sides to break them up into single elements
mergeSort(leftlist)
mergeSort(rightlist)
... |
#
# datePlayground.py
# playing around with date stuff
#
import datetime
today = datetime.datetime.now()
def printDateInfo():
print(today.date())
print(today.isocalendar())
print(today.weekday())
printDateInfo()
today = today + datetime.timedelta(days=1)
print(today.date())
print(today.isocalendar()... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 4 01:29:18 2020
@author: chenguanlin
"""
def check():
if(pw.get()=="213"):
msg.set('correct')
else:
msg.set('error')
import tkinter as tk
win=tk.Tk()
pw=tk.StringVar()
msg=tk.StringVar()
label=tk.Label(... |
#!/usr/bin/env python3
import argparse
import random
import re
def roll(max_roll):
return random.randint(1, max_roll)
def full_throw(die_list):
total = []
for die in die_list:
(num_dice, max_roll) = die.split('d')
(num_dice, max_roll) = (int(num_dice), int(max_roll))
for y in ra... |
import json
dict_data = {}
dict_data_list = []
questions = ["type your name: ", "type your age: ", "type your school: ", "type your height: "]
# keys = ["name", "age", "school", "height"]
for k, v in questions.items():
resp = input(v)
dict_data[k] = resp
dict_data_list.append(dict_data)
#for i in rang... |
# Artificial Neural Network
# Dự đoán khách hàng mới có sử dụng tài khoản ngân hàng không?
# Importing the libraries
from sklearn.metrics import confusion_matrix, accuracy_score
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import OneHot... |
import unittest
class Roman(object):
def say(self, number):
result = ''
while (number > 0):
if (number >= 10):
result += 'X'
number -= 10
elif (number >= 9):
result += 'IX'
number -= 9
elif (number ... |
class Student:
def __init__(self, name, school):
self.name = name
self.school = school
self.grades = []
def average(self):
return sum(self.grades) / len(self.grades)
@classmethod #will be a class of whatever class is calling it, inheriting from student/workingstudent
de... |
n1=int(input("enter the number1 ")
n2=int(input("enter the number2 ")
print("number1 before swapping",n1)
print("number2 before swapping",n2)
temp=n1
n1=n2
n2=temp
print("number1 after swapping",n1)
print("number1 after swapping",n2)
|
def odd(x):
if x%2==0:
return 0
else:
return 1
def flip(x):
# print('x is',x)
if x:
return 0
else:
return 1
def encode(message,p1,p2):
# message=input()
# errorpos=list(map(int,input().strip().split()))
# message='aman'
message=list(map(int,list(messag... |
#!/usr/bin/env python
# BMI.py
# # -----------------------------------
# 15.04.2021 by OJ => Python 3
# -----------------------------------
def bmi(kg, m):
bmi = kg/(m*m)
return bmi
def bewertung(b):
if (b > 25):
print(" => Uebergewicht")
elif (b < 18.5):
print(" => U... |
#!/usr/bin/env python
# bmi2.py
# ---------------------------------------
# 22.4.2012 by OJ - bis Zeile 23 gelynted
# 15.04.2021 by OJ => Python 3
# ---------------------------------------
def bmi(kg, m):
bmi = kg/(m*m)
return bmi
def bewertung(b, a):
# Die Tabelle in einer konstanten List... |
class Image:
"""
This is the class that used to represent one Image for AggieStack
Attributes:
name (str): name of the image
capacity (int): capacity of the image
path (str): path of the image
"""
def __init__(self, name, capacity, path):
"""
con... |
welcome = str("Welcome to your magnificent holiday programme! \n")
print(welcome)
city = input("Which city are you flying to? (Los Angeles, New York, Las Vegas, San Francisco or San Diego California): \n") #user_input
def planeCosts(city): #defining a variable
... |
# codng:utf-8
import math
import matplotlib.pyplot as plt
import numpy as np
if __name__ == "__main__":
x = np.arange(0.05, 3, 0.05)
y1 = [math.log(a, 1.5) for a in x]
plt.plot(x, y1, linewidth = 2, color = '#007500', label = 'log1.5(x)')
y2 = [math.log(a, 2) for a in x]
plt.plot(x, y2, linewidth = 2, color = '#... |
#!/bin/python3
import sys
def caesarCipher(s, k):
# Complete this function
res = ''
for i in s:
if i.isalpha():
a = 'A' if i.isupper() else 'a'
res += chr(ord(a) + ( ord(i) - ord(a) + k) % 26)
else:
res += i
return res
if __name__ == "__main__":
... |
# Definition for a binary tree node.
# https://www.geeksforgeeks.org/sorted-array-to-balanced-bst/
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def printPreOrder(self, n):
if n is None:
return
print(n.... |
#!/usr/bin/python3
# mergesort using recursion
import time
def mergesort(array=[23, 6, 1, 90, 30, 39, 99, 15, 88, 0]):
print("Splitting", array)
if len(array) > 1:
mid = len(array) // 2
lefthalf = array[:mid]
righthalf = array[mid:]
mergesort(lefthalf)
mergesort(righth... |
#!/usr/bin/python3
# quicksort using recursion and python3 lists
import time
def quicksort1(array=[23, 6, 1, 90, 30, 39, 99, 15, 88, 0]):
less = []
equal = []
greater = []
if len(array) > 1:
pivot = array[0]
for x in array:
if x < pivot:
less.append(x)
... |
###从控制(台输入数据,然后数据从小到大输出
# m = []
# for i in range(5):
# x = int(input('please xie date:\n'))
# m.append(x)
# m.sort()
# print(m)
####用*号输入字母2的图案
# print ('@'*8 )
# for i in range(3):
# print (' *')
# print ('@' * 8)
# for j in range(3):
# print('*')
# print ('@'*8)
#####
# m=0
# for i in range(10... |
# =================
# jukebox9.py
# =================
# There is a bug in the code from jukebox8.py and we will fix it here
# THE BUG
# The bug itself is that if any Artist has an album with the same name as the other artist, it selects songs for the first artist's album
# For example, Artist "Billy Idol" has album ... |
n=int(input("Enter Number of Rows: "))
x=input("Enter the character which u wanna to print: ")
space=2*(n-1)
for i in range(0,n):
print(" "*space,end=" ")
for j in range(0,i):
print(x,end=" ")
print("")
space-=2
|
n=int(input("Enter the number whose table u wanna to print: "))
m=int(input("Enter how many times u wanna to print: "))
for x in range(1,m+1):
print(f"{n}x{x}={n*x}")
|
n=int(input("Till where u wanna to print table: "))
for i in range(1,11):
for j in range(1,n+1):
print(j*i,end=" ")
if j*i < 10:
print(" ",end="")
print("")
|
import intro #Use to style and to introduce about the developer of the program
print(" Press 1 to convert kelvin to Fahrenheit\nPress 2 to convert Fahrenheit to kelvin ")
x=int(input())
if x==1:
k=int(input("Enter value in kelvin"))
f=(k-273.15)*1.8 + 32
print("Temperature in Fahreinheit is ",f)
... |
#Frequency of digits in a number means how many times a digit comes in a given Number
num=int(input("Enter a Number: "))
lst=[]
temp=num
while temp != 0:
mod=temp%10
lst.append(mod)
temp=temp//10
for x in range(0,10):
print(f"Frequency of {x}: {lst.count(x)}")
|
import intro #Use to style and to introduce about the developer of the program
x = int(input("Enter value 1 "))
y = int(input("Enter value 2 "))
print("AAddition of two Number is ", x+y)
import end #Use to give style while ending the program
|
import intro #Use to style and to introduce about the developer of the program
x,y=[int(x) for x in input("Enter x and y respictively ").split(",")]
x=x+y
y=x-y
x=x-y
#or we can also do it by x,y=y,x
print("After Swapping \n x = ",x," and y = ",y)
import end #Use to give style while ending the program
|
### we can make set from a list
myList = [1,2,3,4,5]
mySet = set(myList)
print(mySet)
my_set = set([1,2,3,2])
print(my_set)
# we can make set from a tuple
myTpl = (1,2,3,4,5,5,5,5,5)
mySet = set(myTpl)
print(mySet)
|
for x in range(1,101):
if x%2 == 0 and x%3 == 0:
print(x,end=",")
|
import intro #Use to style and to introduce about the developer of the program
x=eval(input("Enter any data type")) #eval allows all numeric data tpe
print(type(x))
import end #Use to give style while ending the program
|
import intro #Use to style and to introduce about the developer of the program
# int(x) use to type casting other data type to integer
# float(x) use to type casting other data type to float
# str(x) use to type casting other data type to string
# long(x) use to type casting other data type to long
# tuple(x) ... |
import intro #Use to style and to introduce about the developer of the program
x=input("Enter a string ")
print("Reverse of the string is ",x[::-1])
#the slice statement [::-1] is the same as [11:0:-1] which
#means start at position 11 (because "Hello "World" has 11 characters),
#end at position 0, move with t... |
import intro #Use to style and to introduce about the developer of the program
x = float(input("Enter Values 1 - "))
y = float(input("Enter Values 2 - "))
print("\t \t \t Arithmetic Operation" )
print("Addition")
print("x + y = ",x+y)
print("Subtraction")
print("x - y = ",x-y)
print("Multiplication")
print... |
password="IRONMAN"
i=1
while i == 1:
p=input("Sir, Please Enter Ur Password: ")
if p == password:
print("Password match Welcome sir: ")
i=2
else:
print("Wrong Password, Try Again: ")
print("While Loop is cracked")
|
num = int(input("Enter the Number: "))
lst=[]
for x in range(1,num):
if num%x == 0:
lst.append(x)
sum=0
for x in lst:
sum+=x
if sum == num:
print(f"{num} is a Perfect Number: ")
else:
print(f"{num} is not a Perfect Number: ")
|
import intro #Use to style and to introduce about the developer of the program
x=int(input("Enter Number "))
print("Number in \n Binary = ", bin(x),"\n octal = ", oct(x),"\n Hexadecimal = ",hex(x))
import end #Use to give style while ending the program
|
#in loops if u get confused then take eg on paper and find output by own
#and Understand every logic
x= int(input("Enter Number: "))
count=0
while x>0:
x=x//10
count=count+1
print(f"Number of Digits is {count}")
|
start = int(input("Enter from where u wanna to start the interval: "))
end = int(input("Enter till where u want to end the interval: "))
lst=[]
for x in range(start,end+1):
var=2
for i in range(2,x):
if x%i == 0:
var=1
break
if var == 2:
lst.append(x)
print... |
def prime(n):
m=int(n/2)
val=0
for x in range(2,m+1):
if n%x == 0:
val=1
break
if val == 0:
return n
else:
pass
def fact(n):
m=int(n/2)
for x in range(1,m+1):
if n%x == 0:
if prime(x) == None:
... |
def prop(r):
print(f"Diameter ofthe Circle is: {2*r}")
print(f"Circumference of the Circle is: {2*r*3.14}")
print(f"Area off the Circle is: {3.14*r*r}")
radii=int(input("Enter Radius of the Circle: "))
prop(radii)
|
import intro #Use to style and to introduce about the developer of the program
#use of \r for carriage return (Leaving lines or space or block)
print(" Use of \\f is: \f \n Use of \\a is: \a \n Use of \\b is: \b \n Use of \\t is: Anurag \t Rai\n Use of \\n is : New Line \n Use of \\r is: Anurag \r Rai")
imp... |
#This is a module
def addition(x=0,y=0):
""" This is Known as Docstring of a Function
Here default parameter were used because if user didn't pass any parameter
by default it take it as 0"""
return x+y
def multiplication(x=1,y=1):
"""Here default parameter were used because if use... |
sum=0
for x in range(1,11):
sum+=x #sum=sum+x
print(sum)
|
#take input in binary form num=int(input(),2)
num=int(input("Enter Number in binary form: "),2)
print("Number in Octal: ",oct(num))
print("Number in Decimal: ",int(num))
print("Number in Hexadecimal: ",hex(num))
|
#using while loop
num=int(input("Enter the Number: "))
temp=num
fact=1
while temp != 1:
fact=fact*temp
temp-=1
print(f"Factorial of a Number is {fact}")
#using Math Module
print("Factorial Using Math Module")
from math import factorial
n=int(input("Enter the Number: "))
print(f"Factorial... |
num = int(input("Enter any Numbe5r: "))
if num % 5 == 0 and num % 11 == 0:
print("Number is Divisible by 5 and 11 both")
else:
print("Number is not Divisible")
|
import intro #Use to style and to introduce about the developer of the program
x,y=[int(x) for x in input("Enter Number 1 and Number 2 respictively and split them by space: ").split()]
if x>y:
print("Number 1 is Greater than Number 2:")
elif y>x:
print("Number 2 is Greater than Number 1:")
else:
... |
lst1 = [1,2,3]
lst2 = ["pasta","burger"]
print(lst1,lst2, sep =",")
lst3 = lst1 + lst2
print(lst3)
|
#here i make a dictionary to store word withtheir respective number
word={0:"Zero",
1:"One",
2:"Two",
3:"Three",
4:"Four",
5:"Five",
6:"Six",
7:"Seven",
8:"Eight",
9:"Nine"}
num=int(input("Enter a Number: "))
temp=num
lst=[]
while temp != 0:
mod=t... |
#Assignment Operator
a=5
print(a)
a+=5 #a=a+5
print(a)
a-=5 #a=a-5
print(a)
a*=5 #a=a*5
print(a)
a/=5 #a=a/5
print(a)
a//=5 #a=a//5
print(a)
a**=5 #a=a**5
print(a)
|
x=int(input("Enter Elctricity units: "))
if x>50:
amount=50*0.5
x=x-50
if x>100:
amount=amount+(100*0.75)
x=x-100
if x>100:
amount=amount+(100*1.20)
x=x-100
if x>0:
amount=amount+(x*1.5)
else:
amount... |
#lestsupgrade Day 2 Assignment - Program 2
n = 5
for i in range(1,n+1):
print(" "*(n-i),str(i)*i)
|
def binary_search(arr, start, end, key):
if(start > end):
return -1
mid = (start + end) / 2
mid = int(mid)
if arr[mid] == key:
return mid
elif arr[mid] < key:
return binary_search(arr, mid + 1, end, key)
else:
return binary_search(arr, start, mid - 1, key)
de... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 13 16:10:17 2018
@author: nasir
"""
from TreeBSTCommon import BST
def main():
#tree_data = [8,3,1,10,6,4,7,14,13]
#tree_data = [100,20,10,30,500,40, 200,300,600]
tree_data = [100,50,200,30,70,150,250,20,60,170,55]
my_bst = BST()
... |
nome = input("Digite uma palavra: ").lower()
print(nome)
for p in nome:
for letra in p:
if letra in 'aeiou':
print(" Essas são as vogais: ",letra)
# eu não consegui fazer com que tirassae as vogais |
class pessoa():
def __init__(self, nome, sobrenome, idade):
self.nome = nome
self.sobrenome = sobrenome
self.idade = idade
def dados(self):
print(f"O nome é : {self.nome} e o sobrenome é: {self.sobrenome} e a idade é: {self.idade}")
alguem = pessoa("Otavio","Matheus"... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.