text stringlengths 37 1.41M |
|---|
#Name: Mohan Subhash Paliwal..
#ID: AIS035
#Python Exercise No: 5
#Subject: Basic programs
#--------------------------------------------------
#Q1) Create a tuple to display the values of a tuple using for loop?
x=(10,25,55,48,66,85,44)
len(x)
for i in x:
print(i)
#------------------------------------... |
#Name: Mohan Subhash Paliwal..
#ID: AIS035
#Python Exercise No: 6
#Subject: Control Statements
#-----------------------------------------------------
#Q1)Which are the control statements in python?
'''
loop control statement : 1) break statement 2) continue statement 3) pass statement
'''
#----------------... |
import random
booleanData = "yes"
#Chooses a 4 digit random number
randoNumber =random.randint(1000, 9999)
print(randoNumber)
#Puts the random number into an array of integers
num = randoNumber
list2 = [int(x) for x in str(num)]
while booleanData.lower() == "yes":
userinput = input("Guess a Random Number between... |
# x = 'abcaafahbaabdfgz'
# S0ManyAlg0s_
def longest_substring_without_repoeating_chars(string):
max_length = 0
for i in range(len(string)):
max_length = max(max_length, helper(string, i))
return max_length
def helper(string, start_index):
seen = set()
for i in range(start, len(string))... |
"""
Первоначальная консольная программа
"""
from math import log
INCORRECT_DATA_MESSAGE = "Incorrect data!"
POACHERS_ARE_GUILTY = "Poachers are guilty!"
HUNTSMEN_ARE_KILLERS = "Huntsmen are killers!"
x1 = 31 # температура во время задержания
x2 = 29 # температура через час после задержания
x = 31 # температура... |
lista = []
for i in range(4):
print("Digitar el numero", str(i+1) + ": ", end="")
Digito = input()
lista += [Digito]
print("La lista creada es: ", lista)
print("Primer numero de la lista es: ", lista[0])
print("Ultimo numero de la lista es: ", lista[3])
print(" <(*) ")
|
class Persona(object):
def __init__(self, nombre, apellido='asdfasdf'):
self.nombre = nombre
self.apellido = apellido
def obtener_nombre(self):
print 'Dentro de clase base'
return '{nombre} {apellido}'.format(
nombre=self.nombre,
apellido=self.apellido
)
#def otro_metodo(cls):... |
import numpy as np
n = int(input('Ingrese el tamaño de la matriz cuadrada'))
# matriz =[]
# for i in range(n):
# a = [0]*(n)
# matriz.append(a)
# print(matriz)
#
import random
# for i in range(0,n):
# for j in range(0,n):
# matriz[i][j] = random.randint(1,9)
# print(matriz[i][j], end ='\t')... |
# -*- coding: utf-8 -*-
"""
Finding path for stormwater drain
"""
import math
class FindingPath:
def __init__(self, pointFile, segmentFile):
self.readPoints(pointFile)
self.readSegments(segmentFile)
self.createConnectionList()
def readPoints(self, fileName):
f = open(f... |
"""
Create a program that asks the user to enter their name and their age.
Print out a message addressed to them that tells them the year that they will turn 100 years old.
"""
def ask():
name = input('Please enter your name:')
age = input('Please enter your age:')
if int(age) < 1:
print('Invaild... |
"""
Generate a random number between 1 and 9 (including 1 and 9).
Ask the user to guess the number,
then tell them whether they guessed too low, too high, or exactly right.
Keep the game going until the user types “exit”
Keep track of how many guesses the user has taken, and when the game ends, print this out.
"""
impo... |
import datetime
import os
from weather.downloader import download_url
class WeatherApi(object):
"""WeatherUnderground Api wrapper"""
def __init__(self):
self.api_key = os.environ.get("WEATHER_API_KEY")
def search_date_range(self, start_date, end_date, zip_code):
"""Search weather condition... |
#Problem-069
T1 = ('Canada','USA','UK','Netherland','Norway')
print(T1)
countries = input('Enter one of the country from above list: ')
print(T1.index(countries))
################################################
#Problem-070
T1 = ('Canada','USA','UK','Netherland','Norway')
print(T1)
countries = input('Enter on... |
"""#Problem-012
x1=int(input('enter first number: '))
x2=int(input('enter second number: '))
if x1>x2:
print('x1 is greater than x2')
print(x2)
print(x1)
else:
print('x2 is greater than x1')
print(x1)
print(x2)
########################################
#problem013
x3=int(input('ent... |
from tkinter import *
from tkinter import messagebox
import random
import tkinter.font as font
#Ive commented out winTracker while I figure out what the bug is
#This is the help popup
def popupHelp ():
messagebox.showinfo("Need Help?", "Press the START button to generate a number, then type your answer in the b... |
def bubble_sort(x):
n = len(x)
for i in range(n):
dontNeedToSwap = True
for j in range(n - i - 1):
if x[j] > x[j + 1]:
temp = x[j]
x[j] = x[j + 1]
x[j + 1] = temp
dontNeedToSwap = False
if dontNeedToSwap:
... |
from insertion_sort import *
def quicksort(x):
#Extended Quicksort with Insertion sort when length is lower of equal than 7
n = len(x)
if n == 0:
return []
if n == 1:
return x
if n <= 16:
return insertion_sort(x)
lower = []
higheq = []
eq = []
pivot = inserti... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class bubble_sort(object):
def __init__(self):
pass
"""
最优时间复杂度:O(n) 【表示遍历一次发现没有任何可以交换的元素,排序结束,此时需要加一个计数值判断元素之间是否进行了交换】
最坏时间复杂度:O(n2)
稳定定:稳定 【连续交换】
"""
def bubble_sort_1(self, alist):
"""冒泡排序"""
"""外层循环控制走多... |
'''Mismo ejercicio, pero ahora usando parametros
y atributo de clase'''
class Cargo:
secuencia = 0
def __init__(self, desc='No tiene cargo'):
Cargo.secuencia = Cargo.secuencia + 1
self.codigo = Cargo.secuencia
self.descripcion = desc
if __name__ == '__main__':
cargo1 =... |
class Numeros:
def __init__(self):
pass
# Ejercicio 9
def evaluar(self):
num = int(input('Ingrese numero entero: '))
V = int(input('Ingrese valor'))
if num == 1:
print('Respuesta: ', 100 * V)
elif num == 2:
print('Respuesta: ',100... |
class Ciclo:
def __init__(self, n1=5): # Metodo constructor que inicializa los atributos de la clase.
self.number1 = n1 # Variable de instancia
def utilidadWhile(self):
caracter = input('Ingrese una vocal: ').lower()
while caracter not in ('a','e','i','o','u'):
car... |
# Example 1
# Date: 05/05/2020
# list comprenhension
def acrobot(input_string_value, min_word_length=1):
acronym = ''.join([value[0].capitalize() for value in [item for item in input_string_value.split(" ")] if (len(value) >= min_word_length)])
return acronym
#print(acrobot("Here is my String", min_word_lengt... |
#!/usr/bin/python3
"""
Module that saves an object to a text file using JSON representation
"""
import json
def save_to_json_file(my_obj, filename):
""" saves an object to a text file using JSON representation """
with open(filename, encoding="UTF-8", mode="w") as a_file:
a_file.write(json.dumps(my_... |
number = int(input('Введите число '))
print('Следующее число после %s - это %s' % (number, number + 1))
print('Предыдущее число перед %s - это %s' % (number, number - 1)) |
from thread import start_new_thread
import time
count=0
def func(delay):
global count
while 1:
#print "a"
if count%2 == 0:
print("even : %d" % count)
count+=1
time.sleep(delay)
def func1(delay):
global count
while 1:
#print "a"
if count%2 != 0:
print("odd : %d" % count)
count+=1
time... |
from tkinter import *
top = Tk()
mb= Menubutton ( top, text="CheckComboBox", relief=RAISED )
mb.grid()
mb.menu = Menu ( mb, tearoff = 0 )
mb["menu"] = mb.menu
Item0 = IntVar()
Item1 = IntVar()
Item2 = IntVar()
mb.menu.add_checkbutton ( label="Item0", variable=Item0)
mb.menu.add_checkbutton ( label="Item1", var... |
#simple python script that reads a Makerates produced reaction file and prints every reaction that forms or destroys a chosen species.
from __future__ import print_function
import csv
species='HCN'
f=open('outputFiles/reactions.csv')
reader=csv.reader(f, delimiter=',', quotechar='|')
forms='Species Formed in: \n'
de... |
#Task Week 2
# This program will calculate your BMI
#Will take inputs of height and weight from the user
height = float(input("What is your height in cm : "))
weight = float(input("What is your weight in kg: "))
#need to square the height
h2 = (height/100)**2
#bmi = weight in kg / height squared in cm
bmi = int(wei... |
'''
@author Nicole Hilden
September 22 2018
'''
import requests
import json
def get_repos(githubID):
repos = requests.get("https://api.github.com/users/" +githubID+ "/repos")
retrieved = json.loads(repos.text)
repo_list = []
for i in retrieved:
try: repo_list += [i.get('name')]
... |
#!/usr/bin/python3
def search_replace(my_list, search, replace):
my_list2 = my_list[:]
for i, num in enumerate(my_list):
if num == search:
my_list2[i] = replace
return my_list2
|
#!/usr/bin/python3
"""
Class that defines a square.
"""
class Square:
""" Square with size."""
def __init__(self, size):
self.__size = size
|
#!/usr/bin/python3
def uppercase(str):
lower_case = [97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108,
109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120,
121, 122]
for letter in str:
if ord(letter) in lower_case:
letter = chr(lower_case[low... |
#!/usr/bin/python3
"""
Function text_indentation module
"""
def text_indentation(text):
"""Function that prints a text with 2 new lines after each of
these characters: ., ? and .
Args:
text: input text.
"""
if type(text) != str:
raise TypeError("text must be a string")
... |
#!/usr/bin/python3
def square_matrix_simple(matrix=[]):
matrix_square = [[x**2 for x in i] for i in matrix]
# for i in matrix:
# for x in i:
# x = x**2
# print(x)
return matrix_square
|
# author : Johann-Mattis List
# email : mattis.list@gmail.com
# created : 2013-03-04 17:02
# modified : 2013-10-30 07:14
"""
Module provides functions for reading csv-files.
Simple fork from lingpy for convenience.
"""
__author__="Johann-Mattis List"
__date__="2013-10-30"
import codecs
import os
import re
def... |
from __future__ import division, print_function
import math
from swampy.TurtleWorld import *
def main():
world = TurtleWorld()
bob = Turtle()
bob.delay = 0.0001
#draw flowers
draw_flower(bob, 7,100,60)
shift(bob,200)
draw_flower(bob, 10,80,80)
shift(bob,200)
draw_flower(bob, 2... |
import this
a = 4 + 5
b = {'foo': 'bar'}
for k, v in b.items():
print(k, ":", v) |
def lexicalOrder(n: int):
ret = list()
num = 1
for i in range(n):
ans.append(num)
if num * 10 <= n:
num *= 10
else:
while num % 10 == 9 or num + 1 > n:
num //= 10
num += 1
return ans
a = lexicalOrder(13)
print(a) |
def letterCombinations(digits: str):
if not digits: return []
ret = []
ALP = {'2':"abc", '3':"def", '4':"ghi", \
'5':"jkl", '6':"mno", '7':"pqrs", '8':"tuv", '9':"wxyz"}
total_num = len(digits)
def search(digits, combine, idx):
if len(combine)==total_num:
ret.append(comb... |
import pygame
import os
"""
管理游戏的类
"""
class Manager:
def __init__(self):
self.game_over = True
self.running = True
self.winner = None
self.USER, self.AI = 1, 0
# 游戏窗口宽高及网格大小
self.WIDTH = 720
self.HEIGHT = 720
self.GRID_WIDTH = self.WIDTH // 20
... |
import numpy as np
from scipy.optimize import least_squares
def align2Paraboloid(x, y, z, paraFit):
"""
Applies the shifts and rotations that align
(x,y,z) with the best fit paraboloid.
Parameters
----------
x : array
1-d array with the x coordinates.
y : array
1-d ar... |
# Problem:
# Climbing Stairs
# You are climbing a stair case. It takes n steps to reach to the top.
# Each time you can either climb 1 or 2 steps.
# In how many distinct ways can you climb to the top?
# Framework for Solving DP Problems:
# 1. Define the objective function
# f(i) is the number of distinct ways ... |
# package lecture5
# Problem:
# Climbing Stairs (k steps)
# You are climbing a stair case. It takes n steps to reach to the top.
# Each time you can climb 1..k steps.
# In how many distinct ways can you climb to the top?
# Framework for Solving DP Problems:
# 1. Define the objective function
# f(i) is the numb... |
# Problem:
# Paint Fence With Two Colors
# There is a fence with n posts, each post can be painted with either green or blue color.
# You have to paint all the posts such that no more than two adjacent fence posts have the same color.
# Return the total number of ways you can paint the fence.
def numWays(n: int)... |
website = "http://www.sadikturan.com"
course = "Python Kursu: Baştan Sona Python Programlama Rehberiniz (40 saat)"
# 1- 'course' karakter dizisinde kaç karakter bulunmaktadır ?
# result = len(course)
# length = len(website)
result=len(course)
# 2- 'website' içinden www karakterlerini alın.
# result = website[7:10]
re... |
from tkinter import *
from tkinter import messagebox
class Aplicacion(Frame):
def __init__(self, ventana=None):
super().__init__(ventana)
self.ventana = ventana
self.grid(column=0, row=0)
self.crear_widgets()
def crear_widgets(self):
self.lbl_nombre = Label(self)
self.lbl_nombre["text"] = "Nombre: "
... |
nota1 = float(input("Digite a primeira nota: "))
nota2 = float(input("Digite a primeira nota: "))
nota3 = float(input("Digite a primeira nota: "))
nota_final = (nota1 + nota2 + nota3)
if nota_final >= 21:
print("Aluno Aprovado")
elif nota_final >=9:
print ("Aluno em Recuperação")
else:
print ("Aluno repro... |
#!/usr/bin/python3
"""
takes in a URL, sends a request to the URL and displays the
value of the X-Request-Id variable found in the header of the
response
"""
import urllib.request
from sys import argv
if __name__ == "__main__":
"""takes in a URL, sends a request to the URL and displays
the value of the X-Requ... |
#!/usr/bin/python3
import json
"""JavaScript Object Notation"""
def from_json_string(my_str):
"""find an object (Python data structure) represented by a JSON string
Args:
my_str(str): a string
Returns:
an object (Python data structure) represented by a JSON string
"""
return json.l... |
#!/usr/bin/python3
import json
"""JavaScript Object Notation"""
def save_to_json_file(my_obj, filename):
"""writes an Object to a text file, using a JSON representation
Args:
my_obj(obj): object
filename(str): filename
"""
with open(filename, mode="w", encoding="utf-8") as a_file:
... |
#!/usr/bin/python3
def best_score(a_dictionary):
if a_dictionary is None or a_dictionary == {}:
return None
flag = 1
for key in a_dictionary:
if flag == 1:
largestVal = a_dictionary[key]
largestKey = key
flag = 0
if a_dictionary[key] > largestVal:
... |
#!/usr/bin/python3
def weight_average(my_list=[]):
if my_list == []:
return 0
result = []
weights = []
for tup in my_list:
result.append(tup[0] * tup[1])
weights.append(tup[1])
return sum(result) / sum(weights)
|
#!/usr/bin/python3
class MyInt(int):
"""creates a class MyInt"""
def __eq__(self, other):
"""invert == to !="""
return False
def __ne__(self, other):
"""invert != to =="""
return True
|
#!/usr/bin/python3
class Square:
"""square"""
def __init__(self, size):
"""
initialize square attributes
Args:
size (int): size of square
Returns:
None
"""
self.__size = size
|
'''
Write a python server program that
0. initialized a socket connection on localhost and port 10000
1. accepts a connection from a client
2. receives a "Hi <name>" message from the client
3. generates a random numbers and keeps it a secret
4. sends a message "READY" to the... |
def match_words(l):
Count=0
for item in l:
if (len(item)>=2) and (item[0]==item[-1]):
Count+=1
return Count
List=['abc', 'xyz', 'aba', '1221']
print(match_words(List)) |
Name="Delwar Hossen Asik"
#len() Function Length
print(f"Count: {len(Name)}")
#lower() Method
print(f"Lower Case: {Name.lower()}")
#upper Method
print(f"Upper Case: {Name.upper()}")
#count() Method Same Alphabet
print(f"Same: {Name.count('s')}") #Use (') Single Quotaion |
#Count Method
#short Method
#shorted Function
#Reverse Method
#copy Method
#Clear Method
#Copy Method
List=["Apple","Banana","Mango","Orange","Apple"]
List2=[6,9,2,7,1,5]
print(List.count("Apple"))
#Shorted Function
print(sorted(List))
print(sorted(List2))
#Sorted function does not change the Variable... |
#If Dictianary Have two same keys
DIC={
'Name':"Delwar",
'Age':24,
'Age':34,
}
print(DIC.get("Age")) #Get Last Age keys First Keys Avoid
print(DIC.get("Movie")) #Print None
print(DIC.get("Movie","Not Found")) #We can Menual Print Avoid None |
List=["Apple",3.2225,None,True,8]
List.pop()
print(List)
List.pop(3)
print(List)
#Delete Operator
del List[1]
print(List)
List=["Apple",3.2225,None,True,8,"Apple"]
List.remove("Apple")
print(List) |
#Cube Finder
def cube_find(l):
D={}
for item in range(1,l+1):
D[item]=item**3
return D
n=int(input("Enter cube Value: "))
print(cube_find(n)) |
Program=["java","Python","C#"] #0,1,2
Program.pop() #pass No Valu Default Last Value pop
print(Program)
Program.pop(1)
print(Program)
Program=["Ruby","Go","Ruby","Python"]
del Program[1]
print(Program)
Program.remove("Ruby") #remove First Ruby
print(Program)
|
S={i for i in range(1,9)}
print(S)
S2={i**2 for i in range(1,9)}
print(S2) #Set Unordered
S3={"Apple","Mango","Banana"}
#We need First Char Set
S4={i[0] for i in S3}
print(S4) #Set Unordered |
def Power_List(power,*args):
if args:
return[i**power for i in args]
else:
return "You didn't passed any value"
Num=(1,2,3,6,5,4,8,7)
Num2=()
print(Power_List(3,*Num)) #Pass *Num Unpacked tuple
print(Power_List(3,*Num2)) #Pass *Num2 Empty tuple
|
#for i in range(2,11,5):
# print("Hello World!!!")
"""
sum=0
n=input("Enter Your Number: ")
for i in range(0,len(n)):
sum+=int(n[i])
print(sum)
"""
name=input("Enter your name: ").lower()
temp=""
for i in range(len(name)):
if name[i] not in temp:
print(f" Here {name[i]} : {name.count(name[i... |
def fibo(n):
f1=0
f2=1
for i in range(n):
print(f1, end=" ") # No need return Becouse only one valu return it
sum=f1+f2
f1=f2
f2=sum
n=int(input("Enter your Number: "))
fibo(n) |
P="My Name Is Asik . My Country Is Bangladesh"
P=P.lower()
print(P.replace("is","Was"))
P1=(P.find("is"))
print(P.find("is", P1+1)) |
import random
win=random.randint(1,100)
n=int(input("Guage A number between 1 to 100: "))
for i in range(1,5):
if n==win:
print(f"You win!!! and you try {i} times")
break
elif n<win:
print("Too low!!!")
elif n>win:
print("Too High!!")
n=int(input("Try Again: ")... |
from mcts_node import MCTSNode
from random import choice
from math import sqrt, log
import random_bot
num_nodes = 500
explore_faction = 2.
def traverse_nodes(node, board, state, identity):
""" Traverses the tree until the end criterion are met.
Args:
node: A tree node from which t... |
#!/usr/bin/env python
#-*- coding:utf-8 -*-
# author: xiatian
# 创建只包含一个元素的tuple
a_tuple = (2,)
b_tuple = [2,]
c_tuple = (2)
print(type(a_tuple))
print(type(b_tuple))
print(type(c_tuple))
# 列表与元素混合
mixed_tuple = (1,2,['a','b'])
print("mixed_tuple: ",mixed_tuple)
mixed_tuple[2][0] = 'c'
mixed_tuple[2][1] = 'd'
print("... |
#!/usr/bin/env python
#-*- coding:utf-8 -*-
# author: xiatian
'''
def func_name(arg1,arg2,arg3):
print(arg1,arg2,arg3)
func_name(4,5,8)
age = 22
def change_age():
global age
age = 24
change_age()
print(age)
import time
def test1():
time.sleep(3)
print('in the test1')
test1()'''
'''
import ti... |
# items in the list need not to be of the same type
# accessing values in the list
demo_list1 = ['python', 'java', 'c', 'c++', 1,2,4,5]
demo_list2 = [1,3,4,7,8,9,5]
print('list[2]:', demo_list1[0])
print('list[1:5]', demo_list2[1:5])
# updating lists
demo_list2[3]=99
# deleting list elements
del demo_list1[1]
# fin... |
#Square or Rectangle
#Given the length and breadth of a box, check if it is a Rectangle or Square.
#Input
#The first line of input will contain the length of the box.
#The second line of input will contain the breadth of the box.
#Output
#If the given length and breadth are equal, print "Square". In all other cases, ... |
#Lucky Number - 3
#Given a two-digit number, print "Lucky Number" if any of the following conditions are satisfied
# 1. The number is a multiple of 9
# 2. One of the digits is 9
#Print "Unlucky Number" in all other cases.
#Input
#The first line of input will contain an integer.
#Output
#If any of the above conditions... |
#String Repetition 3
#Given a word and a number (N), write a program to print the last three characters of the word N times in a single line.
#Explanation
#For example, if the given input is "Transport" and the given number is 2.
#The last three characters of the given word are "ort", which have to be repeated 2 time... |
#Validate Password
#Write a program to check if the given string is a valid password or not. A string is considered as a valid password if the number of characters present is greater than 7.
#Explanation
#For example, if the given input is "passwd", it has only 6 characters (less than 7). So the output should be Fals... |
#Lucky Number
#Given two integers, they are considered a lucky pair if any one of them is 6 or if their sum or difference is equal to 6.
#Input
#The first line of input contains a number.
#The second line of input contains a number.
#Output
#If the given conditions are satisfied, print "Lucky". In all other cases, p... |
#Greatest Among Three Numbers
#Write a program which prints the greatest among the given three numbers.
#Input
#The first line of input will contain a number.
#The second line of input will contain a number.
#The third line of input will contain a number.
#Output
#The output should be a single line containing the gre... |
#Relation Between Two Numbers
#Given two integers A and B, write a program to print the relation between the two numbers.
#Input
#The first line of input will contain an integer.
#The second line of input will contain an integer.
#Output
#If A is equal to B, print "A == B".
#If A is greater than B, print "A > B".
#If... |
class Rational(object):
'''Rational with numerator and denominator. Denominator
parameter defaults to 1'''
def __init__(self, numer, denom=1):
print('in constructor')
self.numer = numer
self.denom = denom
def __str__(self):
'''String representation for printing'''
... |
class MyClass(object):
class_attribute = 'world'
def my_method(self, param1):
print('\nhello {}'.format(param1))
print('The object that called this method is: {}'.\
format(str(self)))
self.instance_attribute = param1
my_instance = MyClass()
print('output of dir(my_instance):')
... |
import random
class Island(object):
'''Island
n X n grid where zero value indicates an unoccupied cell.'''
def __init__(self, n, prey_count=0, predator_count=0):
'''Initialize cell to all 0's, then fill with animals
'''
#print(n, prey_count, predator_count)
self.grid_size =... |
# simple while
x_int = 0 # initialize loop-control variable
# test loop-control variable at beginning of loop
while x_int < 10:
print(x_int, end=' ') # print the value of x_int each time through the while loop
x_int += 1 # change loop-control variable
print()
print('Final value of x_int:', x_int) # b... |
# Anagram test
def are_anagrams(word1, word2):
'''Return True, if words are anagrams.'''
# 2. Sort the characters of the words.
word1_sorted = sorted(word1) # sorted returns a sorted list
word2_sorted = sorted(word2)
# 3. Check that the sorted words are identical.
return word1_sorted == wor... |
import math
global_X = 27
def my_function(param1=123, param2='hi mom'):
local_X = 654.321
print('\n=== local namespace ===')
for key,val in locals().items():
print('key: {}, object: {}'.format(key, str(val)))
print('local_X:',local_X)
print('global X:',global_X)
my_function()
key,val = 0,0 #... |
# Calculate rainfall in gallons for some number of inches on 1 acre.
inches_str = input('How many inches of rain have fallen: ')
inches_int = int(inches_str)
volume = (inches_int / 12) * 43560
gallons = volume * 7.48051945
print(inches_int, 'in. rain on 1 acre is', gallons, 'gallons')
|
dig_str = input('Input an integer: ')
try:
if dig_str.isdigit():
dig_int = int(dig_str)
else:
raise ValueError(dig_str) # raise an exception here!
except ValueError:
print('Conversion to int Error:', dig_str) |
def vowel_search(size):
lis=[]
for x in range(0,size):
lis.append(input())
vowels="aeiouy"
count = "\n answer: \n"
for string in lis:
vowelcount=0
for alpha in string:
if alpha in vowels:
vowelcount+=1
if(vowelcount>0):... |
import numpy as np
"""Shape of an Array
Shape of a two-dimensional array
The function "shape" returns the shape of an array. The shape is a tuple of integers. These numbers denote the lengths of the corresponding array dimension. In other words: The "shape" of an array is a tuple with the number of elements per axis (... |
#Creating Arrays
"""Zero-dimensional Arrays in Numpy
It's possible to create multidimensional arrays in numpy. Scalars are zero dimensional. In the following example, we will create the scalar 42. Applying the ndim method to our scalar, we get the dimension of the array. We can also see that the type is a "numpy.ndarr... |
# BACK-END : Will detect if the mouse is hovering Input bar or buttons and will change his skin
import pygame, os
from module import timeVar, fileDir
pygame.init()
tempIClicked = False
xScreen = 450
yScreen = 550
screen = pygame.display.set_mode((xScreen, yScreen))
black = (40, 40, 43)
grey = (67, 67, 70)
lavanda = ... |
#Implement an algorithm to determine if a string has all unique characters.
def is_unique(str):
#create a seen dictionary, for fast lookup if a char has been seen
seen = {}
#in order to return False, otherwise leaving this out will return None for empty string
if len(str) == 0:
return False
... |
seconds_per_minute = 60
seconds_per_hour = 60*seconds_per_minute # 3600
# get user input in seconds
seconds = int(input("Please enter the number of seconds:"))
# first, compute the number of hours in the given number of seconds
hours = seconds // seconds_per_hour
seconds = seconds % seconds_per_hour
minutes = sec... |
from math import sqrt
num = float(input("Enter number: "))
root = sqrt(num)
print("Square root of", num, "=", root)
|
from time import clock
max_value = 10000
count = 0
start_time = clock() # start timer
# try values from 2 to max_value
for value in range(2, max_value + 1):
is_prime = True;
for trial_factor in range(2, value):
if value % trial_factor == 0:
is_prime = False
break
if is_prime... |
#menampilkan informasi programe
print("Konversi suhu (Fahrenheit ke Celcius)")
#input suhu dalam fahrenheit
F = float(input("Masukkan suhu(fahrenheit): "))
#melakukan konversi suhu fahrenheit ke celcius
C = 5 * (F-32) / 9
#menampilkan hasil konversi ke layar
print("Fahrenheit: ", F)
print("Celcius: ", C... |
def anagram(string1, string2):
"""Determines whether two strings provided are anagrams"""
# create a list of letters in string, then sort
s1 = sorted(list(string1))
s2 = sorted(list(string2))
if len(s1) != len(s2):
return False
else:
for i in range(len(s1)):
if s... |
#! python3
def rec_mergeSort(array):
""" Perform merge sort by recursively splitting array into
halves until all the values are separated
then do a piece wise comparason to fill the array in order
"""
# check if array is none
if len(array) > 1:
# find mid index of list
mid = len(... |
def insertionSort(array):
""" sort an array by inserting items
where appropriate by iterating through
an array """
# iterate through list starting from second
# value
for i in range(1, len(array)):
# initialize variables
current_val = array[i]
# check where current value... |
def rec_fib(n):
"""returns the nth fibonacci number recursively"""
if n == 0:
return 0
elif n == 1:
return 1
else:
return rec_fib(n-1) + rec_fib(n-2)
print(rec_fib(5)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.