text stringlengths 37 1.41M |
|---|
# A Segment Key that is used to identify a segment in the segments graph (SG)
class SG_Key:
exs = []
exs_str = ""
pos = 0
def __init__(self):
self.exs = []
self.exs_str = ""
self.pos = 0
def addEx(self, ex):
self.exs.append(ex)
self.exs_str = ... |
# TUGAS PARALEL 1 AI NI LUH MADE DITA ANJANI 1301174676 IFIK-41-01
import random
chrom = []
x1x2 =[]
fitness = []
ortu = []
x1 = []
x2 =[]
x = []
def chromo():
n = 10
for i in range (n):
#pemilihan chromosom dgn cara random antara biner 0,1 namun disini dibagi dua
#agar dapat dihitung x1 dan x2 secara terpisah
... |
# this drill attempts to take a number set, sort it in ascending order without using .sort and sorted() algorithms
numset1 = [67, 45, 2, 13, 1, 998]
numset2 = [89, 23, 33, 45, 10, 12, 45, 45, 45]
numlist = []
def my_sort(numlist = numset1):
sorted_list = []
while numlist:
var_pick= numlist[0]
... |
# add up and count the input number, end with "done"
num = 0
tot = 0.0
while True:
sval = input("Enter a number")
if sval == 'done':
break
try:
fval = folat(sval)
except:
print("Invalid input")
continue
print(fval)
num = num + 1
tot = tot + fval
print(tot, nu... |
# prompt the user for hours and rate per hour using input to compute gross pay.
# a function of compute pay
def computepay(h,r):
if h > 40:
pay = 40 * r + (h - 40) * r * 1.5
else:
pay = h * r
return pay
hrs = input("Enter Hours:")
rate = input ("Enter Rate:")
try:
fh = float(hrs)
f... |
from collections import deque
N = int(input())
card = deque(list(range(1,N+1)))
while card:
if len(card) == 1:
break
card.popleft()
value = card.popleft()
card.append(value)
print(card[0]) |
def find(n, arr,left, right):
if left > right:
return False
mid = (left+right) // 2
if arr[mid] > n:
return find(n, arr, left, mid-1)
elif arr[mid] < n:
return find(n, arr, mid+1, right)
else:
return True
N = int(input())
cards = list(map(int, input().split()))
m = i... |
a = input()
b = input()
node = 0
cnt = 0
while node+len(b) <= len(a):
if a[node:node+len(b)] == b:
cnt += 1
node += len(b)
else:
node += 1
print(cnt) |
#Autor: Michelle
#Descripción:
#Diccionario
d = {"chicken":"pollito", "pencil":"lapiz", "pen":"pluma"}
def leerOpcion():
print("""
1. Traducir Inglés->Español
2. Traducir Español->Inglés
0. Salir
""")
opcion = int(input("Teclea tu opción: "))
print(opcion)
return opcion... |
hours = input("Enter Hours:")
rate = input("Enter Rate Per Hour:")
try:
h = float(hours)
r = float(rate)
except:
print("Error, please enter numeric values")
quit()
print("You have entered", "employee working hours = ", h, "and rate per hour =", r, "rupees")
if h>40:
pay = (40*r) + (h-40)*(r*1.5)
... |
"""Tests for lists.py"""
from lists import (
get_words_by_first_letter,
filter_by_length,
words_in_common,
every_other_item,
smallest_n_items,
get_index,
)
##
# Test for get_words_by_first_letter
def test_get_words_by_first_letter_is_list():
"""Test that the return value of get_words_by_... |
"""Skills 5: SQLAlchemy & AJAX
Part 1: Define Model Classes
"""
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class Human(db.Model):
"""Data model for a human."""
__tablename__ = 'humans'
human_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
fname = db.Column(db.Strin... |
#!/usr/bin/python
#wap to sum of list elements(user input) using generators?
def fun(list1):
for ele in list1:
yield ele
list1=[1,2,3,4,5,6]
list_sum=0
for ele in fun(list1):
list_sum+=ele
print "sum is:",list_sum
|
#!/usr/bin/python
dict1={'name':'sandeep','Age':55,'Class':'1st'}
print dict1['name']
print dict1['Age']
del dict1['name']
print dict1
dict1['Age']=66
print dict1
|
#!/usr/bin/python
list1=[1,2,3,4,5]
length=len(list1)
for index in range(length):
print list1[index],
itr=iter(list1)
for index in range(length):
print itr.next()
####tuple
tup=(1,2,3,4,5)
length=len(tup)
for index in range(length):
print tup[index],
itr=iter(tup)
for index in range(length):
print itr.next()
###... |
#!/usr/bin/python
def linear_search(list1,data):
list_len=len(list1)
for index in range(list_len):
if(list1[index]==data):
return index
if(index==list_len):
return -1
list1=[3,2,4,5,7,8,9,34]
data=0
flag=linear_search(list1,data)
if(flag==None):
print "data not found"
else:
print "found at ",flag
|
#!/usr/bin/python
dict1={}
dict1['name']='abc'
dict1['class']='last'
print dict1
print dict1.keys()
print dict1.values()
print dict1.items()
#dict2={'key1':123,'abc','key2':44}
#print dict2
dict2={('key1'):123,'key2':44}
print dict2['key1']
dict2={('key1'):(123,33),'key2':[44,12]}
print dict2['key1'],dict2['key2']
|
#!/sur/bin/python
import sys
print "cmd line sum"
sumcmd=lambda v1,v2:v1+v2
total_sum=reduce(sumcmd,sys.argv)
print total_sum
"""total_sum=0
total_num=len(sys.argv)
for index in range(1,total_num):
num=int(sys.argv[index])
total_sum+=num
print total_sum
"""
|
#!/usr/bin/python
string=raw_input("enter a string:")
print string.center(10,'a')
print string.capitalize()
#print string.find("de",5)
#print string.index("de")
#print "isalnum:",string.isalnum()
str1=u"0123"
print "numeric:",str1.isnumeric()
print "isdec:",str1.isdecimal()
#print string.replace("dee","abcd",2)
print s... |
#!/usr/bin/python
list1=(123,23,"abc");list2=(2,99,"Abc")
print cmp(list1,list2)
print cmp(list2,list1)
print max(list1)
print min(list1)
print max(list2)
print min(list2)
print list(list1),list1
tup1=list(list1)
tup1.append(25)
tup1=tuple(tup1)
print tup1
"""print list1
list1.extend(list2)
print list1
print list1.inde... |
#!/usr/bin/python
v1_start=1;v1_end=2;v2_start=2;v2_end=11;
while(v1_start<v1_end):
while(v2_start<v2_end):
print "%d:%d"%(v2_start,v2_end)
v2_start+=2
else:
print "end of inner while"
v1_start+=1
else:
print "end of outer while"
|
#!/usr/bin/python
val1=20
val2=2
res = (val1==val2)
print res
res= (val1<>val2)
print res
res= (val1!=val2)
print res
res=(val1<val2)
print res
res=(val1>val2)
print res
res=(val1<=val2)
print res
res=(val1>=val2)
print res
|
#!/usr/bin/python
num = 10
print "asdfsdf"
guess=input("guess a number:")
print guess
if num==guess:
print "congrats,your guess is correct"
elif(num<guess):
print "you entered littile higher"
else:
print "lower than original"
print "return"
|
#!/usr/bin/python
for cntr in range(1,20,2):
print cntr,
print
for cntr in range(-10,5):
print cntr,
else:
print
print "over"
|
#!/usr/bin/python
class parent:
parentattr=10
def __init__(self):
print "in parent constructor"
def parentmethod(self):
print "in parent method"
def setAttr(self,attr):
parent.parentattr=attr
def getAttr(self):
print "parent attr:",parent.parentattr
class child(parent):
def __init__(self):
print "in chi... |
# https://deeplearningcourses.com/c/data-science-deep-learning-in-theano-tensorflow
# https://www.udemy.com/data-science-deep-learning-in-theano-tensorflow
from __future__ import print_function, division
from builtins import range
# Note: you may need to update your version of future
# sudo pip install -U future
# Not... |
# https://deeplearningcourses.com/c/unsupervised-deep-learning-in-python
# https://www.udemy.com/unsupervised-deep-learning-in-python
from __future__ import print_function, division
from builtins import range, input
# Note: you may need to update your version of future
# sudo pip install -U future
import numpy as np
i... |
# https://deeplearningcourses.com/c/deep-learning-convolutional-neural-networks-theano-tensorflow
# https://udemy.com/deep-learning-convolutional-neural-networks-theano-tensorflow
from __future__ import print_function, division
from builtins import range
# Note: you may need to update your version of future
# sudo pip ... |
# This code is for my NLP Udemy class, which can be found at:
# https://deeplearningcourses.com/c/data-science-natural-language-processing-in-python
# https://www.udemy.com/data-science-natural-language-processing-in-python
# It is written in such a way that tells a story.
# i.e. So you can follow a thought process of ... |
# https://deeplearningcourses.com/c/unsupervised-deep-learning-in-python
# https://www.udemy.com/unsupervised-deep-learning-in-python
from __future__ import print_function, division
from builtins import range
# Note: you may need to update your version of future
# sudo pip install -U future
import numpy as np
import t... |
# demonstrates how to calculate the output of a logistic unit using numpy.
# the data X and weight matrix w are randomly generated from a
# standard normal distribution.
#
# the notes for this class can be found at:
# https://deeplearningcourses.com/c/data-science-logistic-regression-in-python
# https://www.udemy.com/... |
# The corresponding tutorial for this code was released EXCLUSIVELY as a bonus
# If you want to learn about future bonuses, please sign up for my newsletter at:
# https://lazyprogrammer.me
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
# we nee... |
# https://deeplearningcourses.com/c/machine-learning-in-python-random-forest-adaboost
# https://www.udemy.com/machine-learning-in-python-random-forest-adaboost
from __future__ import print_function, division
from builtins import range, input
# Note: you may need to update your version of future
# sudo pip install -U fu... |
import cs50
while True:
print("Type a number between 0 and 23: ", end="")
height = cs50.get_int()
if height > 0 or height < 23:
break
a = 0
for a in range(a,height,+1):
spaces = height - a
for spaces in range(spaces,0,-1):
print(" ", end="")
spaces = spaces - 1
print("#" ... |
input_letters = ['Q', 'W', 'E', 'R', 'T', 'A', 'S', 'D', 'F', 'G', 'Z', 'X', 'C', 'V', 'B']
valid_tokens = input_letters + ['(', ')', ' ']
rows = ['A', 'B', 'C']
input_letter_mappings = {}
# Match keyboard to piano grid mapping
for row in rows:
for column in range(1, 5+1):
note = row + str(column)
... |
""" Author - Kiel Rochow
Creating a seperate file, which is a function to be called to read and
return the chr signal to flight platform
"""
import serial
import time
import sys
import datetime
import string
# From remote receiver tutorial
def align_serial(ser):
"""Aligns the serial stream with the incoming Spe... |
def fibSimple(n):
if n <= 2 and n > 0:
return 1
elif n == 0:
return 0
else:
return fibSimple(n-1) + fibSimple(n-2)
def fibAdvance(n):
c = 2
fibs = [0, 1, 1]
return fibHelper(n, c, fibs)
def fibHelper(n, c, fibs):
if n < 0:
print 'No existe un numero de ... |
import matplotlib.pyplot as plt
#reading the list of values as x1,y1
plt.bar([1,3,5,7,13],[5,2,7,8,6], label="BarEg one")
#reading the list of values as x2,y2
plt.bar([2,4,12,8,10],[8,6,3,5,7], label="BarEg two", color='g')
plt.legend()
#naming the x,y axis
plt.xlabel('number')
plt.ylabel('height of bar')
#naming the ... |
#addition of two matrix elements
_author__ = "Dilipbobby"
#3x2 matrix
A = [[1,2,3],
[4,5,6],
[7,8,9]]
B = [[10,11,12],
[13,14,15],
[16,17,18]]
Result = [[0,0,0],
[0,0,0],
[0,0,0]]
# iterate through rows
for i in range(len(X)):
... |
#CALCULATOR USING def_function
import time
while 'a'=='a':
print("▂▃▄▅▆▇█▓▒░-WELCOME-░▒▓█▇▆▅▄▃▂")
time.sleep(1)
print("LOADING" , end=" ")
print(".", end=" ")
time.sleep(0.2)
print(".", end=" ")
time.sleep(0.2)
print(".", )
time.sleep(0.2)
time.sleep(0.2)
for i in range(50):
print... |
# print('pterodactyls')
my_items = {
"tv": 30,
"timmy": 20,
"stereo": 50
}
def find_it(items, name):
if name in items.keys():
print("its here")
else:
print("no senor")
find_it(my_items, 'timmy')
find_it(my_items, 'john')
# print(find_it(my_items, "timmy"))
# print(find_it(... |
# print('Hello World')
# //////////////////////////////////////////////////////
# Basic Conditional Code:
# ex 1
# x = 10
# if x < 8:
# print("Smaller than 8")
# elif x > 8:
# print("Greater than 8")
# ex 2
# y = 4
# i... |
def wordsinfile():
#opening the file
readwords = open("written file.txt", "r")
word_count = 0
# opeing the wile as an readwords variable
with readwords as file:
for word in file: #for all the words in the file
word_count += len(word.split()) ... |
from Class_Bakery import Bakery_Item
from User_Interface import User_Interface
def User_Interface_menu(self):
n = 1
choice = 0
create_an_item = 1
read_an_item = 2
update_an_item = 3
delete_an_item = 4
count_in_bakery = 5
value_of_bakery = 6
percentage_of_unbroken = 7
exit = 8
... |
from Class_Bakery import Bakery_Item
class User_Interface:
def __init__(self):
self.menu_stock = {}
# def read_from_file(self, file_name):
# file = open(file_name, "rb")
# file.close()
def create_an_item(self, bakery_item):
note = input("Please Enter the Note for the Item: ")... |
def main():
#Asking for the number of words user wants to enter
numberofwords = int(input("Enter the number of words to be written to a file: "))
#Creating an file with the write funtion w
wordfile = open("Written file.txt", "w")
#Enetering the number of the words informed by the user
word = i... |
# The 2 sample list
list1 = [67, 45, 2, 13, 1, 998]
list2 = [89, 23, 33, 45, 10, 12, 45, 45, 45]
# Print the sorted version of the 2 sample lists
print sorted(list1)
print sorted(list2)
# Sorted, using a bubble sort
def sorted (list):
# copy the list, since we don't want to disturb the original
tList = ... |
from collections import deque
num_of_petrol_pumps = int(input())
petrol_pumps = deque()
for _ in range(num_of_petrol_pumps):
petrol_pumps.append(list(map(int, input().split())))
for index in range(num_of_petrol_pumps):
is_completed = True
curr_fuel = 0
for pump in petrol_pumps:
curr_fuel += pu... |
regular_guests = set()
VIP_guests = set()
num_of_guests = int(input())
for _ in range(num_of_guests):
reservation_code = input()
if reservation_code[0].isdigit():
VIP_guests.add(reservation_code)
else:
regular_guests.add(reservation_code)
coming_guest = input()
while not coming_guest == ... |
def fill_the_box(height, length, width, *args):
size_of_box = height * length * width
left_cubes = 0
for el in args:
if el == "Finish":
break
if el <= size_of_box:
size_of_box -= el
else:
el -= size_of_box
size_of_box = 0
... |
def print_sum(cmd, nums):
parity = 0 if cmd == "Even" else 1
print(sum(filter(lambda x: x % 2 == parity, nums)) * len(nums))
command = input()
numbers = [int(x) for x in input().split()]
print_sum(command, numbers)
|
size = int(input())
matrix = []
for _ in range(size):
line = [int(x) for x in input().split(", ")]
matrix.append(line)
primary_diagonal = []
secondary_diagonal = []
for i in range(size):
primary_diagonal.append(matrix[i][i])
secondary_diagonal.append(matrix[i][size - 1 - i])
print(f"Primary diagona... |
def init_matrix(size):
matrix = []
b_rows = []
b_cols = []
s_row = 0
s_col = 0
for i in range(size):
line = list(input())
matrix.append(line)
if "S" in line:
s_row = i
s_col = line.index("S")
if "B" in line:
b_rows.append(i)
... |
from collections import deque
cups = deque([int(x) for x in input().split()])
bottles = [int(x) for x in input().split()]
wasted_water = 0
while cups and bottles:
curr_cup = cups.popleft()
curr_bottle = bottles.pop()
if curr_cup <= curr_bottle:
wasted_water += curr_bottle - curr_cup
else:
... |
file = open("numbers.txt", "r")
sum_numbers = 0
for line in file:
sum_numbers += int(line)
print(sum_numbers)
|
num_of_lines = int(input())
longest_intersection = set()
for _ in range(num_of_lines):
first_range, second_range = input().split("-")
first_start, first_end = map(int, first_range.split(","))
second_start, second_end = map(int, second_range.split(","))
first_set = set()
second_set = set()
for ... |
'''
In a given grid of 0s and 1s, we have some starting row and column sr, sc and a target row and column tr, tc. Return the length of the shortest path from sr, sc to tr, tc that walks along 1 values only.
Each location in the path, including the start and the end, must be a 1. Each subsequent location in the path mu... |
#coding:utf-8
#global variables
board=["-","-","-",
"-","-","-",
"-","-","-"]
#If game still is going
game_still_going = True
#whole won?or tie?
winner = None
#Whos turn is it
current_player ="X"
def display_board():
print(board[0]+ "|" + board[1]+"|"+board[2])
print(board... |
from vectors import *
origin = Vector(i=0, j=0)
g = Vector(i=0, j=-9.8)
t, x, y, s, v, a = sp.symbols('t x y s v a')
class Body(object):
"""
Base class for defining a body performing motion.
"""
def __init__(self, name, position=origin, velocity=Vector(i=0, j=0), acceleration=Vector(i=0, j=0),
... |
# url: https://leetcode.com/problems/fizz-buzz/submissions/
# writtenby: hoangddt
class Solution:
def fizzBuzz(self, n):
"""
:type n: int
:rtype: List[str]
"""
result = []
for number in range(1, n+1):
if (number % 3 == 0) and (number % 5 == 0):
... |
# Done: Parses through XML of the Torah, stripping vowels/accents and loading
# data into a Sqlite DB, also inserting formations
# To do: Match up words to KJV and Strong's numbers
# Regenerate the torah as an interlinear bible in wiki friendly format
# To run this script, first unzip Tanach.xml.zip (inclu... |
'''
Max and Second Max
Given an array arr[] of size N of positive integers which may have duplicates. The task is to find the maximum and second maximum from the array, and both of them should be distinct, so If no second max exists, then the second max will be -1.
Input Format:
The first line of input contains the n... |
import numpy as np
# Create an array of 10 zeros
arr = np.zeros(10)
# Create an array of 10 ones
arr = np.ones(10)
# Create an array from 0 to 10 skipping 2 each
arr = np.arange(0, 11, 2)
# Create an array of 10 fives
arr = np.zeros(10) + 5
# Create an array of the integers from 10 to 50
arr = np.arange(10, 51)
#... |
height = int(input("Altura?"))
while height > 0:
print(height * "*")
height = height - 1
'''
*****
****
***
**
*
''' |
# -*- coding:utf-8 -*-
# author:许浩
from typing import List
class SortList:
def __init__(self,numList:List,MaxSize=50):
self.numList=numList
self.MaxSiae=MaxSize
def ListInsert(self,i:int,e:int)->bool:
if i<1 or i>len(self.numList)+1:
return False
if i>self.MaxSiae:... |
#89342
class ListNode(object):
def __init__(self,val,next=None):
self.val=val
self.next=next
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if l1==None:
return l2
if l2==None:
return l1
while l1 and l2:
... |
from typing import List
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
result=[]
for item1 in nums1:
for item2 in nums2:
if item1==item2:
result.append(item1)
result=list(set(result))
return r... |
# -*- coding: utf-8 -*-
# Generated by xuhao on 2020/11/7 22:58
class Node(object):
def __init__(self,data,leftChild=None,rightChild=None):
self.data=data
self.leftChild=leftChild
self.rightChild=rightChild
class BSTInsert(object):
def bst_insert(self,T:Node,key:int)->int:
""... |
# -*- coding:utf-8 -*-
from chapter3.Stack.Stack import Stack
class Solution(object):
def __init__(self):
self.__stack=Stack(50)
self.__sign=['(',')','-','+','*','/']
self.__equationResult=[]
def conversion(self,equation):
for item in equation:
if item not in self.... |
from typing import List
class ListNode:
def __init__(self, x,next=None):
self.val = x
self.next = next
class Solution:
def reversePrint(self, head: ListNode) -> List[int]:
result=[]
while head:
result.append(head.val)
head=head.next
result.revers... |
class Solution:
def toLowerCase(self, str: str) -> str:
result=""
strList=list(str)
print(ord("a"))
print(ord("Z"))
for item in strList:
if ord(item)>=65 and ord(item)<=90:
result+=chr(ord(item)+32)
else:
result+=item
... |
class Solution:
def lengthOfLastWord(self, s: str) -> int:
if s=="" or s==" ":
return 0
strlist=s.split(" ")
i=len(strlist)-1
while i>=0:
if strlist[i]=="":
strlist.pop(i)
i-=1
if len(strlist)==0:
return 0
... |
class Solution:
def countSegments(self, s: str) -> int:
if s == '':
return 0
strlist=s.split(" ")
result=[]
for item in strlist:
if item!='':
result.append(item)
return len(result)
if __name__=="__main__":
print(Solution().countSeg... |
class Solution:
def romanToInt(self, s: str) -> int:
num0={"I":1,"V":5, "X":10,"L":50,"C":100,"D":500,"M":1000,"IV":4,"IX":9,"XL":40,"XC":90,"CD":400,"CM":900}
numstr=list(s)
result=0
i=0
num1=[]
while i<len(numstr):
if i+1<len(numstr) and numstr[i]+numstr... |
from typing import List
class SeqList:
def __init__(self,data,MaxSize,length):
self.data=data
self.MaxSize=MaxSize
self.length=length
class Solution(object):
def deleteMinValue(self,L:SeqList)->int:
if L.length==0:
return -1
minIndex=0
value... |
from typing import List
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
for item in range(k):
tmp=nums.pop(-1)
nums.insert(0,tmp)
if __name__=="__main__":
nums=[1,2,3,4,5,... |
# -*- coding: utf-8 -*-
# Generated by xuhao on 2020/11/9 13:20
"""
希尔排序
"""
def shellSort(A:list)->list:
new_A=[None]+A
n=len(A)
dk=int(n/2)
while dk>=1:
i=dk+1
while i<=n:
if new_A[i]<new_A[i-dk]:
new_A[0]=new_A[i]
j=i-dk
wh... |
from typing import List
class Solution:
def addList(self,numList1:List,numList2:List)->List:
result=[]
i,j=0,0
while i<len(numList1) and j<len(numList2):
if numList1[i]<=numList2[j]:
result.append(numList1[i])
i+=1
else:
... |
class ListNode(object):
def __init__(self,val,next=None):
self.val=val
self.next=next
class Solution(object):
def isPalindrome(self, head: ListNode) -> bool:
nums=[]
while head!=None:
nums.append(head.val)
head=head.next
return nums==nums[::-1]
... |
"""
8-7 Album: Write a function called make_album() that builds a
dictionary describe a music album. THe function should take in an
artist name and an album title, and it should return a dictionary
containing these two pieces of information. Use the function to
make three dictionaries representing different albums. ... |
"""
9-3 Users: Make a class called user. Create two attributes called first_name
and last_name, and then create several other attributes that are typically
stored in a user profile. Make a method called describe_user() that prints
a summary of the user's information. Make another method called greet_user()
that prints ... |
"""
9-14 Dice: The module random contains a function that generates random
numbers in a variety of ways. The function randint() returns an integer
in the range you provide. The following code returns a number between
1 and 6:
from random import randint
x = randint(1, 6)
Make a class Die with one attribute called side... |
"""
10-5 Programming Poll: Write a while loop that asks people
why they like programming. Each time someone enters a reason,
add their reason to a file that stores all the responses.
"""
filename = "programming_poll.txt"
with open(filename, "a") as file_object:
while True:
reason = raw_input("Why do you like to pro... |
"""
9-1 Restaurant: Make a class called Restaurant. The __init__()
method for Restaurant should store two attributes: a restaurant_name
and a cuisine_type. Make a method called describe_restaurant()
that prints these two pieces of information, and a method called
open_restaurant() that prints a message indicating that... |
"""
9-9 Battery Upgrade: Use the final version of electric_car.py from this
section. Add a method to the Battery class called upgrade_battery(). This method
should check the battery size and set the capactiy to 85 if it isn't already.
Make an electric car with a default battery size, call get_range() once, and
then ca... |
import datetime
#-----------------------------------------------------------------------------
#HELPER FOR THE HELPERS
def connectCursor():
'''
returns the mysql connection and the cursor for further use
'''
connection = mysql.connector.connect(user='root', password='bluecrew', database='Aoc')
cur = connection.cur... |
#Wencchao Yao Homework 7
import pandas as pd
# Part A
customer = {'name': 'Orwell', 'address':'4 Church St', 'age':'46'}
address = customer['address']
print(address)
customer['birthday'] = '25 June'
customer['name'] = 'Orwell,George'
print(customer)
new_customer = {}
new_customer[1] = customer
new_customer[2] = {'name... |
def add_10(value) :
if value < 10:
return 10
result = value + 10
return result #함수 즉시 종료
n=add_10(5)
print(n)
n=add_10(42)
print(n)
n=round(1.5)
print(n) |
# we are going to create a script to find files older than a specific date
import os
import sys
import datetime
age=1 # how many days we want to print files for
req_path=input("enter your path: ")
if not os.path.exists(req_path):
print("enter an existing path")
sys.exit(1)
if os.path.isfile(req_path):
pri... |
# create title from string and display centre screen based on screen size
import os #import os module
sz=os.get_terminal_size().columns #get column number
title=input("give me the title:")
print(title.center(sz).title())
# create title from string and display left and right screen based on screen size
print(titl... |
# working with text files with Python
# create new file - remember whenever you open a file in write mode the data will always be created from 0
# as new file is created with the provided content included
fo=open("C:\\Test\\test_file.txt","w") # to create a file you need to use w=write mode
# fo.close() # close will... |
def to_str(n,base):
convert_string="0123456789ABCDEF"
if n<base:
return convert_string[n]
else:
return to_str(n//base,base)+convert_string[n%base]
print(to_str(1453,16))
|
import sys
def palindrome_rec(str):
if len(str)==1 or len(str)==0:
return True
else:
if str[0]==str[-1]:
return palindrome_rec(str[1:-1])
else:
return False
#print(palindrome_rec("kayak"))
print(palindrome_rec(str(sys.argv[1])))
|
#Snake by Viren W
import turtle
import time
import random
d = 0.1
#Initializes Score
score = 0
highScore = 0
#Screen Setup
Window = turtle.Screen()
Window.title("Snake by Viren")
Window.bgcolor("white")
Window.setup(width = 700, height = 700)
Window.tracer(0)
#Snake Head
TurtleHead = turtle.Turtle()
TurtleHead.sp... |
'''
Создайте программу, которая выводит на экран
дополнительный код введенного с клавиатуры шестнадцатеричного числа
на восемь разрядов
'''
def twos_comp(val, bits):
"""compute the 2's complement of int value val"""
if (val & (1 << (bits - 1))) != 0: # if sign bit is set e.g., 8bit: 128-255
val = val -... |
'''
Операции cо словарями
'''
d2 = dict(bananas=3,apples=5,oranges=2,bag="basket")
d5 = d2.copy() # создание копии словаря
print("Dict d5 copying d2 = ", d5)
40
# получение значения по ключу
print("Get dict value by key d5['bag']: ", d5["bag"])
print("Get dict value by key d5.get('bag'): ",
d5.get('bag'))
print("Get d... |
'''
Строки
'''
group = input("What is your group number? ")
print("Your group is ",group)
print("\nString:")
# получение символов строки в цикле (1)
for i in range(0,len(group)):
print(group[i], end=" ")
print("\nString:")
# получение символов строки в цикле (2)
for elem in group:
print(elem, end=" ")
print("\n... |
def toupleMaker(dictionary):
toupleList = []
for key in dictionary:
toupleList.append((key,dictionary[key]))
return toupleList
my_dict = {
"Speros": "(555) 555-5555",
"Michael": "(999) 999-9999",
"Jay": "(777) 777-7777"
}
print(toupleMaker(my_dict)) |
while True:
list1 = input("\nInput first list: ")
list2 = input("Input second list: ")
if len(list1) != len(list2):
print("The lists are not the same.\n")
else:
same = True
i = 0
while i < len(list1):
if list1[i] == list2[i]:
i += 1
... |
# ~~~~~~~~~~~~~~ FINAL PROJECT ~~~~~~~~~~~~~~
# ~~~~~~~~~~~~~~ NOA BEN-GIGI 318355633 ~~~~~~~~~~~~~~
# ~~~~~~~~~~~~~~ LION DAHAN 318873338 ~~~~~~~~~~~~~~
# ~~~~~~~~~~~~~~ YAM HARUSH 318886058 ~~~~~~~~~~~~~~
# ~~~~~~~~~~~~~~ MICHAEL HARUSH 208829085 ~~~~~~~~~~~~~~
# generate random integer values
fr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.