text stringlengths 37 1.41M |
|---|
"""
Code borrowed from:
https://stackoverflow.com/questions/48878053/tensorflow-gradient-with-respect-to-matrix
"""
import numpy as np
import tensorflow as tf
import tensorflow.contrib.eager as tfe
def _map(f, x, dtype=None, parallel_iterations=10):
"""
Apply f to each of the elements in x using the specified... |
def shapeArea(n):
area = 0
if n == 1 :
return 1
for i in range(1,(2*n-1),2):
area += 2*i
print(area)
return(area +( 2*n -1))
|
# 自定义类
class Person(object):
# 构造方法
def __init__(self):
self.name = 'xiaowang'
self.__age = 12 # 私有属性
# 私有的类属性
__country = '中国'
# 获取私有属性()实例方法
def get_age(self):
return self.__age
# 实例方法(对象方法)修改私有属性
def set_age(self, new_age):
self.__age = new_age
... |
# 返回一个函数
def my_calc_return (x):
if x == 2:
def calc(y):
return y * y
if x == 3:
def calc(y):
return y * y * y
return calc # 使用calc()return失败:TypeError: calc() missing 1 required positional argument: 'y'
mcalc = my_calc_return(3)
print(mcalc(3))
'''
递归:函数中自己调用自己... |
# 定义师傅类-古法
class Master(object):
# 方法
def make_cake(self):
print('古法煎饼果子')
# 自定义师傅类-现代
class School(object):
# 方法
def make_cake(self):
print('现代煎饼果子')
# 自定义徒弟类
class Prentice(Master, School):
# 方法
def make_cake(self):
print('猫式煎饼果子')
# 古法
def make_old_cake... |
"""
Define a function that can receive two integral numbers in string form
and compute their sum and then print it in console.
"""
def sum(string1, string2):
total = int(string1) + int(string2)
print(total)
return total
sum('100', '20')
|
"""
Write a program that accepts a sentence and calculate the number of letters and digits.
Suppose the following input is supplied to the program:
hello world! 123
Then, the output should be:
LETTERS 10
DIGITS 3
"""
def calcNum(userInput):
numLetters = 0
numDigits = 0
for char in userInput:
if char... |
"""
Write a program to compute:
f(n)=f(n-1)+100 when n>0
and f(0)=1
with a given n input by console (n>0).
Example:
If the following n is given as input to the program:
5
Then, the output of the program should be:
500
In case of input data being supplied to the question, it should be assumed to be a console inpu... |
import re
"""
Assuming that we have some email addresses in the "username@companyname.com" format,
please write program to print the user name of a given email address.
Both user names and company names are composed of letters only.
Example:
If the following email address is given as input to the program:
john@google... |
"""
Write a program to compute 1/2+2/3+3/4+...+n/n+1 with a given n input by console (n>0).
Example:
If the following n is given as input to the program:
5
Then, the output of the program should be:
3.55
In case of input data being supplied to the question, it should be assumed to be a console input.
Hints:
Use fl... |
"""
Please write assert statements to verify that every number in the list [2,4,6,8] is even.
Hints:
Use "assert expression" to make assertion.
"""
list = [i for i in range(2, 9) if i % 2 == 0]
for num in list:
assert num % 2 == 0
|
"""
Write a program which can map() and filter() to make a list whose elements are
square of even number in [1,2,3,4,5,6,7,8,9,10].
"""
def squareEvens(userInput):
evens = list(filter(lambda x : x % 2 == 0, userInput))
squares = list(map(lambda x : x * x, evens))
print(squares)
squareEvens([1,2,3,4,5,6,7,8... |
"""
Write a program to solve a classic ancient Chinese puzzle:
We count 35 heads and 94 legs among the chickens and rabbits in a farm. How many rabbits and how many chickens do we have?
Hint:
Use for loop to iterate all possible solutions.
"""
def numRabbitsChickens(heads, legs):
for i in range(heads): # i is the ... |
"""
Please write a program using generator to print the numbers
which can be divisible by 5 and 7 between 0 and n in comma separated form while n is input by console.
Example:
If the following n is given as input to the program:
100
Then, the output of the program should be:
0,35,70
Hints:
Use yield to produce the... |
classnumber=int(input("Please enter the number of classes :"))
for i in range (classnumber):
studentnumber = int(input("Please enter the number of the students:"))
while studentnumber>50:
print("Wrong")
studentnumber = int(input("Please enter a new number:"))
Name = []
Score... |
#This program is used to calculate tax
Taxableincome=int(input("Enter the Taxableincome:"))
#Get the user’s Taxable income
if(Taxableincome<0)
Print("You can not input a negative number")
#Prevent the user from inputing a negative number mistakenly
if(Taxableincome>=0)and(Taxableincome<=50000)
T... |
#输入
String1=str(input("请输入字符串1:"))
String2=str(input("请输入字符串2:"))
String3=""
#根据用户需要,进行操作
while 1:
print("比较,按1;追加,按2;拷贝,按3;结束,按0")
K=int((input()))
if K==0:
break
elif K==1:
if String1>String2:
print("String 1>String 2")
elif String1==String2:
... |
"""
Pig Latin is a game of alterations played on the English language game.
To create the Pig Latin form of an English word the initial consonant sound is transposed to the end of the word
and an ay is affixed (Ex.: "banana" would yield anana-bay). Read Wikipedia for more information on rules.
"""
import re
def pig_... |
"""
Leetcode #75
"""
from typing import List
class Solution:
# two pass
def sortColors_COUNTING_SORT(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
counter = [0, 0, 0] # one for each 0, 1, and 2
for i in nums:
... |
"""
Leetcode #1433
"""
from collections import Counter
class Solution:
def checkIfCanBreak(self, s1: str, s2: str) -> bool:
def check(d1, d2):
diff = 0
for c in "abcdefghijklmnopqrstuvwxyz":
diff += d1[c] - d2[c]
if diff < 0: # if anytime d... |
"""
Leetcode #79
"""
from typing import List
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
if not board or not word:
return False
if not board[0]:
return False
m = len(board)
n = len(board[0])
# using separate v... |
"""
Leetcode #207
"""
from collections import defaultdict
from typing import List
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
if not prerequisites:
return True
# 0: unlearned, 1: learning, 2: learned
self.course_status = ... |
"""
Leetcode # 146
"""
from typing import Dict, List
class DoublyLinkedNode:
def __init__(self, key: int, value: int) -> None:
self.key = key
self.value = value
self.prev = None
self.next = None
class LRUCache:
def __init__(self, capacity: int) -> None:
self.size... |
"""
Leetcode #60
"""
class Solution:
count = 0
perm = None
def getPermutation(self, n: int, k: int) -> str:
nums = [i for i in range(1, n+1)]
res = []
store = {}
def helper(nums, curr):
if len(curr) == len(nums):
self.count = self.count + ... |
"""
1.8 - Write an algorithm such that if in an element in MxN matrix is 0
All elements in that row become should become 0
"""
from typing import List
# assuming all element in matrix are >= 0
def algo(matrix: List[List[int]]) -> List[List[int]]:
M = len(matrix)
N = len(matrix[0])
# mark ... |
"""
Leetcode #575
"""
from typing import List
class Solution:
def distributeCandies_OPTI(self, candies: List[int]) -> int:
unique = set(candies)
# max number of candies sister can get will be atmost len(candies) / 2
if len(unique) >= len(candies) // 2:
return len(candies)... |
"""
2.1 - Write a code to remove duplicates from unsorted linked list
"""
# Definition of a ListNode
class ListNode():
def __init__(self, val):
self.val = val
self.next = None
def dedupe(head: ListNode) -> ListNode:
if not head:
return None
if not head.next:
return h... |
"""
Leetcode #1451
"""
from collections import defaultdict
class Solution:
def arrangeWords(self, text: str) -> str:
if not text:
return ""
arr = text.split()
# sorting in python is stable
# so relative index of same level keys are maintained
# keep will ... |
"""
Leetcode #1443
"""
from typing import List
from collections import defaultdict
class Solution:
def minTime(self, n: int, edges: List[List[int]], hasApple: List[bool]) -> int:
tree = defaultdict(list)
# to avoid loop as graph is not unidirected
visited = set()
for u, v i... |
"""
Leetcode #153
"""
from typing import List
class Solution:
def findMin(self, nums: List[int]) -> int:
if not nums:
return
left = 0
right = len(nums) - 1
while left < right:
mid = left + (right - left) // 2
if nums[mid] < nums[right]:
... |
"""
Leetcode #282
"""
from typing import List
class Solution:
def addOperators(self, num: str, target: int) -> List[str]:
if num == "":
return []
N = len(num)
res = []
def helper(idx, curr, value, prev_num):
if idx >= len(num):
if value... |
"""
Leetcode #63
"""
from typing import List
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
if not obstacleGrid or not obstacleGrid[0]:
return 0
if obstacleGrid[0][0] == 1:
return 0
m = len(obstacleGrid)
n = ... |
"""
Leetcode #313
"""
from typing import List
class Solution:
def nthSuperUglyNumber(self, n: int, primes: List[int]) -> int:
if not n or n == 0 or n == 1:
return n
res = [0] * n
res[0] = 1
# tracker multication for each prime
# after each iteration
... |
"""
Leetcode #1400
"""
from collections import Counter
class Solution:
def canConstruct(self, s: str, k: int) -> bool:
if len(s) < k:
return False
count = Counter(s)
odd = 0
# count odd frequencies, if odd < k then palindrome can be constructed
for i in cou... |
"""
Leetcode #1252
"""
from typing import List
class Solution:
def oddCells(self, n: int, m: int, indices: List[List[int]]) -> int:
if not indices:
return 0
rows = [0] * n
cols = [0] * m
for r, c in indices:
rows[r] += 1
cols[c] += 1
... |
"""
Leetcode #86
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def partition(self, head: ListNode, x: int) -> ListNode:
if not head:
return None
if not head.next:... |
"""
Leetcode #309
"""
from typing import List
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if not prices:
return 0
free = 0
have = cool = float('-inf')
for p in prices:
free, have, cool = max(free, cool), max(have, free - p), have + ... |
"""
Leetcode 230
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def kthSmallest(self, root: TreeNode, k: int) -> int:
if not root:
retu... |
"""
Leetcode #173
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class BSTIterator():
def __init__(self, root: TreeNode):
if node is None:
return ite... |
# build a web app for movies that allows users to
# list - add existing movies to a custom list
# - display query results to table - check
# search - query the model to return matching items - check
# add - add new Movies to the model - check
# edit - edit existing entries - check
# delete -... |
import nltk
from nltk.stem import *
from nltk import tokenize
from nltk.corpus import wordnet as wn
import re
from nltk.corpus import stopwords
import sys
stopWords = stopwords.words('english')
# user_text = str(sys.argv[1])
usertext = str(sys.argv[1])
# usertext = "I've felt really tired the last few days. I have ... |
total=0
for num in range(1,11):
total=total+num
print(total) |
def mean(value):
if type(value) == dict:
ave = sum(value.values())/len(value)
else:
ave = sum(value)/len(value)
return ave
studentscore = {"Joe": 8.9, "Fred": 9.3, "Zel": 5.6, "Matt": 7.4}
grades = [1, 2, 3, 4]
print(mean(studentscore))
print(mean(grades))
|
from queue import deque
class Node:
"""Klasa reprezentująca węzeł drzewa binarnego."""
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = left
self.right = right
def __str__(self):
return str(self.data)
def dfs(top):
"""Przeszukanie DFS... |
#Inicio
num=0
print("Este programa solicita números positivos.")
print("Cuando ya no quieras ingresar números, ingresa un número negativo")
while num>=0:
num=int(input("Dame un número: "))
#indentación de instrucciones del while
#Fin while
#Fin |
import os,os.path
def file_Count_in_Dir():
print(len([name for name in os.listdir('d:') if os.path.isfile(name)]))
def file_list():
ls=os.listdir('.')
file_count = len(ls)
print(file_count)
#This function give us the count of file in a directory
def file_only():
import pdb
pdb.set_trace(... |
def not_string(str):
if(str[:3]=="not"):return str;
else:return "not "+str
|
def love6(a, b):
if(abs(a-b) == 6 or a==6 or b == 6 or a+b==6):return True
return False
|
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#importing data
dataset = pd.read_csv("Position_Salaries.csv")
X = dataset.iloc[:,1:2].values
y = dataset.iloc[:,2].values
#Splitting the dataset
#from sklearn.cross_validation import train_test_split
#X_train, X_test, y_train, y_test = train_test... |
"""Word Finder: finds random words from a dictionary."""
import random
class WordFinder:
# read words.txt (one word per line).
# makes attribute of a list of those words.
# print out "[num-of-words-read] words read"
# create function random() that returns a random word from the list
def __init__(... |
a = int(input("Введите число: "))
b = int(input("Введите число: "))
c = a + b
print ("Сложение равно: ",c )
|
from nltk.tokenize import RegexpTokenizer
from nltk.stem.wordnet import WordNetLemmatizer
'''
Since the dataset is small, using NLTK stop words stripped it off many words that were important for this context
So I wrote a small script to get words and their frequencies in the whole document, and manually selected
inc... |
""" simple madlib """
print('Tell me a verb.')
VERB = input()
print(VERB)
print('And one more verb, please.')
NIIVERB = input()
print(NIIVERB)
print('I have a question: Who do you hate most?')
HATED = input()
print(HATED)
print('And tell me something you did in the past that you hated doing? (past tense)')
HATEVERB... |
print("!Important Message!")
print("# If you want odd no please input 1st no as Odd #")
print("# If you want even no please input 1st no as even #")
a=int(input("Enter Starting No(According to You Ending No)="))
b=int(input("Enter Ending No(Accoridng to you Starting No)="))
if a == b:
print("!Invalid! **Both th... |
n = input("Enter any character : ")
if n.isupper() :
print( n, "!Is an UPPERCASE alphabet!")
elif n.islower() :
print(n, "!Is a lowercase alphabet!.")
else :
print( n, "!Is Not an Alphabetical Character!") |
a=float(input("Enter a="))
b=float(input("Enter b="))
oper=input("Choose a math operation (+,/,%,**, -, *): ") # Choice of operator
if oper=='+':
s1=a+b # Addition
print(a,"Added with",b,"gives = ",s1)
elif oper=='/':
s2=a/b # Quotient
print(a,"Divided By",b,"gives quotient = ",s2)
elif oper==... |
a=float(input("Enter 1st no="))
b=float(input("Enter 2nd no="))
c=float(input("Enter 3rd no="))
d=float(input("Enter 4rd no="))
e=float(input("Enter 5th no="))
choice=float(input("Choose any no out of the five no entered="))
if choice==a:
sum1=a*1,a*2,a*3
print("Multiple of",a,"are",sum1,"...")
elif ch... |
words=["Aniket","Biswas","DPS","CLass","Eleven","Section","A","Science"]
def getWord():
import random
return random.choice (words)
word = getWord ()
word = list (word)
print ("You have to guess this word.\n", "- " * len (word))
answer = "_" * len (word)
answer = list (answer)
while True:
i... |
a=float(input("Enter Marks 1="))
b=float(input("Enter Marks 2="))
c=float(input("Enter Marks 3="))
d=float(input("Enter Marks 4="))
e=float(input("Enter Marks 5="))
avg=(a+b+c+d+e)/5
total=(a+b+c+d+e)
print(avg)
|
"""
>>> [factorial_reduce(n) for n in range(6)]
[1, 1, 2, 6, 24, 120]
"""
def factorial_reduce(n):
"""
>>> [factorial_reduce(n) for n in range(6)]
[1, 1, 2, 6, 24, 120]
"""
return reduce(lambda a, x: a * x, range(1, n + 1))
def factorial(n):
r = 1
for i in range(1, n + 1):
r *= i... |
import itertools
def f1(x, y, z):
return (x, z + 2, z)
def f2(x, y, z):
return (y + z * 2, y, z)
def f3(x, y, z):
return (y - 3, y, z)
def f4(x, y, z):
return (x, y, x + y)
arr_fun = [f1, f2, f3, f4]
def get_max():
max = float("-infinity")
result = []
for arr in itertools.permuta... |
def reverse1(string):
return " ".join(reversed(string.split(" ")))
def reverse2(string):
return " ".join(string.split(" ")[::-1])
def reverse3(string):
words = []
whitespaces = set(string.whitespace)
index = 0
for i in range(len(str)):
if i not in whitespaces:
index = i
... |
class ArrayMap(object):
def __init__(self):
self.d = {}
self.l = []
def append(self, item):
self.l.append(item)
self.d[self.l.index(item)] = item
def __getitem__(self, item):
return self.l[item]
def __setitem__(self, key, value):
pass
a = ArrayMap()
... |
import random
def qsort(iterable, key=lambda x: x, reverse=False):
if len(iterable) < 2:
return iterable
else:
pivot_index = random.randint(0, len(iterable) - 1)
pivot = iterable[pivot_index]
lesser = [x for x in
iterable[:pivot_index] + iterable[pivot_index +... |
class Solution:
def confusingNumber(self, n: int) -> bool:
rotation_map = {'0': '0', '1': '1', '6': '9', '8': '8', '9': '6'}
str_num = str(n)
new_num = ''
for c in str_num:
if c in rotation_map:
new_num += str(rotation_map[c])
else:
... |
class Solution:
def displayTable(self, orders: List[List[str]]) -> List[List[str]]:
MENU = []
ot = {}
for order in orders:
table = order[1]
item = order[2]
if table not in ot:
ot[table] = {}
if item not in ot[table]:
... |
class Solution:
def isPalindrome(self, s):
if s == s[::-1]:
return True
return False
def longestPalindrome(self, s: str) -> str:
for i in range(len(s)+1):
for j in range(i+1):
substr = s[j:len(s)-i+j]
if self.isPa... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Functions related to kernel density estimation.
Created on Tue Nov 10 18:26:34 2020
@author: jeremylhour
"""
import numpy as np
def epanechnikov_kernel(x):
"""
epanechnikov_kernel:
Epanechnikov kernel function,
as suggested in Athey and Imb... |
x = int(input())
n = int(input())
soma = 1
cont = 0
while (soma*x)<n:
soma = soma + 1
print("O numero",x,"tem",soma-1,"multiplos menores que","{:.0f}.".format(n))
|
i = int(input())
if i<16:
print("nao eleitor")
elif i>=18 and i<=65:
print("eleitor obrigatorio")
else:
print("eleitor facultativo")
|
n1 = int(input())
n2 = int(input())
if n1>n2:
print(n1)
elif n2>n1:
print(n2)
else:
print(n1)
|
# Linguagem de Programação II
# AC02 ADS-EaD - Classes e Herança
# ------------------ #
# Criando uma classe #
# ------------------ #
# Crie a classe Mamifero seguindo o exemplo da classe Reptil
# Para esta AC não utilizem o @property ainda
class Reptil:
"""
Classe mãe - não deve ser editada
Observem ... |
question = input("Give me a word in spanish")
if question == "cat":
print("Gato")
if question === "dog":
print("perro")
if question === "horse":
print("caballo")
else:
print("No entiendo")
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/7/4 15:52
# @Author : wenlei
'''
判断一棵二叉树是否是搜索二叉树
'''
class Node():
def __init__(self, x):
self.value = x
self.left = None
self.right = None
class Stack():
def __init__(self):
self.arr = []
def push(self, num... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/7/4 14:11
# @Author : wenlei
'''
判断一棵二叉树是否是平衡二叉树
'''
class Node():
def __init__(self, x):
self.value = x
self.left = None
self.right = None
# 解法1
class ReturnData():
def __init__(self, isB, h):
self.isB = isB
... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2020/8/24 17:32
# @Author : wenlei
# 一个数组,求任一元素减去该元素右边任一元素的差值的最大值。
# 暴力解法时间复杂度是o(n^2),下面的解法可以达到O(N)
def maxDifference(nums):
res = float('-inf')
ma = nums[0]
for num in nums[1:]:
res = max(res, ma - num)
ma = max(ma, num)
return ... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2020/6/24 20:26
# @Author : wenlei
'''
用一个数组实现固定大小的队列和栈
'''
class ArrayStack():
def __init__(self, init_size):
if init_size < 0:
raise Exception('stack size less than 0')
self.arr = [None] * init_size
self.index = 0 # 新数应... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/7/27 9:49
# @Author : wenlei
'''
二分查找:
1. 一个数 返回所在下标
2. 数的左右边界 [1,2,3,3,3,4] 查找3返回[2, 4]
参考:https://www.cnblogs.com/kyoner/p/11080078.html
'''
def binarySearch1(nums, target):
'查找一个数'
l, r = 0, len(nums) - 1
while l <= r: # [l, r]
m ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/7/10 10:24
# @Author : wenlei
'''
母牛问题
'''
def countCow1(n):
if n < 4:
return n
return countCow1(n - 1) + countCow1(n - 3)
def countCow2(n):
if n < 4:
return n
res = 3
resPre = 2
resPrePre = 1
for i in range(... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2020/6/29 20:13
# @Author : wenlei
'''
打印两个有序链表的公共部分
'''
class Node():
def __init__(self, x):
self.val = x
self.next = None
def printCommonPart(head1, head2):
while head1 and head2:
if head1.val < head2.val:
head1 = ... |
def reversort(n, arr):
cost = 0
for i in range(n - 1):
m = min(arr[i:])
j = arr.index(m) + 1
arr[i: j] = reversed(arr[i: j])
cost += j - i
return cost
if __name__ == '__main__':
test_cases = int(input())
for test_case in range(1, test_cases + 1):
size = int(... |
class Bicycle(object):
def __init__(self, model, weight, cost):
self.model = model
self.weight = weight
self.cost = cost
class Shop(object):
def __init__(self, name, inventory, margin=20%):
self.name = model
self.inventory = inventory
self.margin = margin
self.profit = 0
def func... |
'''Program to print the discount if the CP is greater than 1000
Developer:Aakash
Date:21.02.2020
--------------------------------'''
a=int(input("Enter your CP="))
if(a>1000):
print("You are elegible for Discount!")
b=(10/100)*a
print("Your discount amount is=Rs",b)
else:
print("Oops! You are not elegib... |
'''Program to print the grading of student
Developer:Aakash
Date:21.02.2020
--------------------------------'''
a=int(input("Enter your Percentage="))
if(a<25):
print("You are getting the grade 'F'")
elif(a<45 or a>25):
print("You are getting the grade 'E'")
elif(a<50 or a>45):
print("You are getting the gr... |
'''Program to print the sum of 1-2+3+4-5+6-7.............n
Developer:Aakash
Date:03.03.2020
--------------------------------'''
a=int(input("Enter the number for which you want sum up="))
i=1;j=2
su=0;sm=0;
while(i<=a):
su=su+i
i=i+2
print("The odd sum is=",su)
while(j<=a):
sm=sm+j
j=j+2
print("The even... |
'''Program to print the leap year
Developer:Aakash
Date:24.02.2020
--------------------------------'''
year=int(input("Enter the year="))
if((year%400 == 0)or((year%4 == 0)and(year%100!= 0))):
print("You are entering a leap year")
else:
print("Oops! You are not entering a leap year!")
|
t=int(input())
while t>0:
n=int(input())
count=0
while n>0:
if n%2==1:
count+=1
n=int(n/2)
if count==1:
print("YES")
else:
print("NO")
t-=1
|
def checkTheProductOfNumbers(integers):
total = 1
length = len(integers)
digits = integers[:]
while length > 0:
total *= digits[length - 1]
length -= 1
return total
print(checkTheProductOfNumbers([4, 5, 5, 6, 7]))
|
import random
#sekwencja slow do wyboru
WORDS = ("python", "anagram", "latwy", "skomplikowany", "odpowiedz", "ksylofon")
word = random.choice(WORDS)
correct = word
anagram = ""
while word:
position = random.randrange(len(word))
anagram += word[position]
word = word[:position] + word[(position + 1):]
prin... |
#Demonstruje zmienne i metody prywatne
class Critter(object):
"""Wirtualny pupil"""
def __init__(self, name, mood):
print('Urodzil sie niey zwierzak!')
self.name = name
self.__mood = mood #Atrybut prywatny
def talk(self):
print('\nJestem', self.name)
print('W tej chw... |
class Critter(object):
"""Wirtualny pupil"""
def __init__(self, name):
print('Urodzil sie nowy zwierzak')
self.__name = name
@property
def name(self):
return self.__name
@name.setter
def name(self, new_name):
if new_name == "":
print('Pusty lancuch -... |
# 10.Calcular el área y perímetro de un rectángulo.
class Recatangulo:
def __init__(self,ancho,alto):
self.ancho=ancho
self.alto=alto
def area(self):
area=self.alto*self.ancho
return area
def perimetro(self):
perimetro=(self.alto*2)+(self.ancho*2)
... |
# Log a single temperature record from the json data, create a graph to go with it.
import requests
import logging
import json
from datetime import datetime
from matplotlib import pyplot as plt
from matplotlib.pyplot import figure
from dbconnector import DBConnector
from const import Const
from config import Config
c... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#Importing Data
election = pd.read_csv("file:///E:/excelr/Excelr Data/Assignments/Logisitc Regression/election_data.csv")
print(election)
election.head()
#removing CASENUM
election.drop(["Election-id"],axis=1)
temp = election.drop(["Elec... |
# Program Input Variabel #
print("""
|---------------------------------------------------|
| Program Input Data Mahasiswa |
| ====================================== |
|-----------------... |
kullanici = input("Aklinizda bir sayi tuttu iseniz oyunumuza baslayabiliriz,lutfen entere basiniz")
import random
pctahmin = random.randint(0,100)
print("pc tahmini =",pctahmin)
while True:
kullanici_inputu = input("sayi kucukse +,buyukse - yazin :" )
if kullanici_inputu == "-":
print("kullanici inputu... |
import time
'''
Timer class. Emulates behaviour of matlab's tic/toc
'''
start = None
def tic():
global start
start = time.time()
def toc(verbose=True):
global start
if start is None:
print "Timer is not running!"
return 0
else:
elapsed = time.time() - start
if ver... |
#!/usr/local/bin python3
# -*- coding: utf-8 -*-
def sort_lines_with_n(filepath: str, delimiter: str, col_num: int, reverse: bool) -> list:
"""
入力ファイルの指定カラムでソートする関数
Parameters
----------
filepath: str
入力ファイルパス
delimiter: str
デリミタ文字
col_num: int
指定カラム
... |
#!/usr/local/bin python3
# -*- coding: utf-8 -*-
def reverse_str(string: str) -> str:
"""
受け取った文字列を逆順にして返す
Parameter
----------
string: str
逆順にしたい文字列
Return
----------
逆順になった文字列
"""
return string[::-1]
def main():
in_str = 'stressed'
rev_... |
#!/usr/local/bin python3
# -*- coding: utf-8 -*-
def joint_alt_str(string1: str, string2: str) -> str:
"""
入力された2つの文字列を交互に結合して1つの文字列にする関数
Parameters
----------
string1, string2: str
結合したい文字列
Return
----------
join_str: str
結合後の文字列
"""
join_str ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.