text stringlengths 37 1.41M |
|---|
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 22 19:52:58 2019
@author: Joe
"""
#Creating a simple list of friend names
friends = ["Ben","Yarden","Michael"]
print(friends)
#Adding Gabi's name to the end of the list
friends.append("Gabi")
print(friends)
#Adding Abby's name between Ben and Yarden in the list
friends.... |
# Creating a test for the class created in Employee.py
import unittest
from Employee import Employee
class EmployeeTestCase(unittest.TestCase):
"""Test for 'Employee.py'"""
def setUp(self):
"""Creates an employee for use in all test methods"""
self.my_employee = Employee('joe', 'pickert', 65... |
# creating a dictionary of personal information
stranger = {
'first_name' : 'pablo',
'last_name' : 'sandoval',
'hometown' : 'syracuse',
'sport' : 'baseball'
}
print("The stranger's first name is " + stranger['first_name'].title() +".")
print("His last name is " + stranger['last_name'].title() + ".")
pri... |
import sys
from random import randrange
#Author: J. Andrew Key
#Objective: Implement quicksort (aka "partition-exchange" sort) that makes
#on average, O(n log n) comparisons to sort n items. This solution benefits
#from "list comprehensions", which keeps the syntax concise and easy to read.
def quicksort(list):
# a... |
#!/usr/bin/env python2.7
import time
import datetime
d1 = datetime.datetime(2005,2,16)
d2 = datetime.datetime(2004,12,31)
print (d1 - d2).days
|
class ResizableArray(object):
"""Class representing resizable array implementation"""
def __init__(self, capacity):
self.capacity = capacity
self.size = 0
self.arr = [None] * self.capacity
def __getitem__(self, key):
self._check_index_range(key)
return self.arr[key... |
import random
import seven_up_deck
# ********************************************************
# CLASS: Round
# ********************************************************
class Round():
# ********************************************************
# METHOD: __init__
# *******************************************... |
# -*- coding: utf-8 -*-
import time
def timer(func):
'''A simple decorator to count time.
'''
def wrapper(*args, **kwds):
time_begin = time.time()
ret = func(*args, **kwds)
time_end = time.time()
time_cost = time_end - time_begin
print 'call %s cost %f second(s)' %... |
##################################################################################################################################
# Kruskal's algorithm:It computes the minimum spanning tree of a network.Minimum spanning tree is optimization of graph #
# and also ensure that all nodes have connection between... |
import random
number = random.randint(1,10)
name = input('Hi, Whats your name? ')
print ("Well", name, "I have a number in mind between 1 and 10, take a guess")
guess1 = int(input()) # convert input from string to integer
while guess1 != number:
if guess1 > number:
print ('your guess is too high. Try aga... |
import re
def checkio(data: str) -> bool:
small = big = digit = False
for l in data:
if l.isdigit():
digit = True
continue
if l.isupper():
big = True
continue
if l.islower():
small = True
continue
return small ... |
# Maintain the doubly linkedlist and dictionary of node
class Node:
def __init__(self, key:int, value:int):
self.key = key
self.value = value
self.prev = None
self.next = None
class LRUCache:
def __init__(self, capacity:int):
self.capacity = capacity
self.dic = ... |
def nombreMystere(y):
#On récupère chaque chiffre des unités, dizaines et centaines
c=y//100
d=(y-c*100)//10
u=(y-c*100-d*10)//1
#On teste les différentes conditions :
#On comprends vite que le chiffre des dizaines sera forcément 4 d'après la conditions 5
if (d!=4):
return Fals... |
def area(p):
return 0.5 * abs(sum(x0*y1 - x1*y0
for ((x0, y0), (x1, y1)) in segments(p)))
def segments(p):
return zip(p, p[1:] + [p[0]])
def checkio(data):
return area(data)
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main... |
def checkio(number):
n = number
d = {
0: 'zero',
1: 'one',
2: 'two',
3: 'three',
4: 'four',
5: 'five',
6: 'six',
7: 'seven',
8: 'eight',
9: 'nine',
10: 'ten',
11: 'eleven',
12: 'twelve',
13: 'thirteen... |
from fractions import gcd
def checkio(values):
'Calculate the greatest common divisor of two numbers'
a, b = values
return gcd(a, b)
if __name__ == '__main__':
assert checkio((12, 8)) == 4, "First"
assert checkio((14, 21)) == 7, "Second"
print 'All ok'
|
from fractions import Fraction
class Matrix(object):
def __init__(self, matrix):
self.matrix = matrix
self.n = len(matrix)
def replace_col(self, col, data):
for i in range(self.n):
self.matrix[i][col] = data[i]
def sub_determinant(self, i, j):
matrix = []
... |
#for迴圈
#for 變數 in 字串OR列表:
# 要重複執行的程式碼
# for letter in "小白你好":
# print(letter)
# for num in [0,1,2,3,4]:
# print(num)
# for num in range(2,10):
# print(num)
# print(pow(2,6))
# 2*2*2*2*2
def power(base_num,pow_num):
result = base_num
for index in range(pow_num-1):
result=result*base_num... |
#類別class 物件object
class phone:
def __init__ (self,os,number,is_waterproof): #底線案兩次 變長底線
self.os = os
self.number = number
self.is_waterproof = is_waterproof
phone1 = phone ("ios",123,True)
print (phone1.os)
phone2 =phone ("android",456,False)
print (phone2.number) |
#如何使用字串、字串用法
print("hello \nMr.white")
print("hello \n \"mr.white\"")
#hello" mr. white
print("hello " + "mr.white")
phrase = "hello"
print(phrase + " mr. white")
# 函式 fuction
phrase = "HELLO MR. wHITE"
#字母變小寫 /檢查字母是否都是小寫
print(phrase.lower().islower())
#字母變大寫
print(phrase.upper())
print(phrase.islower())
#檢查字母是否大寫... |
# 2. Реализовать функцию, принимающую несколько параметров, описывающих данные пользователя: имя, фамилия,
# год рождения, город проживания, email, телефон. Функция должна принимать параметры как именованные аргументы.
# Реализовать вывод данных о пользователе одной строкой.
fields = ('Name ', 'Second name ', 'Yea... |
#!/usr/bin/python3.6
import pygame, sys
from pygame.locals import *
pygame.init() # activates Pygame, always the first command after import statements
FPS = 30 # frames per second setting
fpsClock = pygame.time.Clock()
# set up the window
DISPLAYSURF = pygame.display.set_mode((400, 300), ... |
#Get name
name = input("What is your name?\n")
#Print name
print("Hello,", name)
|
#Pedro Gallin
#9/15/17
#warmUp3.py- sees if a number is divisible by 2 or three
num = int(input('Enter a number: '))
if num%2 == 0 and num%3 == 0:
print(num,'Is divisible by 3 and 2')
elif num%2 == 0:
print(num,'Is divisible by 2')
elif num%3 == 0:
print(num,'is diviseble by 3')
else:
print(num,'Is no... |
#Pedro Gallino
#9/14/17
#fortuneTeller.py - tells a fortune
color = (input('Pick a color red or blue: '))
num = int(input('Pick a number from 1-4: '))
if color == 'red' and num == 1:
print('You will live to be 200 years old')
elif color == 'red' and num == 2:
print('You will survive a mountain lion attack')
e... |
class StdOutException(Exception):
"""
Raised when data is written to stdout
"""
def __init__(self, text, errno=1):
"""
:text: Output text
;errno: Exit status of program
"""
self.text = text
self.errno = errno
def __str__(self):
return self.t... |
print("Welcome to band name generator")
city = input("Enter the name of the city you grew up in\n")
pet = input("Enter the name of your first pet\n")
print("Your band name can be " + city +" "+ pet)
|
def nextCollatzNumber(n):
if n % 2 == 0:
return n / 2
else:
return 3*n + 1
def CollatzChain(n):
start = n
count = 1
if n == 1:
return count
while nextCollatzNumber(start) != 1:
count += 1
start = nextCollatzNumber(start)
return count + 1
def lookFo... |
from math import sqrt
def divisors(m):
count = 0
for i in range(1, int(sqrt(m)) + 1):
if m % i == 0:
if not (m / i == i):
count += 2
else:
count += 1
return count
def consecSameDivs(m, n):
consecSameDivisors = 0
prev = divisors(m) ... |
'''
[3,5] [3,6]
[4,5] [5,6][6,7]
[4,6][6,8]
3: [4,5][5,6][6,7]
'''
def answer(meetings):
sort = sorted(meetings)
uniq = []
for x in sort:
if x not in uniq:
uniq.append(x)
print uniq
meetings = []
for x in range(0, len(uniq) - 1):
print x
if (uniq[x][1] - 1 in range(uniq[x + 1][0], uniq[x + 1][... |
def answer(x, y, z):
sort = sorted([x, y, z])
time = str(sort[0]) + "/" + str(sort[1]) + "/" + str(sort[2])
a = sort[0]
b = sort[1]
c = sort[2]
# February
if (a == 2) and (b > 28):
return "Ambiguous"
if (a == 2) and (c < 29) and (c != b):
return "Ambiguous"
# Months with 30 days
if (a in [4, 6, 9, 11... |
# Basic script to simulate problem #9 for miniproject 1 in ISYE6644 - Simulation class
# Written by: Spencer Vore & Jessica Warr
import random
import sys
import math
import matplotlib.pyplot as plt
import statistics
import argparse
# Function to take the next turn
def take_turn(player, verbose=False, print_end_state... |
# Copyright (c) 2021 www.SyedAdnan.com
# Title: Function to calculate max profit from stock prices
# Purpose: Coding exercies for Latitude
# Author: Syed Adnan
# Date: 26 Sep, 2021
def get_max_profit(prices):
"""Accept stock prices and return max profit after evaluation
Parameters
--------... |
"""
You are given an array of integers representing coordinates of obstacles situated on a straight line.
Assume that you are jumping from the point with coordinate 0 to the right. You are allowed only to make jumps of the same length represented by some integer.
Find the minimal length of the jump enough to avoid al... |
"""
Two arrays are called similar if one can be obtained from another by swapping at most one pair of elements in one of the arrays.
Given two arrays a and b, check whether they are similar.
Example
For a = [1, 2, 3] and b = [1, 2, 3], the output should be
areSimilar(a, b) = true.
The arrays are equal, ... |
"""
Given a year, return the century it is in. The first century spans from the year 1 up to and including
the year 100, the second - from the year 101 up to and including the year 200, etc.
Example
For year = 1905, the output should be
centuryFromYear(year) = 20;
For year = 1700, the output should be
... |
def newfunct(start, end, step):
while start <= end:
if start % 3 == 0 and start % 5 == 0:
print("FizzBuzz")
elif start % 3 == 0:
print("Buzz")
elif start % 5 == 0:
print("Fizz")
else:
print(start)
start = start + step
|
print('Введите значения переменных типа int: ')
a = int(input())
b = int(input())
print('Вы ввели числа :',a,'и',b)
summ = a + b
minus = a - b
mltplctn = a * b
share = a / b
print('Сумма веденных числе равна :',summ )
print('Разность веденных числе равна :',minus )
print('Произведение веденных числе равно :',mltplctn... |
__author__ = 'steve1281'
import collections
MyDQ = collections.deque("abcdef",10)
print("Starting state:")
for i in MyDQ:
print(i, end=' ')
print()
print('Appending and extending right')
MyDQ.append('h')
MyDQ.extend('ij')
for i in MyDQ:
print(i, end=' ')
print()
print('MyDQ contains {0} items.'.format(len(MyD... |
__author__ = 'steve1281'
meal = ""
print("1. Eggs")
print("2. Pancakes")
print("3. Waffles")
print("4. Oatmeal")
mainChoice = int(input("Choose a breakfast item: "))
if (mainChoice == 2) :
meal = "Pancakes"
elif (mainChoice == 3):
meal = "Waffles"
if (mainChoice == 1):
print("1. Wheat Toast")
print... |
__author__ = 'steve1281'
Colors = ["Red","Orange","Yellow","Green","Blue",]
ColorSelect = ""
while str.upper(ColorSelect) != "QUIT":
ColorSelect = input("Please enter a color name: ")
if (Colors.count(ColorSelect) >= 1):
print("The color exists in the list!")
elif (str.upper(ColorSelect) != "QUIT"... |
# list = ["bike","bike","cricket","travel bag",2,"drawers","bed","suitcase"]
#
# print (list)
#
# # length of a list
# print(len(list))
# #get the first item in a list
# print (list[0])
# # add an item in a list
# list.append("bed")
# print (list)
# #remove an item from a list
# list.remove('bed')
# print("after remove... |
# Data types
# boolean
# integer float
# String
# List
# Dictionary
# Tuple
a = 6
b = "5"
print (type(b))
# type casting is changing one variable to another
b = int(b)
a = str(a)
print (type(b))
print (type(a)) |
#!/usr/bin/env python
"""
基于双端链表 实现的 双端队列 时间复杂度 增删 O(1),查询 O(n);空间复杂度 O(n)
"""
class deq():
def __init__(self, value):
self.va = value
self.prior = self
self.next = self
class MyCircularDeque(object):
def __init__(self, k):
"""
Initialize your data structure here. Set t... |
'''
2
3 问题简述:一只小猴子吃桃子的问题。
4 话说,一只小猴子第一天摘下若干个桃子,并吃了一半。
5 感觉到吃的还不瘾,于是又多吃了一个;
6 第二天早上,又将剩下的桃子吃掉一半,又多吃了一个。
7 以后每天早上,都吃了前一天剩下的一半零一个。
8 python问题:
9 请问,到了第10天早上想再吃时,却发现只剩下一个桃子了。
10 求第一天共摘了多少?
11
12 # 逆向思维
13 s2 = 1
14 for day in range(9,0,-1):
15 s1 = (s2 + 1)*2
16 s2 = s1
17 print(s1)
18 ''... |
def setInterval(s,f,b):
n = len(s)
A = []
A.append(b[0])
k = 1
for i in range(2,n):
if s[i] >= f[k] :
A.append(b[i])
k = i
#print A
print "Enter Number of elements"
n = input()
MAX = 100000000
from random import randint
s = []
f = []
k = []
for i in range(0,n):
x,y = [randint(0,MAX-1),randint(0,... |
def multiply(a,b):
if(a<10 or b<10):
return (a*b)
x=str(a)
y=str(b)
lenA=len(x)
lenB=len(y)
xUHalf = int(x[0:(lenA/2)])
yUHalf = int(y[0:(lenB/2)])
xLHalf = int(x[(lenA/2):])
yLHalf = int(y[(lenB/2):])
p0=multiply(xUHalf,yUHalf)
p1=multiply(xLHalf,yLHalf)
p2=mult... |
S = input()
count = 0
longest = 0
for l in S:
if l in ['A', 'C', 'G', 'T']:
count += 1
else:
if count > longest:
longest = count
count = 0
print(longest)
|
from math import sqrt, floor
def is_prime(n):
if n < 2: return False
if n == 2: return True
if n % 2 == 0: return False
for i in range(3, floor(sqrt(n))+1, 2):
if n % i == 0: return False
return True
val = (lambda x: x if x % 2 != 0 or x == 2 else x + 1)(int(input()))
for i in r... |
import math
minutes = []
for _ in range(5):
minutes.append(int(input()))
minutes.sort(reverse = True, key = lambda x: x % 10 if x % 10 != 0 else 10)
x = 0
for minute in minutes:
x = math.ceil(x / 10) * 10
x += minute
print(x)
|
heights = []
for i in range(10): heights.append(int(input()))
heights.sort(reverse=True)
for i in range(3): print(heights[i]) |
i = input()
print("yes" if len(set(i)) == len(i) else "no")
|
s = input()
p = int(s[:2])
a = int(s[2:])
if 0 < p < 13 and 0 < a < 13:
print("AMBIGUOUS")
elif 0 < p < 13 and 0 <= a < 100:
print("MMYY")
elif 0 <= p < 100 and 0 < a < 13:
print("YYMM")
else:
print("NA") |
from math import sqrt, floor
n = int(input())
for i in range(floor(sqrt(n)), 0, -1):
if n % i == 0:
j = n // i
print(i+j-2)
exit()
|
from math import atan, degrees
a,b,x = map(int,input().split())
o = 2 * x / (a*a) - b
if o < 0:
h = 2 * (x / a) / b
print(degrees(atan(b/h)))
else:
print(degrees(atan((b-o)/a)))
|
from Database import Database
import re
class UserInterface:
def __init__(self):
return None
def printoutinfo(self, **kwargs): # Used Kwargs here to display dictionary infos
for i in kwargs.items():
print(i)
def InteractiveMenu(self):
B = Database()
B.ReadCarb... |
n = abs(int(input("Введите целое положительное число, например 10, 20, 30")))
max = n % 10
while n >= 1:
n = n // 10
if n % 10 > max:
max = n % 10
if n >= 9:
continue
else:
print("Максимальная цифра в числе", max)
break |
import os
# Functions in this file converts the dataset which is in text csv format into
# a list of Python dictionaries.
DATADIR = ""
DATAFILE = "TrainingData.txt"
def parse_file(datafile):
'''
This function converts the dataset(comprising of information regarding
around 2000 films) in csv form... |
import math
operator = "+-*/"
def add(s1, s2):
result = ""
if len(s1) > len(s2):
s1,s2 = s2,s1
diff = len(s2) - len(s1)
carry = 0
for i in range(len(s1) - 1, -1, -1):
temp = int(s1[i]) + int(s2[i + diff]) + carry
result += str(temp % 10)
carry = temp // ... |
from matplotlib import pyplot
from PlotInfo import PlotInfo
from Marker import Marker
from LabelProperties import LabelProperties
class Label(PlotInfo):
"""
Labels a point on the plot with text and/or arrows
"""
def __init__(self, x, y, text=None, bbox=None):
PlotInfo.__init__(self, "label")
... |
import pylab
from matplotlib import pyplot
import os
from boomslang import PlotLayout
from Utils import getGoldenRatioDimensions, _check_min_matplotlib_version
class WeightedPlotLayout(PlotLayout):
"""
A more sophisticated version of :class:`boomslang.PlotLayout.PlotLayout`
that allows some plots to be wi... |
class BoundedFloat(object):
"""
BoundedFloats behave like floats, but are required to be within
`minimum` (inclusive) and `maximum` (exclusive)
"""
def __init__(self, name, minimum, maximum, default=None):
self.name = name
self.min = float(minimum)
self.max = float(maximum)
... |
# Python3 code to demonstrate working of
# Group and count similar records
# using Counter() + loop + set()
from collections import Counter
# initialize list
test_list = ['gfg','is', 'best', 'gfg', 'is', 'for', 'geeks']
# printing original list
print("The original list : " + str(test_list))
# Group and count s... |
def print_as_a_string(age=22, name='Dash'):
print(name + ' ' + str(age))
print_as_a_string()
def number_of_decades_lived(age=32):
print('Number of Decades Lived', age / 10)
number_of_decades_lived(int(input('Enter Your Age: ')))
|
import re
repeat = 30
pattern = "a?" * repeat + "a" * repeat
string = "a" * 2 * repeat
# string = "a" * repeat
print(f'"{pattern}" "{string}"')
ret = re.match(pattern, string)
print(ret[0])
|
#实现输入十个数,求和
'''
b = 0
sum = 0
while b<10:
a = int(input("请输入数字:"))
sum = a+sum
b+=1
print("数字之和为:",sum)
#从键盘依次输入10个数,最后打印最大的数、10个数的和、和平均数。
b = 0
sum = 0
big = 0
while b<10:
a = int(input("请输入数字:"))
sum = a+sum
if a>big:
big = a
b+=1
pingjun=sum/big
print("... |
userinput = input ("Let's party! How long until the party? (Give me a number.) ")
usernum = int(userinput, 10)
if (usernum < 1):
print ("PARTY NOW!!!")
else:
for i in range (usernum, 0, - 1):
print(i)
if (i == 1):
print("PARTY TIME!")
|
"""
1. Given a string, find the longest substring
which is palindrome. For example, if the given
string is "ababad", the output should be "ababa".
"""
"""First thing is to anaylze the problem.
Since it's a palindrome, we know if its backwards
it will be the same forward. So we reverse the string
with the [start:stop:... |
import binarytree
from binarytree import Node, build
#Creates a mirror of the tree
def mirror():
#Pass in any values to create a tree
values = [7, 3, 2, 6, 9, 1, 5, 8]
if len(values)==1:
print(values)
elif len(values)==0:
print("None")
else:
tree1=build(values)
for... |
words = set()
with open('words.txt') as file:
for line in file:
words.add(line.strip())
sentence = input('Enter a sentence and I will spell check every word => ')
set_words = set(sentence.split(' '))
print('Misspelled words: ' + ', '.join(set_words.difference(words)))
|
# -*- coding: utf-8 -*-
"""
Created on Wed May 15 04:30:17 2019
@author: 140524
"""
# factorial program using recursive program
def factorial(num):
if num==0:
return 1
else:
return num*factorial(num-1)
n=int(input("enter your number: "))
factorial(n)
# examples from ed... |
# coding: utf-8
# # Functions
####[5]:
import os, sys, json
# Now we are good to get started with functions
####[1]:
def process(file_path):
if os.path.exists(file_path):
rp = open(file_path, 'r')
for line in rp:
print(line)
rp.close()
####[8]:
def add(n1, n2):
... |
class Solution:
def solve(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
if board:
m, n = len(board), len(board[0])
def check(board, i, j):
"""
Checks for 'O' that are conn... |
"Write a function for what you can buy in Splendor board game based on the cost of the card and how many tokens you have"
def can_buy(cost_of_card, tokens_of_player):
'Method 1'
print(tokens_of_player['blue'])
print(cost_of_card['blue'])
blue_passes = tokens_of_player['blue'] >= cost_of_card['blue']
... |
'''Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.'''
'''Buy and Sell Stock
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one ... |
"""Roman numerals consist of seven different symbols:
I, V, X, L, C, D and M, with the following values
for each symbol:
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
The roman numerals are written next to each other and are added, if they are equal or greater in value reading from left to right, to get ... |
<<<<<<< HEAD
def arrayStringsAreEqual(word1, word2):
"Given two string arrays word1 and word2, return true if the two arrays represent the same string, and false otherwise. A string is represented by an array if the array elements concatenated in order forms the string."
# concatenate all strings for word1... |
def nums(num):
prev = 0
for i in range(num):
sum=prev+i
print(sum)
prev = i
num = int(input("Enter number: "))
nums(num)
|
# coding: utf-8
# # Python的日期和时间处理
# ## datetime模块
# In[1]:
from datetime import datetime
# In[2]:
now = datetime.now()
print(now)
# In[3]:
print('年: {}, 月: {}, 日: {}'.format(now.year, now.month, now.day))
# In[4]:
diff = datetime(2017, 3, 4, 17) - datetime(2017, 2, 18, 15)
print(type(diff))
print(di... |
# coding: utf-8
# # 第3讲 Python语言基础
# ## 3.1 Python数据类型
# ### 3.1.1 字符串
# 在Python中用引号引起来的字符集称之为字符串,比如:'hello'、"my Python"、"2+3"等都是字符串
# Python中字符串中使用的引号可以是单引号、双引号跟三引号
# In[ ]:
print ('hello world!')
# In[ ]:
c = 'It is a "dog"!'
print (c)
# In[ ]:
c1= "It's a dog!"
print (c1)
# In[ ]:
c2 = """hello
world... |
class LinkedList :
class Node :
__slots__ = 'element' , 'next'
def __init__(self, element, next):
self.element = element
self.next = next
def __init__(self):
self.head = None
self.tail = None
self.size = 0
def __len__(self):
return se... |
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 2 10:16:47 2019
@author: roush
"""
#
# write up_heapify, an algorithm that checks if
# node i and its parent satisfy the heap
# property, swapping and recursing if they don't
#
# L should be a heap when up_heapify is done
#
def up_heapify(L, i):
# if node is the roo... |
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 27 17:47:44 2019
@author: roush
Sort a list by using the comparison model
BigO (or BigTheta) == n*log(n)??
"""
import random
testlist = [4,1,55,1,311,556,2,33,44,109,592958,5293,50]
def sort_list(a_list):
for fillslot in range(len(a_list)): # iterate through posit... |
'''
37. Write a Python program to display your details like name, age, address in three different lines.
'''
name = input("Please enter your name : ")
age = int(input("Please enter your age : "))
adress = input("Please enter your adress : ")
print(f"{name}\n{age}\n{adress}") |
'''
6. Write a Python program which accepts a sequence of comma-separated numbers
from user and generate a list and a tuple with those numbers.
'''
import re
inputStr = input("Please enter sequence of comma-separated numbers : ").split(',')
myList = list(inputStr)
myTuple = tuple(inputStr)
print(myList)
print(myTup... |
'''
27. Write a Python program to concatenate all elements in a list into a string and return it.
'''
def function(list):
new_str = ""
for item in list:
new_str += str(item)
return new_str
my_list = [2,5,1,2131,435,6]
my_list2 = ["hello","world","my","name","is","bat"]
print(function(my_list))
pr... |
import cv2 as cv
import numpy as np
import torch
def image_normalization(img, img_min=0, img_max=255):
"""This is a typical image normalization function
where the minimum and maximum of the image is needed
source: https://en.wikipedia.org/wiki/Normalization_(image_processing)
:param img: an image coul... |
#coding=utf-8
name=input('为什么叫我贝塔?')
if name=='巧碧螺':
print('yes its me!')
else:
print('飞机刷没了!!')
|
#coding=utf-8
#字符串
for i in 'abcd':
print(i)
#列表
l1=[1,2,'heygor','ladeng']
for a in l1:
print(a)
print('*'*20)
#函数
#内置函数range()
#range(10) 0-9
#range(1,10) 1-9
for i in range(10):
print(i)
print('*'*20)
for i in range(1,10):
print(i)
print('*'*20)
for i in range(-5,... |
#!/usr/bin/env python
# encoding: utf-8
"""Transform a YAML file into a LaTeX Beamer presentation.
Usage: bin/yml2tex input.yml > output.tex
"""
from pygments import highlight
from pygments.lexers import get_lexer_for_filename
from pygments.formatters import LatexFormatter
import yaml
def separate(doc):
"""
... |
"""
Write a function that will receive a 2D list of integers. The function should return the count of how many rows of the list have even sums
and the count of how many rows have odd sums.
For example if the even count was 2, and odd count was 4 your function should return them in a list like this: [2, 4].
"""
# Fun... |
"""
Write a function that accepts a list of integers and returns a new list which is the sorted version (ascending order) of the original list
(Original list should not be modified). You may NOT use the built in sort() or sorted() functions. Notice that the original list should not
be modified
"""
# Function Dec.
def ... |
"""
Write a function that accepts two lists A and B and returns a new list which contains all the elements of list A followed by elements of
list B. Notice that the behaviour of this function is different from list.extend() method because the list.extend() method extends the
list in place, but here you are asked to c... |
"""
Write a function that accepts two input lists and returns a new list which contains only the unique elements from both lists.
"""
# Function Dec.
def get_unique(L1, L2):
L1.append(L2)
new_list = []
# Accessing the List
for i in L1:
# Logic
if i not in new_list:
new_list.... |
"""
Write a function named find_longest_word that receives a string as parameter and returns the longest word in the string. Assume that the
input to this function is a string of words consisting of alphabetic characters that are separated by space(s). In case of a tie between
some words return the last one that occu... |
"""
Write a function that accepts an alphabetic character and returns the number associated with it from the ASCII table.
"""
#Function Dec.
def get_asc(n):
# Using
return ord(n)
|
"""
Write a function that accepts two positive integers a and b (a is smaller than b)and returns a list that contains all the odd numbers
between a and b (including a and including b if applicable) in descending order.
"""
# Function Decl.
def odd_num(a, b):
num = b
# An empty list
l = []
# Logicc and... |
"""
Write a program using while loops that asks the user for a positive integer 'n' and prints a triangle using numbers from 1 to 'n'.
For example if the user enters 6 then the output should be like this :
(There should be no spaces between the numbers)
1
22
333
4444
55555
666666
"""
# Getting User Input
n = int(in... |
"""
Write a function that accepts a 2 Dimensional list of integers and returns the average.
Remember that average = (sum_of_all_items) / (total_number_of_items).
"""
# Function Dec.
def avg_list(L):
total_sum = 0
# Accessing every row
for row in range(len(L)):
# Accessing every column
for... |
"""
Write a function that accepts a positive integer n and returns the ascii character associated with it.
"""
#Function Dec.
def get_asc(n):
return chr(n)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.