blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
7f439b0c5b387c7304ea07479c43413966ba719d | Lancher/coding-challenge | /array/_merge_intervals.py | 443 | 3.515625 | 4 | # LEETCODE@ 56. Merge Intervals
#
# --END--
def merge(intervals):
if not intervals:
return []
res = []
intervals.sort(key=lambda i: i.start)
new_i = intervals[0]
for i in range(1, len(intervals)):
if intervals[i].start <= new_i.end:
new_i.end = max(intervals[i].end, new_i.end)
else:
res.append(new_i)
new_i = intervals[i]
res.append(new_i)
return res
|
dca7de2c65e53f5625ea98c467c80d2d43e59816 | sukhdevsinghsaggar/movie-trailer-website | /entertainment_center.py | 2,029 | 3.703125 | 4 | import media
import fresh_tomatoes
import urllib
import json
def get_info(movie_name):
# Get a response after opening the URL
response = urllib.urlopen("http://www.omdbapi.com/?t="+movie_name+
"&y=&plot=short&r=json")
# Data from the website in the form of JSON is recieved
output = response.read()
# Parsing Values from JSON data
wjdata = json.loads(output)
return wjdata
# get_info method takes the Movie name as the argument
# and stores the returned data in info variable
info = get_info("Batman v Superman: Dawn of Justice")
# Constructor of Movie Class takes title, description, image URL
# and YouTube Link of the trailer as argument
bat_vs_sup = media.Movie(info['Title'], info['Plot'], info['Poster'],
"https://www.youtube.com/watch?v=fis-9Zqu2Ro")
info = get_info("Ice Age: Collision Course")
tarzan = media.Movie(info['Title'], info['Plot'], info['Poster'],
"https://www.youtube.com/watch?v=Aj7ty6sViiU")
info = get_info("Captain America: Civil War")
capt_america = media.Movie(info['Title'], info['Plot'], info['Poster'],
"https://www.youtube.com/watch?v=dKrVegVI0Us")
info = get_info("Suicide Squad")
suicide = media.Movie(info['Title'], info['Plot'], info['Poster'],
"https://www.youtube.com/watch?v=CmRih_VtVA")
info = get_info("Doctor Strange")
doc_strange = media.Movie(info['Title'], info['Plot'], info['Poster'],
"https://www.youtube.com/watch?v=HSzx-zryEgM")
info = get_info("Deadpool")
deadpool = media.Movie(info['Title'], info['Plot'], info['Poster'],
"https://www.youtube.com/watch?v=gtTfd6tISfw")
# Array of Movie objects
movies = [bat_vs_sup, tarzan, capt_america, suicide, doc_strange, deadpool]
# movies array is passed to open_movies_page function to load
# the webpage with the information provided
fresh_tomatoes.open_movies_page(movies)
|
7703ba965b3553b9aea2dae8ea6c70bfb983893f | andrewblim/advent-of-code-2020 | /py/advent_of_code_2020/day06.py | 619 | 3.5625 | 4 | import sys
from functools import reduce
def parse_question_data(full_data):
return [data.split("\n") for data in full_data.split("\n\n")]
def count_all_yeses(data):
return len(set("".join(data)))
def count_all_yeses2(data):
return len(reduce(lambda x, y: set(x) & set(y), data))
if __name__ == "__main__":
with open(sys.argv[1], "r") as fp:
question_data = fp.read().strip()
print("Part 1:")
parsed_data = parse_question_data(question_data)
print(sum([count_all_yeses(x) for x in parsed_data]))
print("Part 2:")
print(sum([count_all_yeses2(x) for x in parsed_data]))
|
c3d9dcc8a15c53bb268b44454c7a710ed18d1281 | akashsatardekar/program | /fibonacci.py | 99 | 3.546875 | 4 | n,n1,n2,count=13,0,1,0;#initialization
while count<n:
print(n1);n3=n1+n2;n1=n2;n2=n3;count+=1;
|
d54bf70542831854836276811ef37b471e9e376e | sreekanthpv/mypythonworks | /exam/q3_find_sec_lar_ele.py | 229 | 3.84375 | 4 | a=[3,5,7,9,0,8,55,34,23,76,4,65,12,89,56,76,34,289,49,12,63,976]
b=[]
while a:
min=a[0]
for j in a:
if j<min:
min=j
b.append(min)
a.remove(min)
print(b)
print('second largest element is',b[-2]) |
f84dfba4be15dc47a67315deb8f76ef1bc8eff1e | MattHeard/Python-Toys | /practical/201/double_priority_queue.py | 3,043 | 4.125 | 4 | from collections import deque, namedtuple
class DoublePriorityQueue:
"""A double priority queue, which looks the same as a regular priority
queue, but uses two independent priorities instead of one. The double
priority queue can either 'pop' the entry with the highest priority for
'priority A', the entry with the highest priority for 'priority B', or the
entry that was pushed on earliest (as in a regular queue)."""
Node = namedtuple('Node', ['val', 'priorityA', 'priorityB'])
def __init__(self):
"""Initialise the double priority queue."""
self.queue = deque()
self.priorityAList = []
self.priorityBList = []
def Count(self):
"""Return the number of entries."""
return len(self.queue)
def Clear(self):
"""Remove all entries from the double priority queue."""
self.queue.clear()
self.priorityAList.clear()
self.priorityBList.clear()
def pushOntoPriorityAList(self, node):
"""Push an entry onto priority list A."""
pos = 0
isAdded = False
for curr in self.priorityAList:
if node.priorityA > curr.priorityA:
self.priorityAList.insert(pos, node)
isAdded = True
break
else:
pos += 1
if isAdded == False:
self.priorityAList.append(node)
def pushOntoPriorityBList(self, node):
"""Push an entry onto priority list B."""
isAdded = False
pos = 0
for curr in self.priorityBList:
if node.priorityB > curr.priorityB:
self.priorityBList.insert(pos, node)
isAdded = True
break
else:
pos += 1
if isAdded == False:
self.priorityBList.append(node)
def Enqueue(self, val, priorityA, priorityB):
"""Push an entry onto the double priority queue."""
node = self.Node(val, priorityA, priorityB)
self.queue.append(node)
self.pushOntoPriorityAList(node)
self.pushOntoPriorityBList(node)
def Dequeue(self):
"""Pop off the entry that was pushed on the earliest."""
if len(self.queue) > 0:
node = self.queue.popleft()
self.priorityAList.remove(node)
self.priorityBList.remove(node)
return node
else:
return None
def DequeueA(self):
"""Pop off the entry with the highest priority A."""
if len(self.queue) > 0:
node = self.priorityAList.pop(0)
self.queue.remove(node)
self.priorityBList.remove(node)
return node
else:
return None
def DequeueB(self):
"""Pop off the entry with the highest priority B."""
if len(self.queue) > 0:
node = self.priorityBList.pop(0)
self.queue.remove(node)
self.priorityAList.remove(node)
return node
else:
return None
|
e3c21733a2a64ca68588533b42b2f5f9891f981c | ochunsic/test | /new.py | 196 | 3.84375 | 4 | #for문 테스트
squares =[]
for value in range(100):
square = value**2
squares.append(square)
print(squares)
print(min(squares))
print(max(squares))
print(sum(squares))
print('haha')
|
71965f94dfd116af6db7be2fc4d6b94637995750 | astlock/Outtalent | /Leetcode/1013. Partition Array Into Three Parts With Equal Sum/solution1.py | 443 | 3.515625 | 4 | class Solution:
def canThreePartsEqualSum(self, A: List[int]) -> bool:
total = sum(A)
if total % 3 != 0: return False
target = total // 3
count = accumulate = 0
for i in range(len(A)):
accumulate += A[i]
if accumulate == target:
count += 1
accumulate = 0
if count == 2: break
return count == 2 and i < len(A) - 1
|
7587906c1b2dab1956af9aa1ab5b077a2860f32d | vinay-chowdary/python | /listsQuestion1.py | 612 | 4.375 | 4 | # Question:
# Open the file romeo.txt and read it line by line. For each line, split the line into a list of
# words using the split() method. The program should build a list of words. For each word
# on each line check to see if the word is already in the list and if not append it to the list.
# When the program completes, sort and print the resulting words in alphabetical order
fname = input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
words = line.rstrip().split()
for word in words:
if word not in lst:
lst.append(word)
fh.close()
lst.sort()
print(lst)
|
cbec2abe1c1eca81d163e0918bec317eafc3f547 | satyamgovila/Leetcode | /Replace Words.py | 362 | 3.671875 | 4 | class Solution:
def replaceWords(self, dictionary: List[str], sentence: str) -> str:
sentence = sentence.split()
for root in dictionary:
for i, word in list(enumerate(sentence)):
if word.startswith(root):
sentence[i] = root
return " ".join(c for c in sentence)
|
33d2579d4c7fe4644a99d5c6c477e4d20926e008 | Abh1shekSingh/Hactoberfest-First-PR | /Python/guess_no.py | 641 | 4.03125 | 4 | import random
number = random.randint(1, 10)
player_name = input("Hi, What's your name? ")
no_of_guess = 0
print('Okay! ' + player_name + " I'm guessing a number between 1 to 10." )
while no_of_guess < 5:
print('Take a guess')
guess = int(input())
no_of_guess += 1
if guess < number:
print('Your guess is too low. Try again!')
if guess > number:
print('Your guess is too high. Try again!')
if guess == number:
break
if guess == number:
print('You guessed the number in ' + str(no_of_guess) + ' tries!')
else:
print('You did not guess the number, The number was ' + str(no_of_guess)) |
8f53e50102fcb16cb5deb6612c586397ddc21c08 | Nzadrozna/main | /labs/03_more_datatypes/2_lists/04_07_duplicates.py | 130 | 3.703125 | 4 | '''
Write a script that removes all duplicates from a list.
w
'''
y = [2, 3, 5, 7, 3, 8, 5, 2, 8, ]
y = list(set(y))
print(y)
|
b2ae18a829f32672322253163546b1346f56d127 | MaverickMeerkat/MachineLearningPython | /ex4/TestCase.py | 537 | 3.640625 | 4 | import numpy as np
from ex4.CostGradientNN import nn_cost_function, nn_gradient
# Test case for the cost/gradient functions
# https://www.coursera.org/learn/machine-learning/discussions/weeks/5/threads/uPd5FJqnEeWWpRIGHRsuuw
il = 2
hl = 2
nl = 4
nn = np.arange(1, 19) / 10
X = np.cos([[1, 2], [3, 4], [5, 6]]) # Matlab gives slightly different results than Python
y = np.array([4, 2, 3]).reshape(-1, 1)
lambd = 4
J = nn_cost_function(il, hl, nl, X, y, lambd, nn)
grad = nn_gradient(il, hl, nl, X, y, lambd, nn)
print(J)
print(grad)
|
cef67b7aaf467d23fe5a47b5f978a6c51eac7fba | haidang2408/BaiTApBAi5 | /cau1.py | 406 | 3.984375 | 4 | import mymath
def square (n):
return n*n
def cube(n):
return n*n*n
def average(values):
nvals=len(values)
sum = 0.0
for v in values:
sum+=v
return float(sum)/nvals
values=[2,4,6,8,10]
print('square:')
for v in values:
print(mymath.square(v))
print ('cubes:')
for v in values:
print(mymath.cube(v))
print('average: ' + str(mymath.average(values)))
|
83b5d3b6626e80a404665e171a2569b448f3185c | federicomontesgarcia/EjerciciosPython | /Unidad 3/notasMayores.py | 543 | 3.859375 | 4 | #Escribir un programa que solicite ingresar 10 notas de alumnos y nos informe cuántos
#tienen notas mayores o iguales a 7 y cuántos menores.
listaNotas = []
for x in range(10):
Nota = input("ingrese una nota: ")
listaNotas.append(Nota)
print(listaNotas)
menores = 0
mayores = 0
i = 0
for i in range (len(listaNotas)):
if int(listaNotas[i]) > 6:
mayores = mayores + 1
else:
menores = menores + 1
print("las notas mayores o iguales a 7 son:",mayores)
print("las notas menores a 7 son:",menores)
|
b8696fd12d9063350f86ce61906526c67ddec4de | OCC111/p09 | /jiudian-2.py | 3,269 | 3.625 | 4 | list1=['1宫保鸡丁','2鱼香肉丝','3喜庆满堂六彩碟','4白花胶鸡煲汤','5秋油蒸深海石斑','6法式锦蔬焗扇贝']
print('☺ '*25)
print(' 欢迎来到威妥码国际大酒店')
print('本店新开张,一周内所有业务免费')
print(' 2.选择vip房间')
print(' 3.菜品详情')
print(' 4.********')
print('☺ '*25)
list2=[]
import time
def fangjian():
dic1={}
time.sleep(2)
print('由于相关规定您需要先输入本人信息方可进入系统!')
time.sleep(2)
name = input('请输入您的姓名:')
time.sleep(2)
phone = int(input('请输入您的手机号:'))
time.sleep(2)
p_card = input('请出示您的身份证:')
dic1['name']=name
dic1['phone']=phone
dic1['p_card']=p_card
list2.append(dic1)
time.sleep(2)
print('客官,您的信息添加成功!!!')
time.sleep(2)
print('您输入的信息是:',list2)
fangjian()
while True:
import random
vip=random.randint(666001,666999)
time.sleep(2)
fang = input('请您选择要进入的程序:')
if fang == '2':
time.sleep(2)
print('欢迎进入vip房间%d'% vip)
elif fang == '3':
time.sleep(4)
for i in list1:
time.sleep(2)
print('-'*30)
print(list1[0])
print(list1[1])
print(list1[2])
print(list1[3])
print(list1[4])
print(list1[5])
print('-'*30)
time.sleep(2)
pinming = input('请输入菜品编号:')
if pinming == '1':
time.sleep(3)
print('已选定-宫保鸡丁-请您稍等...')
time.sleep(5)
print('客官,您的菜来喽!请您慢用!!')
time.sleep(5)
elif pinming == '2':
time.sleep(5)
print('已选定-鱼香肉丝-请您稍等...')
time.sleep(5)
print('客官,您的菜来喽!请您慢用!!')
time.sleep(5)
elif pinming == '3':
print('已选定-喜庆满堂六彩碟-请您稍等...')
time.sleep(5)
print('客官,您的菜来喽!请您慢用!!')
time.sleep(5)
else:
time.sleep(5)
print('您输入有误,正在退出系统中...')
break
elif fang == '4':
time.sleep(3)
print('即将进入后台系统...')
time.sleep(3)
print('不要着急,已经很努力的加载啦...')
time.sleep(3)
print('正在做最最最后的处理...')
time.sleep(6)
print('亲爱的威妥玛,欢迎您进入后台系统☺')
time.sleep(3)
print(' ')
jiang=['恭喜您中奖,接下来只需要您打开手机微信转发这条消息到100个群里,账户就会有100元,并且会有威妥玛国际大酒店总经理的亲笔签名照一张']
for i in jiang:
print(i)
else :
time.sleep(3)
print('请您立刻马上退出系统,否则后果自负!!!')
break
|
b16c358c7367dc263cea3ea1d7209f34a82f516e | Naeel90/les2 | /Les7/pe7_3.py | 240 | 3.84375 | 4 | studenten = {'Ahmad': 11.0, 'Giedo': 9.0, 'Abed': 10.5, 'niek': 12.0, 'mohammad': 8.0, 'Dj': 7.0, 'Nael': 4.5, 'Sudo': 3.0}
for student in studenten:
if studenten[student] > 9:
print('{:10}{}'.format(student,studenten[student])) |
a6522b4b27f3a6d6f2867598e6c697afd33c052a | zolangi/complang-course | /pyLabs/lab9/course.py | 739 | 3.625 | 4 | #from student import Student
class Course:
def __init__(self, courseNum, name):
self._courseNum = courseNum
self._name = name
# self._students = []
def get_courseNum(self):
return self._courseNum
def get_name(self):
return self._name
# def add_student(self, studentid, name):
# self._students.append(Student(studentid, name))
# def get_students(self):
# curr = None
# print('Students Enrolled in %s:\n', self.get_name())
# for index in range(len(self._students)):
# curr = self._students[index]
# return curr + '\n'
def __str__(self):
return 'Course #' + str(self._courseNum) + ': ' + str(self._name)
|
0f9f4fdab99499be1abb556de1b565755bfbc516 | goguvova/codecademy-Learn-Python-3 | /LOOPS(Divisible by Ten).py | 394 | 4.125 | 4 | ##Create a function named divisible_by_ten() that takes a list of numbers named nums as a parameter.
##
##Return the amount of numbers in that list that are divisible by 10.
#Write your function here
def divisible_by_ten(nums):
m=0
for i in nums:
if i %10 == 0:
m+=1
return m
#Uncomment the line below when your function is done
print(divisible_by_ten([20, 25, 30, 35, 40])) |
1777834088d439da2abc616b1ca79ea72aad1664 | ajbacon/python-algorithms | /recursion/subsets_with_given_sum.py | 1,843 | 4.28125 | 4 | import unittest
def num_subsets(arr, m, sum):
if arr == []:
return 0
# Base cases
if sum == 0:
return 1 # if sum is zero we have a solution, therefore +1
if sum < 0:
return 0 # if sum goes below 0 we have gone too far, hence not a solution
if m == 0:
return 0 # reached the end of the array and implicitly the sum isn't <= 0
# return a recursive function summing count when the solution
# a) uses arr[m - 1]
# b) does not use arr[m - 1], hence removes from the count call
return num_subsets(arr, m - 1, sum) + num_subsets(arr, m - 1, sum - arr[m - 1])
# ------------------------------TESTING-------------------------------------
class MergeSort(unittest.TestCase):
def setUp(self):
pass
def test_empty_array(self):
"""it should return 0 for an empty array"""
res = num_subsets([], 0, 0)
self.assertEqual(res, 0)
def test_simple_1_element_arr(self):
"""it should return 1 when target sum is the only number in the array"""
res = num_subsets([1], 1, 1)
self.assertEqual(res, 1)
def test_4_element_arr_with_multiple_solutions(self):
"""it should return the correct answer when there are multiple solutions"""
res = num_subsets([2, 4, 6, 10], 4, 6)
self.assertEqual(res, 2)
def test_5_element_arr_with_multiple_solutions(self):
"""it should return the correct answer when there are multiple solutions"""
res = num_subsets([1, 2, 3, 6, 9], 5, 9)
self.assertEqual(res, 3)
def test_multi_element_arr_with_no_solutions(self):
"""it should return the correct answer when there are multiple solutions"""
res = num_subsets([5, 6, 7], 3, 10)
self.assertEqual(res, 0)
if __name__ == '__main__':
unittest.main()
|
036925d524f9407f11d1fc957881ef8c565d03b4 | pawwahn/python_practice | /numpy concepts/numpy1.py | 657 | 4.53125 | 5 | import numpy as np
a = np.array([1,2,3])
print("The numpy array created is {}".format(a))
print("The numpy array type is {}".format(type(a)))
print("The length of numpy array is {}".format(len(a)))
print("The rank of numpy array is {}".format(np.ndim(a)))
print("*************")
b = np.array([(1,2,3),(4,5,6,7)])
print(b)
print("The numpy array type is {}".format(type(b)))
print("The length of numpy array is {}".format(len(b)))
print("The length of b[0] is {}".format(len(b[0])))
print("The length of b[1] is {}".format(len(b[1])))
'''
reasons for using numpy even as we have lists:
1. occupies less memory
2. fast to access
3. convenient to use
''' |
1cd10e563bb4c6930c48c5607baaff910ae3495d | moontree/leetcode | /version1/1317_Convert_Integer_to_the_Sum_of_Two_No_Zero_Integers.py | 1,832 | 3.984375 | 4 | """
Given an integer n.
No-Zero integer is a positive integer which doesn't contain any 0 in its decimal representation.
Return a list of two integers [A, B] where:
A and B are No-Zero integers.
A + B = n
It's guarateed that there is at least one valid solution.
If there are many valid solutions you can return any of them.
Example 1:
Input:
n = 2
Output:
[1,1]
Explanation:
A = 1, B = 1. A + B = n and both A and B don't contain any 0 in their decimal representation.
Example 2:
Input:
n = 11
Output:
[2,9]
Example 3:
Input:
n = 10000
Output:
[1,9999]
Example 4:
Input:
n = 69
Output:
[1,68]
Example 5:
Input:
n = 1010
Output:
[11,999]
Constraints:
2 <= n <= 10^4
"""
class Solution(object):
def getNoZeroIntegers(self, n):
"""
:type n: int
:rtype: List[int]
"""
for i in range(n):
if '0' not in str(i) and '0' not in str(n - i):
return [i, n - i]
examples = [
{
"input": {
"n": 2,
},
"output": [1, 1]
}, {
"input": {
"n": 11,
},
"output": [2, 9]
}, {
"input": {
"n": 10000,
},
"output": [1, 9999]
}, {
"input": {
"n": 69,
},
"output": [1, 68]
}, {
"input": {
"n": 1010,
},
"output": [11, 999]
},
]
import time
if __name__ == '__main__':
solution = Solution()
for n in dir(solution):
if not n.startswith('__'):
func = getattr(solution, n)
print(func)
for example in examples:
print '----------'
start = time.time()
v = func(**example['input'])
end = time.time()
print v, v == example['output'], end - start
|
ca664d941da2f9a2e481653af2175a2693eb2d10 | brajesh-rit/hardcore-programmer | /practice/find_print_cir.py | 1,653 | 3.921875 | 4 | """
https://practice.geeksforgeeks.org/problems/detect-loop-in-linked-list/1
Given a linked list of N nodes. The task is to check if the linked list has a loop. Linked list can contain self loop.
Example 1:
Input:
N = 3
value[] = {1,3,4}
x = 2
Output: True
Explanation: In above test case N = 3.
The linked list with nodes N = 3 is
given. Then value of x=2 is given which
means last node is connected with xth
node of linked list. Therefore, there
exists a loop.
Successful implement
"""
class Node:
def __init__(self, val):
self.data = val
self.next = None
class LinkList:
def __init__(self):
self.head = None
def add(self,val):
newNode = Node(val)
newNode.next = self.head
self.head = newNode
def prepareLnkList(self, arr, leng, cirNode ):
lnkList = LinkList()
lnkList.add(arr[0])
tail = lnkList.head
for i in range(1,leng):
lnkList.add(arr[i])
if i == cirNode -1:
cirLink = lnkList.head
tail.next = cirLink
return lnkList
def detectLoop(self, head):
slwPnt = head
if slwPnt.next == None:
return False
fstPnt = head
while slwPnt is not None and fstPnt is not None:
slwPnt = slwPnt.next
fstPnt = fstPnt.next
if fstPnt is not None:
fstPnt = fstPnt.next
if slwPnt == fstPnt:
return True
return False
leng= 3
arr = [1,3,4,6,7,8,5,6,7,3,4,6]
cirNode = 3
lnkList = LinkList()
head = lnkList.prepareLnkList(arr,leng,cirNode)
print(lnkList.detectLoop(head.head)) |
4460048b61ecc38a93470e778e5d043a8eae4226 | alexfreed23/OleksiiHorbachevskyi-PythonCore | /Python/PythonCore/HomeWork/HomeWork_5_20200619/Task6.py | 586 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 25 19:19:00 2020
@author: oleksiy
"""
enteredText = input("Enter text: ")
isUpperCase = False
isLowerCase = False
for letter in enteredText:
if ord(letter) in range(97,123):
isLowerCase = True
if ord(letter) in range(65,91):
isUpperCase = True
if isUpperCase:
print("Text contain UPPERCASE letter")
else:
print("Text does not contain UPPERCASE letter")
if isLowerCase:
print("Text contain lowercase letter")
else:
print("Text does not contain lowercase letter")
|
5ca274e13ddf46adebeb7be74adaacfae122d3d7 | hugo655/Teste | /Hero.py | 489 | 3.59375 | 4 | '''
This is a simple class to train the concepts seen before
'''
class Hero():
'''
Simple character prototype that has attributes: name and health
'''
__counter = 0 # Helps us keep track of the ammount of heroes out there
def __init__(self,name):
self.name = name
self.health = 100
Hero.__counter += 1
def __del__(self):
type(self).__counter -= 1
@classmethod
def getCounter(cls):
return (cls.__counter)
|
c301ea87bd490604c6af7cb3ee318ddee60bb510 | clayll/zhizuobiao_python | /练习/day03/test.py | 2,697 | 3.609375 | 4 | dic = {1:"clay",2:"mike"}
# 1. (本题3分)现在有一个List[1,2,3,4,5,6,7,8,10],手动输入一个数字,分别与List中的每一个成员进行身份运算,并输出结果。
# 2.(本题2分)
# 定义一个整形变量,并打印出其变量类型,再定义一个浮点型变量并打印其变量类型,将这个整形和浮点型相乘,预测并打印其变量类型。
# 3. (本题3分)Python里面如何拷贝一个对象?(赋值,浅拷贝,深拷贝的区别)
# 4. (本题2分)存在字符串“ab2b3n5n2n67mm4n2”,编程统计字符串中字母n出现的次数
#回家作业
# dic = {
# 'name':'汪峰',
# 'age':48,
# 'wife':[{'name':'国际章','age':38}],
# 'children':{'first_girl':'小苹果', 'sencond_girl':'小一','third_girl':'顶顶'}
# }
#1.获取汪峰的名字
#2.获取这个字典{'name':'国际章','age':38}
#3.获取汪峰妻子的名字
#4.获取汪峰的第三个孩子的名字
def test1():
ls = [i+1 for i in range(10)]
inputStr = input("手动输入一个数字:")
try:
inputStr = int(inputStr)
except:
print("您输入的不是数字,请重新输入")
return
for i in ls:
print("身份运算结果:%s " % bool(i==inputStr))
def test2():
n1 = 2;
print("整形类型为:%s " % type(n1))
n2 = 1.5
print("浮点类型为:%s " % type(n2))
n3 = n1 * n2
print("整形和浮点型相乘类型为:%s" % type(n3))
def test3():
s1 = "test"
s2 = s1
s1 = "test2"
print(s1)
def test4():
inputStr = input("请输入带n的字符串:")
ls = list(inputStr)
n = ls.count('n')
print("您输入的字符串没有n" if n == 0 else "您输入的字符串中n包括%d个" % n)
def test5():
dic = {
'name':'汪峰',
'age':48,
'wife':[{'name':'国际章','age':38}],
'children':{'first_girl':'小苹果', 'sencond_girl':'小一','third_girl':'顶顶'}
}
# 1.获取汪峰的名字
print("获取汪峰的名字:%s" % dic['name'])
# 2.获取这个字典{'name':'国际章','age':38}
print("获取汪峰的名字:%s" % dic.setdefault('wife'))
# 3.获取汪峰妻子的名字
print("获取汪峰妻子的名字:%s" % dic.setdefault('wife')[0]['name'])
# 4.获取汪峰的第三个孩子的名字
print("汪峰的第三个孩子的名字:%s" % [dic.setdefault('children')[i] for i in dic.setdefault('children').keys()][2])
def test():
list1 = [2, 3, 8, 4, 9, 5, 6]
list2 = [5, 6, 10, 17, 11, 2]
ls = map(lambda x,y : x+y,[i+1 for i in range(10)],[i+2 for i in range(10)])
print(list(ls))
test()
# test4()
# map(float,input()) |
d68d0070362b165c06c64e5ea2d0c30bacf32953 | jwday/orbitSim | /orbit_decay_num_sim_v5.py | 11,123 | 3.5 | 4 | # Numerical Integration of Polar Eqns. of Motion for Orbital Motion
# =============================================================================
# Polar Equations of Motion
# =============================================================================
# r'' = r(th')^2 - mu/r^2 # Radial acceleration
# th'' = -2(r')(th')/r + a_T/r # Angular acceleration
# As a baseline, first-order method solely to test functionality, drag will be
# constant on the object of interest to observe how the orbit decays
# Define variables to integrate:
# Let:
# x[0] = r
# x[1] = r'
# x[2] = th
# x[3] = th'
#
# Therefore:
# x[0]' = x[1]
# x[1]' = x[0]*x[3]**2 - mu/(x[0]**2)
# x[2]' = x[3]
# x[3]' = -2*x[1]*x[3]/x[0] + a_T/x[0]
# =============================================================================
# Script begin
# =============================================================================
from __future__ import print_function
import numpy as np
import math
from scipy.integrate import ode
from scipy.interpolate import interp1d
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import time
import decimal
from decimal import Decimal as D
from decimal_pi import pi as dec_pi
from atm_model_exp import nasa_eam_model, msise00_model
from mpmath import *
import pandas as pd
from datetime import datetime, timedelta
# =============================================================================
# Specify constants and simulation parameters
# =============================================================================
# -- Set Integration Parameters -----------------------------------------------
# 'dopri5' is 4th-order Dormand-Prince method with error calculated to 5th order,
# identical to the MATLAB solver 'ode45'. 'dopri5' has multiple options for step
# size adjustment, tolerance, max step size, etc...
# Defaults:
# rtol=1e-6, atol=1e-12,
# nsteps=500,
# safety=0.9,
# ifactor=10.0
# 'dop853' is an 8th-order Dormand-Prince method with 5th order error and something
# something 3rd order. It's about 40% slower than dopri45 but gives better results.
# Options are identical to dopri45.
# Defaults:
# rtol=1e-6, atol=1e-12,
# nsteps=500,
# safety=0.9,
# ifactor=6.0
def orbit(h_perigee, v_perigee, C_D, A_ref, mass_sat, t_step, start_time, **kwargs):
drag_on = kwargs["drag_on"]
circular_orbit = kwargs["circular_orbit"]
error_testing = kwargs["error_testing"]
sim_time = start_time
if error_testing:
circular_orbit=False
drag_on=False
num_orbits = kwargs["num_orbits"]
else:
pass
print("")
print("")
if not error_testing:
print("Deorbiting a " + str(int(mass_sat)) + "kg cubesat of ref. area " + str(int(A_ref*10000)) + " cm^2 (" + str(int(t_step)) + " sec time step)")
else:
print("Error testing over " + str(num_orbits) + " orbits")
# =============================================================================
# Define Numerical and Integration Parameters
# =============================================================================
decimal.getcontext().prec=8
integrator = 'dopri5'
rtol=10**-3
atol=10**-6
nsteps=1000
dt = t_step # Time step (seconds)
# =============================================================================
# Define Constants
# =============================================================================
# ISS_alt = D(408)*1000 # Kilometers
r_earth = D(6378100) # Radius of Earth, m
G = D(6.67*10**-11) # Gravitational constant
mass_earth = D(5.972*10**24) # Earth mass, kg
# mu = G*mass_earth # Specific gravitational constant of Earth
mu = D(3.986*10**14)
# =============================================================================
# Calculate remaining orbit characteristics
# =============================================================================
r_perigee = r_earth + D(h_perigee) # Radius at perigee
if circular_orbit:
a = r_perigee # Semi-major axis (circular)
H = (a*mu)**D(0.5) # Angular momentum (circular)
v_perigee = H/a # Orbital velocity (circular)
else:
a = 1/(2/r_perigee - (D(v_perigee)**D(2.0))/mu) # Semi-major axis
## DO I NEED THIS STUFF??
# eccen = (v_perigee**2)/2 - mu/r_perigee # Eccentricity
# orbit_h = r_perigee*v_perigee # Specific angular momentum
# # I'm defining the apoapsis and periapsis of the ISS orbit around Earth and
# # using these two properties to determine the remaining orbit characteristics
# # init_r_a = earth_rad + init_alt # Apoapsis
# # init_r_p = init_r_a # Periapsis (for circular orbit, r_p = r_a)
# init_a = (init_r_a + init_r_p)/2 # Semi-major axis
# init_e = (init_r_a - init_r_p)/(init_r_a + init_r_p) # Eccentricity
# init_p = init_a*(1 - init_e**2) # Semi-latus rectum
# init_orbital_E = -mu/(2*init_a) # Energy
# init_orbital_H = (init_p*mu)**D(0.5) # Angular momentum
# init_orbital_vel = init_orbital_H/init_a # Orbital velocity
# init_orbital_period = 2*dec_pi()*((init_a**3)/mu)**D(0.5) # Orbital period
##
# =============================================================================
# Initial State Vector
# =============================================================================
x0 = np.array([float(r_perigee), 0, 0, float(v_perigee)/float(r_perigee)])
t0 = 0
# =============================================================================
# State Function
# =============================================================================
def func(t, x, drag):
# Returns a 1x4 array of x_dots, aka the derivates of the EOMs above
x_dot = np.zeros(4) # Pre-make the array
x_dot[0] = D(x[1]) # r'
x_dot[1] = D(x[0])*D(x[3])**2 - mu/D(x[0])**2 # r''
x_dot[2] = D(x[3]) # th'
x_dot[3] = -2*D(x[1])*D(x[3])/D(x[0]) + drag(x[0], x[3], mass_sat, sim_time)/D(x[0]) # th''
x_dots = np.array([x_dot[0], x_dot[1], x_dot[2], x_dot[3]])
return x_dots
# =============================================================================
# Drag Function
# =============================================================================
def drag(alt, ang_vel, mass_sat, sim_time):
if drag_on and not error_testing:
vel = D(alt)*(D(ang_vel) - D(7.2921159*10**-5)) # Takes into account the angular velocity of the Earth
# rho = nasa_eam_model(D(alt) - r_earth)[2] # Density is calculated by passing altitude to this function
rho = msise00_model((D(alt) - r_earth), sim_time)[2]
drag_force = D(0.5)*D(C_D)*D(A_ref)*rho*vel**2 # Drag force
a_T = -drag_force/D(mass_sat) # Tengential acceleration from F = ma
else:
a_T = 0
return D(a_T)
# =============================================================================
# Integration Routine
# =============================================================================
r = ode(func) # Make the ODE object
r.set_integrator(integrator, rtol=rtol, atol=atol, nsteps=nsteps) # Set integrator and tolerance
r.set_initial_value(x0, t0) # Set initial values from Initial State Vector
r.set_f_params(drag) # Pass the 'drag' function as a parameter into the EOMs
x = [[x0[0]], [x0[1]], [x0[2]], [x0[3]]] # Initialize state vector list for logging
t = [t0] # Initialize time vector list for logging
# This block sets up the "integration time remaining" estimator
# -----------------------------------------------------------------------------
comp_time_zero = time.time() # Store the time at the beginning of integration
comp_time = []
comp_time.append(0)
# -----------------------------------------------------------------------------
# =============================================================================
# Integrate until we crash (when altitude goes to zero)
# =============================================================================
def append_data(x, r, t):
# Append to state vector list for logging
x[0].append(float(r.y[0])) # r
x[1].append(float(r.y[1])) # r'
x[2].append(float(r.y[2])) # theta (aka true anomoly)
x[3].append(float(r.y[3])) # theta'
# Append to time vector list for logging
t.append(r.t) # time
return t, x
N = 0 # Number of full orbits
N_prev = 0
orbit = [0]
# These are only used for error testing
radius = []
true_anomoly = []
estimated_periapsis = []
while r.successful():
r.integrate(D(r.t)+D(dt))
th_home = 2*np.pi*N
sim_time += timedelta(seconds=dt)
# Log the number of full orbits made
if (float(r.y[2]) - th_home) >= 2*np.pi:
N += 1
orbit.append(N)
else:
pass
# Do something different depending on the kwarg parameters passed to the function
if drag_on and not error_testing and r.y[0] > r_earth:
t, x = append_data(x, r, t)
min_altitude = min(x[0]) - float(r_earth)
print("\rTime: {:2.1f} Min Altitude: {:2.1f}".format(r.t, min_altitude), end='')
elif not drag_on and not error_testing and N < num_orbits:
t, x = append_data(x, r, t)
print("\rTime: {:2.1f} Number of Orbits: {:d}".format(r.t, N), end='')
elif error_testing and N <= num_orbits:
t, x = append_data(x, r, t)
print("\rTime: {:2.1f} Number of Orbits: {:d}".format(r.t, N), end='')
if N != N_prev:
radius.append([float(x[0][-1]), float(x[0][-2]), float(x[0][-3]), float(x[0][-4])])
true_anomoly.append([float(x[2][-1])-2*np.pi*N, float(x[2][-2])-2*np.pi*N, float(x[2][-3])-2*np.pi*N, float(x[2][-4])-2*np.pi*N])
interpolated_orbit = interp1d(true_anomoly[-1], radius[-1], kind='cubic')
estimated_periapsis.append(interpolated_orbit(0).tolist())
N_prev = N
else:
pass
else:
break
times = np.array(t) # Converts time list to array
altitude = np.array([i-float(r_earth) for i in x[0]])
states = np.array(x) # Convert states list to array
if not error_testing:
return(times, altitude, states)
else:
plot_error(orbit, estimated_periapsis, num_orbits, r_perigee, t_step, integrator, atol, rtol)
def plot_error(orbit, estimated_periapsis, num_orbits, r_perigee, t_step, integrator, atol, rtol):
error = [0] + [float(r_perigee) - i for i in estimated_periapsis]
fig_err = plt.figure(figsize=(8,8))
plt.plot(orbit[:-1], error)
main_title = 'Variation (m) of Periapsis over ' + str(num_orbits) + ' Orbits'
subtitle1 = 'Step Size: ' + str(t_step) + ' sec. Precision: ' + str(10**-decimal.getcontext().prec)
subtitle2 = 'Integrator: ' + integrator + ' atol: ' + str(atol) + ' rtol: ' + str(rtol)
plt.title(main_title + '\n' + subtitle1 + '\n' + subtitle2)
plt.xlabel('Orbit No.')
plt.ylabel('Variation from Inital Value (m)')
plt.show()
|
c0e33de1eeaa53d20fa55e6d0a4fddd2e93c1ba8 | dlaperriere/misc_utils | /ip.py | 1,361 | 3.734375 | 4 | #!/usr/bin/env python
"""
Description
ip.py - get public IP address
Usage
python ip.py
Output
https://duckduckgo.com/?q=what+is+my+ip&ia=answer:
IP: x.x.x.x
http://checkip.dyndns.com/:
IP: x.x.x.x
Note
- works with python 2.7 and 3.6
Author
David Laperriere <dlaperriere@outlook.com>
"""
import re
import sys
import time
try:
import urllib.request as urllib2
except ImportError:
import urllib2
__version_info__ = (1, 0)
__version__ = '.'.join(map(str, __version_info__))
__author__ = "David Laperriere dlaperriere@outlook.com"
def main():
timeout = 3
urls = ["https://duckduckgo.com/?q=what+is+my+ip&ia=answer",
"https://ipinfo.io/",
"http://checkip.dyndns.com/"]
ip_regexp = re.compile(b'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}')
for url in urls:
try:
request = urllib2.Request(url)
response = urllib2.urlopen(request)
except urllib2.URLError as e:
print(url + " error : \n" + str(e.reason) + "\n")
continue
print(url + ":\n")
data = response.read()
ip = ip_regexp.search(data)
if ip:
print("IP: {}".format(ip.group().decode("utf-8")))
sys.exit(0)
else:
print("not found")
print(" ")
time.sleep(timeout)
if __name__ == "__main__":
main()
|
6419f5f19926fd181b5b8e7694a3fa3ce68d1159 | 7PH/EPFL-Machine-Learning-Project-01 | /src/gradients.py | 529 | 3.546875 | 4 | import numpy as np
from src.maths_helpers import sigmoid
def compute_logistic_gradient(y, tx, w):
"""
Compute gradient for logistic gradient descent
:param y:
:param tx:
:param w:
:return:
"""
return tx.T @ (sigmoid(tx @ w) - y)
def compute_gradient_mse(y, tx, w):
"""
this function computes the gradient with a mse lost function
:param y:
:param tx:
:param w:
:return:
"""
e = y - np.dot(tx, w)
grad = - np.dot(tx.T, e) / tx.shape[0]
return grad, e
|
f09c9a8f8a4cc29cdcd610b0ef88c8a7161487f5 | ZionDeng/LeetPythonCode | /BLBL_algorithm/4_Tree/bi_search_tree.py | 3,287 | 3.90625 | 4 | from binary_tree_new import TreeNode, Tree
def bst_insert(root, x):
'''二叉排序树的插入方法'''
node = TreeNode(x)
if root is None:
root = node
elif x < root.val:
root.left = bst_insert(root.left, x)
else:
root.right = bst_insert(root.right, x)
return root
def bst_delete(root, x):
'''二叉查找树的删除方法
root: root node
x: target value
q,p: precursor, current cursor '''
# if leaf node: father to None
# if one child: father to child
# if 2 children: find direct decent(right child the most left) or vise versa
p = root
find = False
while p and not find:
if x == p.val:
find = True
elif x < p.val:
q, p = p, p.left
else:
q, p = p, p.right
if p is None:
print(x,'Not found')
return
else:
print(x,'Node found')
# 查找主体
if p.left is None and p.right is None: # leaf node
if p == root:
root = None
elif q.left == p:
q.left = None
else:
q.right = None
elif p.left is None or p.right is None: # p has single branch
if p == root:
if p.left is None:
root = p.right
else:
root = p.left
else:
if q.left == p and p.left:
q.left = p.left
elif q.left == p and p.right:
q.left = p.right
elif q.right == p and p.left:
q.right = p.left
else:
q.right = p.right
else: # p has 2 children
t, s = p, p.left
while s.right: # 查找p的前驱,即p左子树中最大的节点
t,s = s, s.right
p.val = s.val # 赋值
if t == p: # pay attention here
p.left = s.left
else:
t.right = s.left
def bst_delete2(root, x):
'''二叉树删除方法二,by ZionDeng'''
# if x < root.val: find in left
# elif x > root.val: find in right
# else: root, find descent -> switch
# 查找主体
if x < root.val:
root.left = bst_delete2(root.left, x)
elif x > root.val:
root.right = bst_delete2(root.right, x)
else: # x is root
if root.left is None and root.right is None:
root = None
elif root.left is None:
root = root.right
elif root.right is None:
root = root.left
else: # root has 2 children:
t, s = root, root.left
while s.right: # 查找p的前驱,即p左子树中最大的节点
t,s = s, s.right
root.val = s.val # 赋值
if t == root: # pay attention here
root.left = s.left
else:
t.right = s.left
return root
return root
tree = Tree()
ls_new = [15, 5, 3, 12, 16, 20, 23, 13, 18, 10, 6, 7]
for i in ls_new:
# tree.root = tree.bst_insert(tree.root,i)
tree.root = bst_insert(tree.root, i)
tree.breadth_travel()
print(" < BST travel")
# tree.bst_delete(tree.root, 12)
tree.root = tree.bst_delete(tree.root, 12)
tree.breadth_travel()
print(" < BST travel after deleted")
|
f06fda920d80cb69af10ea4e8d53604e202652de | weibinfighting/optimization | /QA.py | 4,847 | 3.65625 | 4 | # -*-coding:utf-8-*-
import random
import math
import heapq
def readcitycoord(filename):
'''
read data from file
where saved data :param filename:
the coord of city :return:
'''
f = open(filename,'r')
a=[]
for i in list(range(N)):
coord = str.split(f.readline())
try:
a.append([int(coord[0]),int(coord[1])])
except:
a.append([float(coord[0]),float(coord[1])])
f.close()
return a
N,pop_size = 30,200
filename = 'DATA30.dat'
city_coord = readcitycoord(filename)
def distance(x,y):
#x,y=a[0],a[1];
if isinstance(x,list)and isinstance(y,list):
d = []
for i in list(range(0,len(x))):
d.append((x[i]-y[i])**2)
dis = (sum(d))**0.5
return dis
elif not(isinstance(x,list) or isinstance(y,list)):
dis = math.sqrt((x-y)^2)
return dis
else:
print('Please check type of x_1 and x_2')
exit(1)
def obf(x,coord):
if x == None or coord == None:
print('The parament is None!');
exit(1);
D = [];
for i in list(range(len(x)-1)):
D.append(distance(coord[x[i]],coord[x[i+1]]));
D = sum(D)
return D
def initnum(N):
'''
product N random numbers from 0 to N
N paraments:param N:
N random number:return:
'''
order_data=[];
for i in list(range(N)):
order_data.append(random.random());
sort_data = sorted(order_data)
sorted_data = []
for i in list(range(N)):
sorted_data.append(order_data.index(sort_data[i]))
return sorted_data
def Xchange(n_cross):
'''
The X numbers do cross;
the number of crossing : param n_cross:
which order of solution is crossed : return:
'''
X_cross = random.sample(range(N),n_cross)
return X_cross
def cross(x_cross,y_cross,qc):
l_x,l_y = len(x_cross),len(y_cross)
if l_x!=l_y:
print('two parm lengh is not same!\n')
exit(1);
l = len(qc)
class zx:
value = [];
index = [];
for i in qc:
zx.value.append(x_cross[i])
for x_v in zx.value:
zx.index.append(y_cross.index(x_v))
z_x = []
z_xs = sorted(zx.index)
m = 0
for i in list(range(N)):
change = 0
for j in qc:
if i==j:
change = 1;
else:
continue
if change==1:
z_x.append(zx.value[zx.index.index(z_xs[m])]);
m = m+1;
else:
z_x.append(x_cross[i])
class zy:
value = [];
index = [];
for i in qc:
zy.value.append(y_cross[i])
for y_v in zy.value:
zy.index.append(x_cross.index(y_v))
z_y = []
z_ys = sorted(zy.index)
m = 0
for i in list(range(N)):
change = 0
for j in qc:
if i==j:
change = 1;
else:
continue
if change==1:
z_y.append(zy.value[zy.index.index(z_ys[m])]);
m=m+1
else:
z_y.append(y_cross[i])
return z_x,z_y
def variation(X,P=0.01,qn=2):
if random.random()<=P:
n = math.floor(random.random()*N);
m = math.floor(random.random()*N);
while n==m:
m = math.floor(random.random()*N);
X[n], X[m]=X[m],X[n];
return X;
else:
return X;
def findgroup(pop_size,Acp):
next_p = random.random();
if next_p <= Acp[0]:
return 0;
for i in list(range(1,pop_size)):
if Acp[i-1]<next_p and next_p<=Acp[i]:
return i;
else:
continue;
def generation(x):
x_c = Xchange(n_cross);
new_x = []
for i in list(range(0,pop_size-2,2)):
z = cross(x[i],x[i+1],x_c)
new_x.append(variation(z[0]))
new_x.append(variation(z[1]))
Fit = [];
for i in list(range(pop_size)):
Fit.append(obf(x[i], city_coord))
new_x.append(x[Fit.index(heapq.nsmallest(2,Fit)[0])])
new_x.append(x[Fit.index(heapq.nsmallest(2,Fit)[1])])
fitvalue = [];
for i in list(range(pop_size)):
fitvalue.append(M-obf(new_x[i],city_coord))
Acp = [];
allfv = sum(fitvalue);
Acd = 0;
for i in list(range(pop_size)):
Acd = Acd+fitvalue[i]
Acp.append(Acd/allfv)
next_group = [];
for i in list(range(pop_size)):
next_group.append(findgroup(pop_size,Acp));
next_x = [];
for i in list(range(pop_size)):
next_x.append(new_x[next_group[i]]);
return next_x
x=[];
for i in list(range(pop_size)):
x.append(initnum(N));
n_cross = 5
M=2000
for i in list(range(1500)):
x = generation(x)
for j in list(range(pop_size)):
print(obf(x[j],city_coord))
ob = [];
for i in list(range(pop_size)):
ob.append(obf(x[i],city_coord))
print(min(ob))
print(x[ob.index(min(ob))]) |
2e7217eaf96ab05cd71883f3924f0f9a17dfc123 | aria-xx0/caesar-cypher | /project.py | 1,155 | 3.8125 | 4 | def decrypt(cypher, letters, amount):
decrypted_cypher = ""
for letter in cypher:
num = letters.index(letter) + 1
num -= amount
num = num % 30
sub_letter = letters[num - 1]
decrypted_cypher += sub_letter
return decrypted_cypher
def encrypt(cypher, letters, amount):
num_cypher = ""
for letter in cypher:
letter = letter.lower()
num = letters.index(letter) + 1
num += amount
num = num % 30
add_letter = letters[num - 1]
num_cypher += add_letter
return num_cypher
if __name__ == "__main__":
cypher = input("What string do you want to encrypt? ")
eord = input("Encrypt or decrypt? (e/d) ")
amount = int(input("Encrypt by how many letters? "))
letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", " ", ".", ",", ";"]
if eord == "e":
print(encrypt(cypher, letters, amount))
elif eord == "d":
for amount in range(0, 30):
print(decrypt(cypher, letters, amount + 1))
else:
print("Invalid input") |
38f9a1601963770c7573bd98ab78b98a78fbfea5 | programmingrocks/code | /Python/lists.py | 235 | 3.921875 | 4 | letters = ["b", "e", "d", "x", "v", "w", "s", "a"]
# Printing the 5th letter
print(letters[4])
# Adding a letter and printing the list
letters.append("l")
print(letters)
# Sorting and printing the list
letters.sort()
print(letters)
|
18a440a5aa895aa4187569d58a3e9a4d0a676417 | fzingithub/LearnPythonFromLiao | /3.advanced_features/2.slice.py | 815 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jan 22 09:32:49 2018
@author: FZ
"""
#slice 切片操作符
L = ['Michael','Sarah','Tracy','Bob','Jack']
print (L[0:3]) #catch 0,1,2
print (L[-3:-1] )#catch -3,-2
L1 = list(range(100))
print (L1[:10]) #catch 0,1......9
print (L1[10:20])
print (L1[:10:2])
print (L1[::5])
print (L1[:])
T = tuple(range(50))
print (T[::5]) #tuple slice still is tuple
print ('ABCDEFG'[:3]) #string slice still is string
#exercise
def trim(str):
if str[0] is ' ':
str = str[1:]
if str[-1] is ' ':
str = str[:-1]
return str
print (trim(' hello'))
print (trim('hello '))
print (trim(' hello '))
#Summary
#we have slice,and somewhere do not need loop enough.
#and python's slice is every flexible and a row code can realize what the loop
#realize |
4259082b10d5b86bbe8c41ab4228571a4ce38874 | hobosteaux/bytelynx | /ui/menu.py | 1,631 | 3.59375 | 4 | class MenuOption():
"""
Option for a menu.
.. attribute:: text
The text to display to the user.
.. attribute:: function
The function to execute.
"""
def __init__(self, text, function):
"""
:param text: Text to display.
:type text: str.
:param function: Function to execute on selection.
:type function: func()
"""
self.text = text
self.function = function
class Menu():
"""
Simple wrapper for an interactive menu.
.. attribute:: options
A list of :class:`ui.MenuOption`s.
"""
def __init__(self, options):
"""
:param options: Options for the menu.
:type options: [:class:`ui.MenuOption`]
"""
self.options = options
def display(self):
"""
A while (True) wrapper for displaying options.
Lets the user choose one.
"""
while (True):
self.print()
choice = self.get_choice()
if (choice == len(self.options)):
break
else:
self.options[choice].function()
def get_choice(self):
"""
Gets a choice from the user and checks it for validity.
"""
number = -1
while (number < 0) or (number > len(self.options)):
number = int(input('Enter your menu choice: '))
return number
def print(self):
"""
Displays the menu.
"""
for idx, item in enumerate(self.options):
print(idx, '-', item.text)
print(len(self.options), '- Exit')
|
1f05bc8696ad480361b7571aab2fd7a2ca9da9d8 | renato-droid/Python-Exercises | /Exercise_32.py | 675 | 3.859375 | 4 | from datetime import date # da biblioteca datetime importa date
n = int(input('\033[1:35mQue ano quer analisar? Coloque 0 para analisar o ano atual: ')) # qual é o ano que quer analisar
if n == 0: # se a data for igual a zero
n = date.today().year # ee irá mostrar a data atual do computador
if 0 == n % 4 and n % 100 != 0 or n % 400 == 0: # se o resto da divisão por 4 for igual a 0 e o resto da divisão por
# 100 for diferente de 0 ou o resto da divisão por 400 for igual a zero
print('\033[1:33mO ano {} é BISSEXTO'.format(n)) # o ano será bissexto
else: #senão
print('\033[1:31mO ano {} NÃO É BISSEXTO'.format(n)) # não será bissexto
|
313a107a28d9010ad53d194d0418c374258106b1 | FarcasiuRazvan/Python-Projects | /StudentsCatalog/Student Lab Assignments/Assignment 5-7/domain_assignment.py | 515 | 3.875 | 4 | '''
Created on Nov 26, 2017
@author: RAZVI
'''
class assignment:
'''
This class will define an asssignment.
'''
def __init__(self, ida, desc, deadline):
'''
Constructor
'''
self.ida=ida
self.desc=str(desc)
self.deadline=str(deadline)
def __str__(self):
'''
The assignment wil be represented in memory as for exemple : "1. Matematica 2/7/2008"
'''
return str(self.ida)+','+str(self.desc)+','+str(self.deadline)
|
743619836de94ad83dcbad97c9d9c98d220b0d5c | mangabhi/Python | /Concatenaction.py | 193 | 4.15625 | 4 | #Define a function that can accept two strings as input and concatenate them and then print it in console.
a=str(input("Enter a string: "))
b=str(input("Enter a string: "))
c=str(a+b)
print(c)
|
0ce3ba3b5a327b05d083199a8072a1c7da6a7ade | iota-cohort-dc/Daniel-Perez | /Python/funfunction.py | 440 | 3.921875 | 4 | x = 0
def oddeven():
for num in range(1, 2001):
if(num %2 != 0):
print "Number is", +num, ".This is an odd number"
if(num % 2== 0):
print "Number is", +num, ". This is a even number"
oddeven()
x = [2,4,6,8,10] #arr values
def multi(x,y):
arr= []
for item in x:
arr.append(item *y)
print arr
multi([2,4,6,8,10], 5)
def layered(arr)
new_arr= []
return new_arr
|
83d01ebbd3fb752585110689678160dbab2a2c7e | thals7/BOJ | /for문/8393.py | 74 | 3.640625 | 4 | n = int(input())
add = 0
for i in range(n+1):
add = add + i
print(add) |
477e6f04c898939f8b8b2bceffbb69933959a695 | 7Dany6/yandex-algorithms | /Algorithms 2.0/Section B/Second Homework/2(B)_D_Лавочки в атриуме.py | 532 | 3.625 | 4 | def count(length, number_of_legs, array_legs):
to_save = 0
middle = length // 2
if len(array_legs) == 1:
return array_legs[0]
for leg in range(number_of_legs):
if array_legs[leg] < middle:
to_save = leg
elif array_legs[leg] == middle and length % 2 != 0:
return array_legs[leg]
else:
return '{} {}'.format(array_legs[to_save], array_legs[leg])
L, K = map(int, input().split())
legs = list(map(int, input().split()))
print(count(L, K, legs))
|
c530316096a0ef08402859127c970cf842a07585 | s-kyum/Python | /ch03/loop/while.py | 736 | 3.71875 | 4 | #while 문 (반복)
'''
i=1
while i < 11:
print('hello~')
i += 1
'''
'''
#1부터 10까지 출력
i=1
sum=0
while i < 11:
sum += i
#print(i, end=' ') #수평으로 출력하기
print("i=",i,",sum=",sum)
i += 1
print("합계 : ",sum)
#while~if break 반복조건문
i=1
while True:
print(i)
i += 1
if i>10:
break
'''
#while~break
i=1
while True:
print("반복을 계속할까요? [y/n] : ")
answer = input()
if answer =='y' or answer =='Y':
print("반복을 계속합니다.")
i+=1
i<20
print(i)
elif answer =='n' or answer =='N':
print("반복을 중단합니다.")
break
else:
print("잘못된 입력입니다.")
|
c923e2eb5c2b60f2f3ff87380952a209650aff43 | nishad-bdg/machine-learning | /Part 2 - Regression/Section 5 - Multiple Linear Regression/prac.py | 947 | 3.671875 | 4 | # -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
dataset = pd.read_csv('Advertising.csv')
dataset = dataset.drop(['Unnamed: 0'], axis = 1)
#plt.figure(figsize = (16,8))
plt.scatter(dataset['TV'],dataset['sales'], color = 'black')
plt.xlabel("Money spent on TV ads ($)")
plt.ylabel("Sales ($)")
plt.show()
X = dataset['TV'].values.reshape(-1,1)
y = dataset['sales'].values.reshape(-1,1)
from sklearn.linear_model import LinearRegression
reg = LinearRegression()
reg.fit(X,y)
print("Linear Model is: Y = {:.5} + {:.5}X".format(reg.intercept_[0], reg.coef_[0][0]))
predictions = reg.predict(X)
plt.scatter(dataset['TV'], dataset['sales'], color = 'blue')
plt.plot(dataset['TV'], predictions, color = 'red', linewidth = 2)
plt.xlabel('Money spent on TV ads ($)')
plt.ylabel('Sales ($)')
plt.show()
import statsmodels.api as sm
X2 = sm.add_constant(X)
est = sm.OLS(y,X2)
est2 = est.fit()
|
85dc7eb96528acd0e14621532eac4f4cf23c8b78 | nsudhanva/mca-code | /Sem3/Python/iterators/reverse_iter.py | 508 | 4.0625 | 4 | # Write a class called as reverseiter that displys the list in reverse order
class ReverseIter:
def __init__(self, my_list):
self.my_list = my_list
def __iter__(self):
self.length = len(my_list)
return self
def __next__(self):
if self.length != 0:
self.length -= 1
return my_list[self.length]
else:
raise StopIteration
my_list = [1,2,3,4,5,6]
reverse_iter = ReverseIter(my_list)
for i in reverse_iter:
print(i) |
6003bfbfd44c98d71ebc76687e8770cac76934a6 | gopalgoyal2002/python | /12.py | 161 | 3.671875 | 4 | n = int(input("enter the value: "))
j=5
i=n
while(i>0):
k=i
while(k>0):
print(k, end =" ")
k=k-1
print()
i=i-1 |
19831488276b64d0cf440ab3407e2a93c39289db | dplicn/dpPython | /heimaPython/12判断语句.py | 411 | 3.78125 | 4 | '''
1,语法
if 条件:
执行的内容
执行的内容
......
'''
if (2<1):
print('执行的内容')
print('执行的内容')
print('外面执不执行?')
'''
需求,
1,输入年龄
2,判断是否成年
3,输出,成年可以上网
'''
age = eval(input('请输入年龄:'))
if (age>=18):
print('成年可以上网')
else:
print(f'你的年龄是{age},未成年,不能上网')
|
7ae205cc9a99d7b41e8c0ac13dc9e2a16dea1ea2 | Leoberium/BA | /Chapter9/BA9A.py | 1,576 | 3.546875 | 4 | import sys
class Node:
def __init__(self, key):
self.label = key
self.edges = {}
self.e_lbl = {}
def get_label(self):
return self.label
def change_label(self, key):
self.label = key
def add_edge(self, v, w):
self.edges[v] = w
self.e_lbl[w] = v
def remove_edge(self, v):
w = self.edges[v]
self.edges.pop(v)
self.e_lbl.pop(w)
def edge_label(self, v):
return self.edges[v]
def output_edges(self):
return self.edges.items()
def neighbors(self):
return self.edges.keys()
def neighbor_by_label(self, w):
if w in self.e_lbl:
return self.e_lbl[w]
else:
return -1
def trie_construction(patterns):
trie = {0: Node(0)}
cur_key = 1
for pattern in patterns:
cur_node = trie[0]
for ch in pattern:
v = cur_node.neighbor_by_label(ch)
if v > -1:
cur_node = trie[v]
else:
v = cur_key
v_node = Node(v)
trie[v] = v_node
cur_node.add_edge(v, ch)
cur_node = v_node
cur_key += 1
return trie
def main():
patterns = []
for line in sys.stdin:
patterns.append(line.strip())
trie = trie_construction(patterns)
for u in trie:
node = trie[u]
for edge in node.output_edges():
v, w = edge
print(str(u) + '->' + str(v) + ':' + w)
if __name__ == '__main__':
main()
|
6b8184b2a20f01aa53b0a165f139f276bd96b2f8 | vikasvasireddy01/django-project | /primetest1/prime3/datecheck.py | 1,496 | 3.859375 | 4 | def datetimevalidation(r):
l=r.split('-')
thirty =[4,6,9,11]
thirtyone=[1,3,5,7,8,10,12]
feb=[2]
if len(l)!=3:
return False
if len(l)==1:
return False
if len(l)==3:
if l[0].isnumeric():
if l[1].isnumeric():
if int(l[1])in thirty:
if l[2].isnumeric():
if int(l[2])<31:
return True
else:
return False
elif int(l[1])in thirtyone:
if l[2].isnumeric():
if int(l[2])<32:
return True
else:
return False
elif int(l[1])in feb:
if l[2].isnumeric():
if int(l[0])%4==0:
if int(l[2])<30:
return True
else:
return False
if int(l[0])%4!=0:
if int(l[2])<29:
return True
else:
return False
else:
return False
else:
return False
else:
return False
datetimevalidation('201-3-3')
|
1ae7c353093ab8f4efd22943091d73ad9e9084ac | anildoferreira/CursoPython-PyCharm | /exercicios/aula13-ex047.py | 135 | 3.625 | 4 | print('-=' * 16)
print('ACHANDO NÚMEROS PARES DE 1 A 50')
print('-=' * 16)
for pares in range(0, 52, 2):
print(pares, end=(' '))
|
4f360ad185bd933c7f974f04e524a52509544f8b | vishal-chillal/assignments | /new_tasks_23_june/46_solutions/20_translation_through_dictionary.py | 851 | 3.859375 | 4 | # 20.Represent a small bilingual lexicon as a Python dictionary in the following fashion {"merry":"god", "christmas":"jul", "and":"och", "happy":"gott", "new":"nytt", "year":"arr"} and use it to translate your Christmas cards from English into Swedish. That is, write a function translate() that takes a list of English words and returns a list of Swedish words.
base_dict = {"merry":"god", "christmas":"jul", "and":"och", "happy":"gott", "new":"nytt", "year":"arr"}
res = []
def translate(word_list):
for i in word_list:
try:
res.append(base_dict[i])
except:
res.append(i)
return res
def translate_using_map(word_list):
res = map(lambda x:base_dict[x], word_list)
return res
if __name__ == "__main__":
print translate_using_map(["happy","merry","new"])
print translate(["happy","and"])
|
dab19715b792e3874a5468b4af6eb79184b673e8 | Rishabh450/PythonAutomation | /removedublicate.py | 150 | 3.828125 | 4 | numbers = set([4, 2, 6, 4, 6, 3, 2])
uniques = []
for number in numbers:
if number not in uniques:
uniques.append(number)
print(uniques)
|
964c0b5ba2e18ea252c7617fd0eec84c8cd1c2a5 | evan9148/dic_logical_question | /highest_keys_dic.py | 533 | 3.9375 | 4 | my_dict = {
'a':50,
'b':58,
'c': 56,
'd':40,
'e':100,
'f':20
}
a=[]
highest=0
sec_highest=0
third_highest=0
for i in my_dict:
for j in my_dict:
if highest<my_dict[j]:
highest=my_dict[j]
b=j
elif highest>my_dict[j] and sec_highest<my_dict[j]:
sec_highest=my_dict[j]
c=j
elif sec_highest>my_dict[j] and third_highest<my_dict[j]:
third_highest=my_dict[j]
d=j
a.append(b)
a.append(c)
a.append(d)
print(a)
|
34eb621b2340339e4dbed5e4a788c408599d1f81 | v-franco/Facebook-ABCS | /strings & arrays/FB_in_string.py | 748 | 3.921875 | 4 |
# Create string with 'Facebook'
# Create counter variable
# Check if input is empty, return
# iterate over characters of given word
# if char in given word == char in facebook, add counter
# if len == facebook, true, else: false
def fbInString(input):
fb = "facebook"
counter = 0
if not input:
return False
else:
for i in range(len(input)):
if input[i] == fb[counter]:
counter += 1
if counter == len(fb):
return True
return False
if __name__ == '__main__':
print(fbInString("ffffaaccccebbok"))
print(fbInString("is instagram owned by facebook?"))
print(fbInString("ffffaacccebbooook"))
print(fbInString(""))
|
a5e8a5aa24518eb88fc69e3da7c1f6eb4de8ee8d | stephanbos96/programmeren-opdrachten | /school/les5/5.1.py | 233 | 3.609375 | 4 | def convert(celcius):
fah = celcius * 1.8 + 32
return fah
def table():
for i in range(-30, 41, 10):
print ('{0:5},{1:6}'.format(i, convert(i)))
print ('{0:6}{1:6}'.format(' c',' f'))
table()
|
952608c4744b6f5329dcbbff875528cc0ac204e6 | daniel-reich/ubiquitous-fiesta | /iLLqX4nC2HT2xxg3F_21.py | 162 | 3.515625 | 4 |
def deepest(lst,d=1):
if not any([isinstance(i,list) for i in lst]):
return d
else:
return max([deepest(i,d+1) for i in lst if isinstance(i,list)])
|
6824016d3cfffe8485b3ab47f87df992981b8c1b | me6edi/Python_Practice | /B.Code Hunter/48. Python Bangla Tutorial -- Square Root -- Code Hunter/48. Python Bangla Tutorial -- Square Root -- Code Hunter.py | 130 | 3.6875 | 4 | #Square - Root
import math
a = int(input())
b = int(input())
c = math.sqrt(a*a + b*b)# c = sqrt(a=4 + b=9) = 13 = 3.605
print(c)
|
f876514d534e4802a34f139ac8c1b93c8574410f | romaniuknataliia/pyladies | /03/cykly.py | 1,054 | 3.796875 | 4 | '''from math import pi, sin, cos, ceil
x = sin(1) # v radianech
print(x)
a = cos(sin(1))
print(a)
if sin(1) < 3:
print('Je to mensi.')
print(pi)
y = 6
z = str(y)
print(type(y)) #funkce co rika typ promene
print(ceil(6.2)) #zaokruhli do 7'''
'''import math
help(math)'''
'''from random import randrange, uniform
print(randrange(1, 7))
print(uniform(1, 7))'''
from turtle import forward, right, left
from turtle import penup, pendown
from turtle import exitonclick
from turtle import shape
shape('turtle')
# 3 kvadrata pid riznym kutom
'''for _cislo in range(3):
for _cislo in range(4):
forward(150)
right(90)
left(20)'''
#sxody
'''for _ in range(5):
forward(50)
left(90)
forward(50)
right(90)'''
#punktyr
'''for delka in range(10):
forward(1 + delka)
penup()
forward(10)
pendown()'''
#left(20)
'''forward(150)
right(90)
forward(150)
right(90)
forward(150)
right(90)
forward(150)
right(90)'''
#trouhelnik
for cislo in range(3):
forward(150)
left(120)
exitonclick()
|
7d0a66c5aab03ac4a1ef66f314a4b38981c549a1 | SeavantUUz/LC_learning | /removeDuplicate2.py | 552 | 3.6875 | 4 | # coding: utf-8
__author__ = 'AprocySanae'
__date__ = '15/7/25'
def removeDuplicate2(nums):
if not nums:
return 0
index = 0
toleration = 1
pre = float('inf')
for num in nums:
if not num == pre:
toleration = 1
else:
if not toleration:
continue
else:
toleration -= 1
pre = num
nums[index] = num
index += 1
del nums[index:]
return index
if __name__ == '__main__':
print removeDuplicate2([1,1,1,2,2,3])
|
47c081a83df50563b96ace43fc9b7313df3dc07a | chelseashin/AlgorithmStudy2021 | /chelseashin/Programmers/04_Sorting/K번째수.py | 292 | 3.65625 | 4 | # 5분 소요
# 문제 읽고 그대로 구현
# List Comprehension 으로 한줄 코딩
def solution(array, commands):
return [sorted(array[i-1:j])[k-1] for i, j, k in commands]
array = [1, 5, 2, 6, 3, 7, 4]
commands = [[2, 5, 3], [4, 4, 1], [1, 7, 3]]
print(solution(array, commands)) |
c6543067013d5f1a5ecb2eccf352fafe34520c79 | juniorsmartins/Aulas-Python | /Aula5.py | 250 | 3.6875 | 4 | print('Desafio 2 - Curso em Vídeo')
print('Professor: Gustavo Guanabara')
dia = input('Em qual dia você nasceu? ')
mes = input('Em qual mês você nasceu? ')
ano = input('Em qual ano você nasceu? ')
print('Você nasceu em ', dia, ' de ', mes, ' de ', ano)
|
ab624ff48e1525af299a9a540a5e7d09d4bc3719 | Viniciusadm/Python | /exerciciosCev/Mundo 2/Aula 14/064.py | 214 | 3.84375 | 4 | numero = 0
soma = -999
contador = -1
while numero != 999:
numero = int(input('Digite um número [999 pra parar]: '))
soma+=numero
contador+=1
print(f'A soma dos {contador} números digitados é {soma}') |
33c117589ba3ccdba6bab0e98f835bde6f2f0392 | ParadoxTwo/Python-And-Machine-Learning | /A5.py | 15,101 | 3.515625 | 4 | #!/usr/bin/env python
# coding: utf-8
# # SIT 720 - Machine Learning
#
# Lecturer: Chandan Karmakar | karmakar@deakin.edu.au
#
# School of Information Technology,
# <br/>Deakin University, VIC 3125, Australia.
# ## Assessment Task 5 (35 marks)
#
# In this assignment, you will use a lot of concepts learnt in this course to come up with a good solution for a given chronic kidney disease prediction problem.
#
# ## Submission Instruction
# 1. Student should insert Python code or text responses into the cell followed by the question.
#
# 2. For answers regarding discussion or explanation, **maximum ten sentences are suggested**.
#
# 3. Rename this notebook file appending your student ID. For example, for student ID 1234, the submitted file name should be A5_1234.ipynb.
#
# 4. Insert your student ID and name in the following cell.
# In[ ]:
# Student ID: 218599279
# Student name: Edwin John Nadarajan
# ##The dataset
#
# **Dataset file name:** chronic_kidney_disease.csv
#
# **Attribute Information:**
#
# There are 24 features + class = 25 attributes
# 1. Age(numerical): age in years
# 2.Blood Pressure (numerical): bp in mm/Hg
# 3.Specific Gravity (categorical): sg - (1.005,1.010,1.015,1.020,1.025)
# 4.Albumin (categorical): al - (0,1,2,3,4,5)
# 5.Sugar (categorical): su - (0,1,2,3,4,5)
# 6.Red Blood Cells (categorial): rbc - (0, 1)
# 7.Pus Cell (categorical): pc - (0, 1)
# 8.Pus Cell clumps (categorical): pcc - (0, 1)
# 9.Bacteria (categorical): ba - (0, 1)
# 10.Blood Glucose Random (numerical): bgr in mgs/dl
# 11.Blood Urea (numerical): bu in mgs/dl
# 12.Serum Creatinine (numerical): sc in mgs/dl
# 13.Sodium (numerical): sod in mEq/L
# 14.Potassium (numerical): pot in mEq/L
# 15.Hemoglobin (numerical): hemo in gms
# 16.Packed Cell Volume (numerical)
# 17.White Blood Cell Count (numerical): wc in cells/cumm
# 18.Red Blood Cell Count (numerical): rc in millions/cmm
# 19.Hypertension (categorical): htn - (0, 1)
# 20.Diabetes Mellitus (categorical): dm - (0, 1)
# 21.Coronary Artery Disease (categorical): cad - (0, 1)
# 22.Appetite (categorical): appet - (0, 1)
# 23.Pedal Edema (categorical): pe - (0, 1)
# 24.Anemia (categorical): ane - (0, 1)
# 25.Class (categorical): class - (ckd, notckd)
#
# ## Part 1: Short questions: **(6 marks)**
#
#
#
# 
#
# 1. For the above figure, what value of k in KNN method will give the best accuracy for leave-one-out cross-validation. Report accuracy and k value. **(3 marks)**
# In[ ]:
# CODE and/or COMMENT
# k = 2 should give the best accuracy fro leave-one-out cross-validation method.
# accuracy = (true_positives+true_negatives)/(true_positives+true_negatives+false_positives+false_negatives)
# accuracy = (14+14)/(14+4+14+4) = 28/36 = 0.777
# 2. In classification, overfitting and underfitting is a big problem. Does it happen in Random Forest or not? Why? **(3 marks)**
# In[ ]:
# CODE and/or COMMENT
"""
A single decision tree can easily overfit due to noise in the data. Random Forest is an ensemble of decision tree.
Therefore, a Random Forest with only one tree will overfit. But as the number of trees increases, overfitting decreases.
The more trees in Random Forest, the better. Overfitting can be prevented by increasing min_samples_leaf parameter (but not too much).
As for underfitting, yes, that too can happen depending on how the hyperparameters are set. For eg: increasing min_samples_split
hyperparameter too much can cause underfitting. Also, if the value of the max_leaf_nodes is very small, the random forest
is likely to underfit.
"""
# ## Part 2: **(24 marks = 4 methods x 6)**
#
# Using the following four supervised machine learning methods, answer questions(A-D).
# 1. Support vector machine
# 2. K-Nearest Neighbour
# 3. Decision tree, and
# 4. Random forest
#
# **A.** Build optimised classification model to predict the chronic kidney disease from the dataset. **(1 marks)**
#
# **B.** For each optimised model, answer the followings - **(3 marks)**
#
# * which hyperparameters were optimised? [Hint: For SVM, kernel can be considered as one of the hyperparameters.]
#
# * what set or range of values were used for each hyperparameter?
#
# * which metric was used to measure the performance?
#
# * justify your design decisions.
#
# **C.** Plot the prediction performance against hyperparameter values to visualise the optimisation process and mark the optimal value. **(1 marks)**
#
# **D.** Evaluate the model (obtained from A) performance on the test set. Report the confusion matrix, F1-score and accuracy. **(1 marks)**
# In[45]:
# CODE and/or COMMENT
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import classification_report, confusion_matrix
from sklearn import svm
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import KFold
from sklearn.model_selection import cross_val_score
from sklearn.metrics import accuracy_score
get_ipython().run_line_magic('matplotlib', 'inline')
df = pd.read_csv('chronic_kidney_disease.csv')
#cleaning
df = df[df!='?']
df = df.dropna()
#preprocessing
y = df['class']
X = df.drop(columns=['class'])
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.40)
#standardization
scaler = StandardScaler()
scaler.fit(X_train)
X_train = scaler.transform(X_train)
X_test = scaler.transform(X_test)
print(y.value_counts())
#I'm using accuracy as the main performance metric as this dataset is relatively balanced
#(the number of not_ckd is close to ckd) as seen in y.value_counts()
#if it was imbalanced, I would have used F1 score or sensitivity/recall
#Using SVM for prediction
print('SVM:\n')
#optimising SVM model based on kernel. Using these kernels:
kernels = ['linear', 'poly', 'rbf', 'sigmoid']
best = kernels[0]
accs = []
highest=0
for kernel in kernels:
clf = svm.SVC(kernel=kernel)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
#performance evaluation using accuracy because the dataset is balanced
acc = accuracy_score(y_test, y_pred)
accs.append(acc)
#saving the top accuracy score
if(acc>highest):
best = kernel
highest = acc
print('Accuracy: '+str(acc))
#plotting on graph
plt.plot(kernels,accs)
plt.xlabel('kernel')
plt.ylabel('Performance')
plt.show()
print('\nBest kernel hyperparameter in SVM is: '+best+'\n\n')
#optimising SVM model based on C. Using this range:
Cs = np.arange(1,10)
best = 1
accs = []
highest=0
for i in Cs:
clf = svm.SVC(C=i)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
#performance evaluation using accuracy because the dataset is balanced
acc = accuracy_score(y_test, y_pred)
accs.append(acc)
#saving the top accuracy score
if(acc>highest):
best = i
highest = acc
print('Accuracy: '+str(acc))
#plotting on graph
plt.plot(Cs,accs)
plt.xlabel('C value')
plt.ylabel('Performance')
plt.show()
print('\nBest C value hyperparameter in SVM is: '+str(best)+'\n\n')
#Using KNN for classification
print('KNN:\n')
#Optimizing the model based on k. Using the range 1 to 10
best = 1
highest=0
accs = []
ks = np.arange(1,10)
for k in ks:
classifier = KNeighborsClassifier(n_neighbors=k)
classifier.fit(X_train, y_train)
y_pred = classifier.predict(X_test)
#performance evaluation using accuracy because the dataset is balanced
acc = accuracy_score(y_test, y_pred)
accs.append(acc)
#saving the top accuracy score
if(acc>=highest):
best = k
highest = acc
print('Accuracy: '+str(acc))
#plotting on graph
plt.plot(ks,accs)
plt.xlabel('k value')
plt.ylabel('Performance')
plt.show()
print('\nBest k value hyperparameter in KNN is: '+str(best)+'\n\n')
#Optimizing the model based on algorithm. Using these:
algorithms = ['auto', 'ball_tree', 'kd_tree', 'brute']
best = algorithms[0]
highest=0
accs = []
for algo in algorithms:
classifier = KNeighborsClassifier(algorithm=algo)
classifier.fit(X_train, y_train)
y_pred = classifier.predict(X_test)
#performance evaluation using accuracy because the dataset is balanced
acc = accuracy_score(y_test, y_pred)
accs.append(acc)
#saving the top accuracy score
if(acc>highest):
best = algo
highest = acc
print('Accuracy: '+str(acc))
#plotting on graph
plt.plot(algorithms,accs)
plt.xlabel('Algorithm')
plt.ylabel('Performance')
plt.show()
print('\nBest algorithm hyperparameter in KNN is: '+str(best)+'\n\n')
#Using Decision Tree for classification
print('Decision Tree:\n')
#Using min_samples_split hyperparameter for optimization with a range of 2 to 11 because minimum value must be 2
mss = np.arange(2,11)
highest = 0
accs = []
for j in mss:
clf = DecisionTreeClassifier(min_samples_split=j)
clf = clf.fit(X_train,y_train)
y_pred = clf.predict(X_test)
#performance evaluation using accuracy because the dataset is balanced
acc = accuracy_score(y_test, y_pred)
accs.append(acc)
#saving the top accuracy score
if(acc>highest):
best = j
highest = acc
print('Accuracy: '+str(acc))
#plotting on graph
plt.plot(mss,accs)
plt.xlabel('min_samples_split')
plt.ylabel('Performance')
plt.show()
print('\nBest value of min_samples_split hyperparameters in Decision Tree is: '+str(best)+'\n\n')
#Using min_samples_leaf hyperparameter for optimization with a range of 1 to 10
msl = np.arange(1,10)
highest = 0
accs = []
for j in mss:
clf = DecisionTreeClassifier(min_samples_leaf=j)
clf = clf.fit(X_train,y_train)
y_pred = clf.predict(X_test)
#performance evaluation using accuracy because the dataset is balanced
acc = accuracy_score(y_test, y_pred)
accs.append(acc)
#saving the top accuracy score
if(acc>highest):
best = j
highest = acc
print('Accuracy: '+str(acc))
#plotting on graph
plt.plot(msl,accs)
plt.xlabel('min_samples_leaf')
plt.ylabel('Performance')
plt.show()
print('\nBest value of min_samples_leaf hyperparameters in Decision Tree is: '+str(best)+'\n\n')
#Using Random Forest for classification
print('Random Forest:\n')
#n_estimators ie the number of trees in the forest is selected as the hyperparameter for optimization ranging from 1 to 201
estimators = np.arange(1,201,20)
highest = 0
accs = []
for i in estimators:
clf=RandomForestClassifier(n_estimators=i)
clf.fit(X_train,y_train)
y_pred=clf.predict(X_test)
#performance evaluation using accuracy because the dataset is balanced
cc = accuracy_score(y_test, y_pred)
accs.append(acc)
#saving the top accuracy score
if(acc>highest):
best = i
highest = acc
print('Accuracy: '+str(acc))
#plotting on graph
plt.plot(estimators,accs)
plt.xlabel('Estimators')
plt.ylabel('Performance')
plt.show()
print('\nBest value of n_estimators hyperparameters in Decision Tree is: '+str(best)+'\n\n')
#Using min_samples_split hyperparameter for optimization in range 2 to 11 because minimum value cannot be less than 2
mss = np.arange(2,11)
highest = 0
accs = []
for i in mss:
clf=RandomForestClassifier(min_samples_split=i)
clf.fit(X_train,y_train)
y_pred=clf.predict(X_test)
#performance evaluation using accuracy because the dataset is balanced
cc = accuracy_score(y_test, y_pred)
accs.append(acc)
#saving the top accuracy score
if(acc>highest):
best = i
highest = acc
print('Accuracy: '+str(acc))
#plotting on graph
plt.plot(mss,accs)
plt.xlabel('min_samples_split')
plt.ylabel('Performance')
plt.show()
print('\nBest value of min_samples_split hyperparameters in Decision Tree is: '+str(best)+'\n\n')
# In[56]:
#Using linear kernel and C value 1 for optimizing SVM model
print('\nSVM\n')
clf = svm.SVC(kernel='linear',C=1)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
#performance evaluation
acc = accuracy_score(y_test, y_pred)
print('Accuracy: '+str(acc))
print('Confusion Matrix:\n'+str(confusion_matrix(y_test, y_pred)))
print('Classification Report:\n'+str(classification_report(y_test, y_pred)))
#Using k=4 neighbours and algorith='auto' for optimizing KNN model
print('\nKNN\n')
clf = KNeighborsClassifier(n_neighbors=4,algorithm='auto')
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
#performance evaluation
acc = accuracy_score(y_test, y_pred)
print('Accuracy: '+str(acc))
print('Confusion Matrix:\n'+str(confusion_matrix(y_test, y_pred)))
print('Classification Report:\n'+str(classification_report(y_test, y_pred)))
#Using min_samples_split = 2 and min_samples_leaf = 3 hyperparameter for optimization of Decision Tree model
print('\nDecision Tree\n')
clf = DecisionTreeClassifier(min_samples_split = 2,min_samples_leaf=3)
clf = clf.fit(X_train,y_train)
y_pred = clf.predict(X_test)
#performance evaluation
acc = accuracy_score(y_test, y_pred)
print('Accuracy: '+str(acc))
print('Confusion Matrix:\n'+str(confusion_matrix(y_test, y_pred)))
print('Classification Report:\n'+str(classification_report(y_test, y_pred)))
#Using n_estimators=1 and min_samples_split = 2 hyperparameter for optimization of Random Forest model
print('\nRandom Forest\n')
clf = RandomForestClassifier(n_estimators=1,min_samples_split=2)
clf = clf.fit(X_train,y_train)
y_pred = clf.predict(X_test)
#performance evaluation
acc = accuracy_score(y_test, y_pred)
print('Accuracy: '+str(acc))
print('Confusion Matrix:\n'+str(confusion_matrix(y_test, y_pred)))
print('Classification Report:\n'+str(classification_report(y_test, y_pred)))
# ## Part 3: Discussion **(5 marks)**
#
# Based on the results obtained in Part-2, which classification method showed the best performance and why? Do you have any suggestions to further improve the model performances? **(5 marks)**
# In[ ]:
# CODE and/or COMMENT
"""
Based on the results obtained from Part-2, decision tree with min_samples_split of 2 and min_samples_leaf of 3 showed
the best performance.
By increasing the value of the min_sample_split, we can reduce the number of splits that happen in the decision tree
and therefore prevent the model from overfitting.
According to the graph of min_samples_leaf vs performance, we can clearly see that after a particular threshold, the
performance drops with the increase of min_samples_leaf. Apart from that, keeping this parameter value too low may result in
overfitting sometimes. Therefore the shown value of 3 is optimal.
One way to improve the performance of the model would be to optimize max_depth parameter. Using the max_depth parameter,
what depth is wanted for the decision tree's growth can be set. Increasing max_depth might increase performance but we need
to be careful because after a certain threshold, overfitting will begin and test performance will drop.
"""
|
abf6aa5060e78602b62ddf8fa95e8ae123106045 | treasureb/Python | /day11/lambda.py | 514 | 3.875 | 4 | # -*- coding: utf-8 -*-
#匿名函数
map(lambda x:x * x,[1,2,3,4,5,6,7,8,9])
print map
#匿名函数的限制
#1.只能有一个表达式
#2.不写return
sorted([1,3,9,5,0],lambda x,y:-cmp(x,y))
print sorted
#返回匿名函数
myabs = lambda x: -x if x < 0 else x
#使用匿名函数简化代码
def is_not_empty(s):
return s and len(s.strip()) > 0
print filter(is_not_empty,['test',None,'','str',' ','END'])
#简化后
#print filter(lambda s: s and len(s.strip()) > 0,['test',None,'','str',' ','END']
|
b3f42f39965f8f14411f52021623e17ec216517b | lauramayol/laura_python_core | /week_03/labs/12_files/12_02_rename_doc.py | 1,159 | 4.03125 | 4 | '''
Write a function called sed that takes as arguments a pattern string,
a replacement string, and two filenames; it should read the first file
and write the contents into the second file (creating it if necessary).
If the pattern string appears anywhere in the file, it should be
replaced with the replacement string.
If an error occurs while opening, reading, writing or closing files,
your program should catch the exception, print an error message,
and exit.
Solution: http://thinkpython2.com/code/sed.py.
Source: Read through the "Files" chapter in Think Python 2e:
http://greenteapress.com/thinkpython2/html/thinkpython2015.html
'''
def sed(find_string, replace_with, f1, f2):
try:
with open(f1, "r") as f:
data = f.readlines()
except:
print(f"Cannot read file {f1}")
else:
new_data = ""
for word in data:
new_data += word.replace(find_string, replace_with)
write_file(new_data, f2)
def write_file(message, fwrite):
try:
with open(fwrite, "w") as f:
f.write(message)
except:
print(error)
sed("e", "!!", "words.txt", "output.txt")
|
53ee41d6ec4a6f337b37a414ff13ccf5657017f3 | itsme-vivek/Akash-Technolabs-Internship | /Day-2/DataType.py | 902 | 3.734375 | 4 | #number
a=50
print(a, "is of type", type(a))
b=50.5
print(b, "is of type", type(b))
print(b, "is complex number?", isinstance(50.5, float))
c= 3 + 2j
print(c, "is complex number?", isinstance(3 + 2j, int))
#String Datatype
name= "Waether is good"
print("name is:", name)
print(name[0])
print(name[2:6])
print(name[3:])
print(name[:6])
print(name * 2)
print(name + "The")
#List datatypes
list1 = [50, 60, 30 , 90, 40, "hello", 10 ]
print("list1[2] =", list1[2])
print("list1[0:5] =", list1[0:5])
print("list1[5:] =", list1[5:])
print(type(list1))
#Tuple Datatypes
tuple1 = (50, 60, 30 , 90, 40, "hello", 10)
print(tuple1)
print("tuple1[2]", tuple1[2])
print("tuple1[0:4]", tuple1[0:4])
print("tuple1[5:]", tuple1[5:])
#Dictionary Datatype
d = {1: "Python", 2: "Easy", "key": 50}
print(type(d))
print("2nd =", d[1])
print("dictonary key =", d["key"]) |
cf1d7684aea27496d67a466470dfa183b8fb41cf | SURBHI17/python_daily | /src/quest_11.py | 421 | 3.90625 | 4 | #PF-Prac-11
def find_upper_and_lower(sentence):
#start writing your code here
countU=0
countL=0
result_list=[]
for el in sentence:
if el>="a" and el<="z":
countL+=1
elif el>="A" and el<="Z":
countU+=1
result_list.append(countU)
result_list.append(countL)
return result_list
sentence="Come Here"
print(find_upper_and_lower(sentence)) |
1a6f71e24dd935c09ece349a16e32cab31e2e068 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_201/1901.py | 1,146 | 3.75 | 4 | def solve(input):
def splitLargestSegment():
#find largest segment
largestIndex = findLargest()
#split in two and reinsert
newSegmentLeft = int((segments[largestIndex]-1)/2)
if (segments[largestIndex]%2) != 0:
#for odd numbers
newSegmentRight = newSegmentLeft
else:
#even numbers
newSegmentRight = newSegmentLeft+1
#insert new segments
segments[largestIndex] = newSegmentLeft
segments.insert(largestIndex+1, newSegmentRight)
def findLargest():
largestIndex = 0
for i in range(len(segments)):
if segments[i] > segments[largestIndex]:
largestIndex = i
return largestIndex
data = input.split(" ")
N = int(data[0])
K = int(data[1])
segments = [N]
#whenever a toileteer arrives:
for i in range(K-1):
splitLargestSegment()
#final toileteer
largestIndex = findLargest()
maximum = int(segments[largestIndex]/2)
if segments[largestIndex]%2 == 0:
#even spaces
minimum = maximum-1
else:
minimum = maximum
return str(maximum)+" "+str(minimum)
T = int(input()) # reads in number of test cases
# Take input
for i in range(1, T + 1):
print("Case #{}: {} ".format(i, solve((input())))) |
ab3eecd0ac9baa1f7fcf5b5a9a30322809d441eb | honorezemagho/python-10Apps | /5. list-comprehension.py | 351 | 3.65625 | 4 | temps = [221, 234, 340, 230]
# list comprehension
new_temps = [temp / 10 for temp in temps]
print(new_temps)
# list comprehension with if Conditional
temps2 = [221, 234, 340,-9999, 230]
# new_temps = [temp / 10 for temp in temps if temp != -9999]
## with else
new_temps = [temp / 10 if temp != -9999 else 0 for temp in temps ]
print(new_temps)
|
85a8da89e3664e0dacf483b65414c67f4305782a | rurinaL/coursera_python | /week2/32.py | 95 | 3.515625 | 4 | n = int(input())
i = 1
sum2 = 0
while i <= n:
sum2 += i ** 2
i += 1
print(sum2)
|
68947a688332b36e429c07edf579df67106ab84c | 0neir0s/ctci | /9-recursion/9.4.py | 417 | 3.75 | 4 | def allSubsets(elems):
""" return the set of all subsets of elems """
l = len(elems)
if l == 0:
return []
if l == 1:
return [set(),set(elems)]
if l == 2:
return [set(),set(elems),{elems[0]},{elems[1]}]
output = []
for ss in allSubsets(elems[1:]):
output.append(ss)
output.append(ss.union({elems[0]}))
return output
print(allSubsets([1,2,3,4]))
|
0f1672716b9348fdcb1f848d79c9b2772bfdcef5 | Goontown/RandomEmails | /Random.email/main.py | 929 | 3.625 | 4 | import random
from random import randint
import csv
def forname():
with open("firstnames.txt", "r") as file:
allText = file.read()
words = list(map(str, allText.split()))
name = (random.choice(words))
return name
def lastname():
with open("lastnames.csv", "r") as file:
allText = file.read()
words = list(map(str, allText.split()))
name = (random.choice(words))
return name
def numbers():
value = (random.randint(10,999))
return value
def generator(forname,lastname,numbers):
adress = (f"{forname}{lastname}{numbers}@gmail.com\n")
print(adress)
file = open('randomemails', 'a')
file.write(adress)
file.close()
def main ():
for i in range (30):
fn = forname()
ln = lastname()
nu = numbers()
generator(fn, ln, nu)
if __name__ == "__main__":
main()
|
622dee3e18f4741b333e3a57045ae8a83e1967ef | MJK618/Python | /Jatin Kamboj CW/3.6.0/Random Sum.py | 229 | 4.125 | 4 | #Sum of Random Numbers
#By Jatin Kamboj
n=int(input("Enter Total Number Of Terms"))
Sum=0
for i in range(1,n+1):
Num=int(input("Enter Number"))
Sum=Sum+Num
print(("Sum="),(Sum))
print("Total Sum=",(Sum))
|
031eee7d4a230ebf2ec977339804ff5df1cd5591 | BKlasmer/heart_disease | /heart_disease/data_loader.py | 8,041 | 3.71875 | 4 | #!/usr/bin/env python3
# -*- coding: latin-1 -*-
import pandas as pd
import numpy as np
from sklearn.utils import resample
from sklearn.model_selection import train_test_split
from heart_disease.utils import Logging
""" Class to ingest UCI Heart Disease Data Set - https://archive.ics.uci.edu/ml/datasets/Heart+Disease
"""
class DataLoader(object):
def __init__(self, logger_level: str = "INFO") -> None:
self._logger = Logging().create_logger(logger_name="Data Loader", logger_level=logger_level)
self._logger.info("Initialise Data Loader")
self.dataset = self.prepare_dataset()
def prepare_dataset(self) -> pd.DataFrame:
"""Prepares the heart disease dataset, which performs the following:
- Ingesting the data
- Handling missing data
- One hot encoding the categorical data
- Apply normalisation
- Binarise the label
Returns:
pd.DataFrame: Heart disease dataset
"""
dataset = self._ingest_data()
dataset = self._handle_missing_data(dataset)
dataset = self._handle_categorical(dataset)
dataset = self._apply_normalisation(dataset)
# Change heart disease to binary
heart_disease = pd.DataFrame(
[1 if x >= 1 else 0 for x in dataset["Heart Disease"].to_list()], columns=["Heart Disease"]
)
dataset = dataset.drop("Heart Disease", axis=1)
dataset = dataset.join(heart_disease)
return dataset
def split_dataset(self, test_size: float = 0.2, balance: bool = True, split_labels: bool = True, random_state: int = 42):
train, test = train_test_split(self.dataset, test_size=test_size, random_state=random_state)
if balance:
train = self.balance_data(train, random_state)
if split_labels:
train_labels, train_features, _ = self.features_and_labels_to_numpy(train)
test_labels, test_features, _ = self.features_and_labels_to_numpy(test)
self._logger.info(f"Training Features Shape: {train_features.shape}")
self._logger.info(f"Training Labels Shape: {train_labels.shape}")
self._logger.info(f"Testing Features Shape: {test_features.shape}")
self._logger.info(f"Testing Labels Shape: {test_labels.shape}")
return train_features, train_labels, test_features, test_labels
self._logger.info(f"Training Shape: {train.shape}")
self._logger.info(f"Testing Shape: {test.shape}")
return train, test
def _ingest_data(self) -> pd.DataFrame:
"""Ingests the processed Cleveland dataset from https://archive.ics.uci.edu/ml/datasets/Heart+Disease
Returns:
pd.DataFrame: The processed Cleveland dataset with column names
"""
column_names = [
"Age",
"Sex",
"Chest Pain Type",
"Resting Blood Pressure",
"Cholestoral",
"Fasting Blood Sugar",
"Resting ECG",
"Maximum Heart Rate",
"Exercise Induced Angina",
"ST Depression",
"Slope of Peak Exercise",
"Number of Major Vessels",
"Thal",
"Heart Disease",
]
dataset = pd.read_csv(
"https://archive.ics.uci.edu/ml/machine-learning-databases/heart-disease/processed.cleveland.data",
header=None,
names=column_names,
)
self._logger.info(f"Dataset loaded: {len(dataset.columns)} columns, {len(dataset)} rows")
return dataset
def _handle_missing_data(self, dataset: pd.DataFrame) -> pd.DataFrame:
"""Replace all missing data in the dataset
Args:
dataset (pd.DataFrame): Heart disease dataset with missing values
Returns:
pd.DataFrame: Heart disease dataset without missing values
"""
self._logger.info(
f"{len(dataset.loc[dataset['Thal'] == '?', 'Thal'])} missing values in Thal, replaced with 3.0 (= normal)."
)
dataset.loc[dataset["Thal"] == "?", "Thal"] = "3.0"
self._logger.info(
f"{len(dataset.loc[dataset['Number of Major Vessels'] == '?', 'Number of Major Vessels'])} missing values in Number of Major Vessels, replaced with 0.0 (= mode)."
)
dataset.loc[dataset["Number of Major Vessels"] == "?", "Number of Major Vessels"] = "0.0"
# Change both these column types to floats
dataset = dataset.astype({"Thal": "float64", "Number of Major Vessels": "float64"})
return dataset
def _handle_categorical(self, dataset: pd.DataFrame) -> pd.DataFrame:
"""One hot encodes all the categorical fields in the dataset
Args:
dataset (pd.DataFrame): Heart disease dataset with categorical features
Returns:
pd.DataFrame: Heart disease dataset with one-hot encoded categorical features
"""
one_hot_dict = {
"Chest Pain Type": [
"Chest Pain Typical",
"Chest Pain Atypical",
"Chest Pain Non-anginal",
"Chest Pain Asymptomatic",
],
"Resting ECG": ["Resting ECG Normal", "Resting ECG Abnormal", "Resting ECG Hypertrophy"],
"Slope of Peak Exercise": ["Peak Exercise Slope Up", "Peak Exercise Slope Flat", "Peak Exercise Slope Down"],
"Thal": ["Thal Normal", "Thal Fixed Defect", "Thal Reversable Defect"],
}
for column, new_columns in one_hot_dict.items():
temp = pd.get_dummies(dataset[column])
temp.columns = new_columns
dataset = dataset.join(temp)
dataset = dataset.drop(column, axis=1)
return dataset
def _apply_normalisation(self, dataset: pd.DataFrame) -> pd.DataFrame:
"""Normalises the dataset to values between 0 and 1
Args:
dataset (pd.DataFrame): Heart disease dataset with unbounded features
Returns:
pd.DataFrame: Heart disease dataset with features bounded between 0 and 1
"""
variable_columns = [
"Age",
"Resting Blood Pressure",
"Cholestoral",
"Maximum Heart Rate",
"ST Depression",
"Number of Major Vessels",
]
for column in variable_columns:
column_values = dataset[column].to_numpy()
dataset[column] = self._minmax(column_values)
return dataset
@staticmethod
def balance_data(train_set: pd.DataFrame, random_state: int = 42) -> pd.DataFrame:
heart_disease = train_set[train_set["Heart Disease"] == 1]
no_heart_disease = train_set[train_set["Heart Disease"] == 0]
max_samples = max(len(heart_disease), len(no_heart_disease))
# Upsample to balance
if len(heart_disease) < len(no_heart_disease):
heart_disease = resample(heart_disease, replace=True, n_samples=max_samples, random_state=random_state)
else:
no_heart_disease = resample(no_heart_disease, replace=True, n_samples=max_samples, random_state=random_state)
train_set = pd.concat([heart_disease, no_heart_disease])
return train_set
@staticmethod
def features_and_labels_to_numpy(dataset):
labels = np.array(dataset["Heart Disease"])
dataset = dataset.drop("Heart Disease", axis=1)
features = np.array(dataset)
feature_columns = list(dataset.columns)
return labels, features, feature_columns
@staticmethod
def _minmax(column_values: np.ndarray) -> np.ndarray:
"""Applies min max normalisation on a numpy array
Args:
column_values (np.ndarray): Unbounded numpy array
Returns:
np.ndarray: Min max normalised numpy array
"""
min_val = np.min(column_values)
max_val = np.max(column_values)
return (column_values - min_val) / (max_val - min_val)
|
f1c127874c4edd2046a2104ae90dbcc1f173256c | uccser/codewof | /codewof/programming/content/en/evens-out/solution.py | 147 | 3.703125 | 4 | def evens_out(numbers):
result = []
for number in numbers:
if number % 2 != 0:
result.append(number)
return result
|
0db01653a86b406231f7f2585922de10f6514b8d | SOL-2/TIL | /python/4.while_for.py | 2,737 | 3.703125 | 4 | # 1. while문
# ryony = 1
# while ryony <= 5:
# print(ryony, '번 요요를 한다')
# ryony += 1
# num = 1
# sum = 0
# while num <= 100:
# sum += num
# num += 1
# print('sum =' ,sum)
# num = 151
# sum = 0
# while num <= 1500:
# sum += num
# num += 1
# print('sum = ', sum)
# 2. for문
# for student in [1,2,3,4,5]:
# print(student, '번 학생이 도망갔네')
# range(시작, 끝, 증가값)
# 거꾸로
# for i in range (100, 0, -1):
# print(i, '번째 학생은 어디로 간거야?')
# for i in range (1,51):
# if i % 10 == 0:
# print('+', end='')
# else:
# print('-',end='')
# for i in range(1, 51):
# if i % 10 == 5:
# print('+',end='')
# else:
# print('-',end='')
# break : 특정한 조건에 의해 탈출
# ex
age = [31, 23, 24, 41, 51, 62, 24, 13, 24, 53]
# for i in age:
# if 20 <= i <= 70:
# print('앞으로도 건강을 유지합시다!! 당신의 나이는 %d입니다' %i)
# elif i < 20:
# print('우앙 새나라의 어린이당')
# break
# age 리스트 13 뒤의 24, 53은 출력되지 않는다
# continue : 이번 루프는 지나치고 다른 루프는 계속 수행
# for i in age:
# if 20 <= i <= 70:
# print('앞으로도 건강을 유지합시다!! 당신의 나이는 %d입니다' %i)
# elif i < 20:
# print('우앙 새나라의 어린이당')
# continue
# age 리스트 13 뒤의 24, 53도 출력된다
# 이중루프
# for i in range(2, 20):
# print('='*10)
# print(i,'단')
# print('='*10)
# for q in range(2, 20):
# print('%dx%d='%(i,q),i*q)
# dan = 2
# while dan <= 19:
# hang = 2
# print(dan, '단')
# while hang <= 9:
# print(dan, '*', hang, '=', dan*hang)
# hang += 1
# dan += 1
# print()
# 무한 루프
# while True를 활용하여 무한 루프 작성
# 반복 조건이 항상 참이므로 이 루프는 무한 반복 -> 중간에 반드시 break 명령을 해야함
# print('4 x 8 = ?')
# while True:
# a = int(input('정답을 입력하세요 : '))
# if (a == 32) :
# break
# print('정답')
# 오프셋 : 기준점에서의 상대적 거리. 첫 요소의 오프셋이 0부터 시작하는 것이 좋다
# for i in range(0, 6):
# for num in range(i*10, (i*10)+10):
# print (num, end=',')
# print()
# star = 1
# start = 0
# end = 10
# for i in range(end, start, -1):
# print(' '*i,'*'* star, ' '*i)
# print()
# star += 2
def star_triangle(endline):
star = 1
for i in range(endline,0, -1):
print(' ' * i, '*'*star, ' ' * i)
star += 2
star_triangle(int(input("줄 수를 입력하세요")))
|
0b355a5486c853ed549c061bde54e708c0050eb3 | iqbalhanif/digitalent | /p3.py | 3,183 | 3.546875 | 4 | # nama file p3.py
# Isikan email anda dan copy semua cell code yang dengan komentar #Graded
# untuk revisi dan resubmisi sebelum deadline
# silakan di resubmit dengan nilai variable priority yang lebih besar dari
# nilai priority submisi sebelumnya
# JIKA TIDAK ADA VARIABLE priority DIANGGAP priority=0
priority = 2
#netacad email cth: 'abcd@gmail.com'
email='iqbal.hanif.ipb@gmail.com'
# copy-paste semua #Graded cells YANG SUDAH ANDA KERJAKAN di bawah ini
def caesar_encript(txt,shift):
b = ''
c = shift % 26
for i in range (0, len(txt)):
if txt[i].isalpha() == True:
if txt[i].islower() == False:
x = ord(txt[i].lower())
if x + c > 122:
y = 96 + (x + c - 122)
elif x + c < 97:
y = 123 + (c + (x - 97))
else:
y = x + c
z = chr(y).upper()
else:
x = ord(txt[i])
if x + c > 122:
y = 96 + (x + c - 122)
elif x + c < 97:
y = 123 + (c + (x - 97))
else:
y = x + c
z = chr(y)
else:
z = txt[i]
b = b + z
return(b)
pass
# Fungsi Decript caesar
def caesar_decript(chiper,shift):
b = ''
c = shift % 26
for i in range (0, len(chiper)):
if chiper[i].isalpha() == True:
if chiper[i].islower() == False:
x = ord(chiper[i].lower())
if x - c < 97:
y = 122 - (c - (x - 96))
elif x - c > 122:
y = 96 - (c + (122 - x))
else:
y = x - c
z = chr(y).upper()
else:
x = ord(chiper[i])
if x - c < 97:
y = 122 - (c - (x - 96))
elif x - c > 122:
y = 96 - (c + (122 - x))
else:
y = x - c
z = chr(y)
else:
z = chiper[i]
b = b + z
return(b)
pass
#return caesar_encript(chiper,-shift)
# Fungsi mengacak urutan
def shuffle_order(txt,order):
return ''.join([txt[i] for i in order])
# Fungsi untuk mengurutkan kembali sesuai order
def deshuffle_order(sftxt,order):
a = [0] * len(sftxt)
for i in range(0,len(sftxt)):
x = order[i]
a[x] = sftxt[i]
a = ''.join(a)
return a
pass
import math
# convert txt ke dalam bentuk list teks yang lebih pendek
# dan terenkrispi dengan urutan acak setiap batchnya
def send_batch(txt,batch_order,shift=3):
# Mulai Kode anda di sini
enc = caesar_encript(txt, shift)
if (((math.ceil(len(enc) / len(batch_order))) * len(batch_order)) - (len(enc))) !=0:
a = "_" * (((math.ceil(len(enc) / len(batch_order))) * len(batch_order)) - (len(enc)))
b = enc + a
else:
b = enc
x = [b[i:i+len(batch_order)] for i in range(0, len(enc), len(batch_order))]
y = [0] * math.ceil((len(b) / len(batch_order)))
for i in range(0,len(x)):
y[i] = shuffle_order(x[i],batch_order)
return y
pass
# batch_cpr: list keluaran send_batch
# fungsi ini akan mengembalikan lagi ke txt semula
def receive_batch(batch_cpr,batch_order,shift=3):
batch_txt = [caesar_decript(deshuffle_order(i,batch_order),shift) for i in batch_cpr]
return ''.join(batch_txt).strip('_') |
707bb9d528570f9dbdc29e8b6a93ce7bffd03537 | elvarlax/python-masterclass | /Section 07/Sets Challenge/sets_challenge.py | 414 | 4.28125 | 4 | """
Section 7 Challenge - Sets
Create a program that takes some text and returns a list of
all the characters in the text that are not vowels,
sorted in alphabetical order.
You can either enter the text from the keyboard or
initialise a string variable with the string.
"""
text = "Python is a very powerful language"
vowels = {"a", "e", "i", "o", "u"}
result = sorted(set(text).difference(vowels))
print(result)
|
656786c9c8e502960e244797afd3dcbc5732388c | viswan29/Leetcode | /Strings/leftmost_col_with_at_least_a_1.py | 2,583 | 3.953125 | 4 | '''
A binary matrix means that all elements are 0 or 1. For each individual row of the matrix, this row is sorted in non-decreasing order.
Given a row-sorted binary matrix binaryMatrix, return leftmost column index(0-indexed) with at least a 1 in it. If such index doesn't exist, return -1.
You can't access the Binary Matrix directly. You may only access the matrix using a BinaryMatrix interface:
BinaryMatrix.get(x, y) returns the element of the matrix at index (x, y) (0-indexed).
BinaryMatrix.dimensions() returns a list of 2 elements [n, m], which means the matrix is n * m.
Submissions making more than 1000 calls to BinaryMatrix.get will be judged Wrong Answer. Also, any solutions that attempt to circumvent the judge will result in disqualification.
Example 1:
Input: mat = [[0,0],[1,1]]
Output: 0
Example 2:
Input: mat = [[0,0],[0,1]]
Output: 1
Example 3:
Input: mat = [[0,0,0,1],[0,0,1,1],[0,1,1,1]]
Output: 1
'''
# """
# This is BinaryMatrix's API interface.
# You should not implement it, or speculate about its implementation
# """
#class BinaryMatrix(object):
# def get(self, x: int, y: int) -> int:
# def dimensions(self) -> list[]:
class Solution:
# method - 1 --> use binary search (O r*log c)
def find_firstOne(self, binaryMatrix, row, col_count):
start = 0
end = col_count - 1
ans = -1
while(start <= end):
mid = int((start + end)/2)
if binaryMatrix.get(row, mid) == 1:
ans = mid
end = mid - 1
else:
start = mid + 1
return ans
def leftMostColumnWithOne(self, binaryMatrix: 'BinaryMatrix') -> int:
dimen = binaryMatrix.dimensions()
n = dimen[0]
m = dimen[1]
min_ans = m
for row in range(n):
ans = self.find_firstOne(binaryMatrix, row, m)
if ans > -1:
min_ans = min(min_ans, ans)
if min_ans == m:
return -1
return min_ans
# method - 2 --> start from right top, if 1 then move left, if 0 then down(O r + c)
def leftMostColumnWithOne(self, binaryMatrix: 'BinaryMatrix') -> int:
dimen = binaryMatrix.dimensions()
n = dimen[0]
m = dimen[1]
row = 0
col = m-1
ans = -1
while(row < n and col >= 0):
if binaryMatrix.get(row,col) == 1:
ans = col
col -= 1
else:
row += 1
return ans |
836a6052fd4a4cee51b5564b67c994e9e075a394 | PearCoding/SpriteResourceCompiler | /src/padding/fill_padding.py | 1,479 | 3.546875 | 4 | from .padding import Padding
from PIL import ImageDraw
class FillPadding(Padding):
def fill(self, img, tiles, padding):
drawer = ImageDraw.Draw(img)
for tile in tiles:
if tile.x > padding:
for y in range(tile.y, tile.y + tile.height):
pixel = tile.image.getpixel((0, y - tile.y))
for x in range(tile.x - padding, tile.x):
drawer.point((x, y), pixel)
if tile.y > padding:
for x in range(tile.x, tile.x + tile.width):
pixel = tile.image.getpixel((x - tile.x, 0))
for y in range(tile.y - padding, tile.y):
drawer.point((x, y), pixel)
if tile.x + tile.width < img.width - 1: # It's ok to draw over the canvas
for y in range(tile.y, tile.y + tile.height):
pixel = tile.image.getpixel((tile.width - 1, y - tile.y))
for x in range(tile.x + tile.width, tile.x + tile.width + padding):
drawer.point((x, y), pixel)
if tile.y + tile.height < img.height - 1: # It's ok to draw over the canvas
for x in range(tile.x, tile.x + tile.width):
pixel = tile.image.getpixel((x - tile.x, tile.height - 1))
for y in range(tile.y + tile.height, tile.y + tile.height + padding):
drawer.point((x, y), pixel)
|
932560a3d6eb03a1f8018cc8463eafe69a455768 | keipa/bsuir-labs | /11cem/sap/database/database_upgrade.py | 2,498 | 3.609375 | 4 | from Tkinter import *
import database_module as data
class App:
def __init__(self, master):
frame = Frame(master, bg="green")
frame.pack(fill=BOTH)
self.quit_button = Button(frame, text="QUIT", fg="red", command=self.close_window)
self.quit_button.pack(side=LEFT)
self.select_button = Button(frame, text="Select All", fg="blue", command=self.get_all_records)
self.select_button.pack(side=LEFT)
self.find_button = Button(frame, text="Find", fg="green", command=self.find_records)
self.find_button.pack(side=LEFT)
# find records by name
self.text_box = Text(frame, height=1, width=15, font='Arial 10', wrap=WORD)
self.text_box.pack(side=LEFT)
self.text_box.insert(END, "Pupkin")
self.list_box = Listbox(root, width=30) # Create 2 listbox widgets
# self.list_box.place(x=22, y=40)
self.list_box.pack(side=LEFT)
self.text_box_surname = Text(frame, height=1, width=6, font='Arial 10', wrap=WORD)
self.text_box_surname.pack(side=RIGHT)
self.text_box_surname.insert(END, "Kolkin")
self.text_box_group = Text(frame, height=1, width=5, font='Arial 10', wrap=WORD)
self.text_box_group.insert(END, "123")
self.text_box_group.pack(side=RIGHT)
self.text_box_faculty = Text(frame, height=1, width=5, font='Arial 10', wrap=WORD)
self.text_box_faculty.insert(END, "Agra")
self.text_box_faculty.pack(side=RIGHT)
self.insert_button = Button(frame, text="Insert", fg="black", command=self.insert_records)
self.insert_button.pack(side=RIGHT)
def insert_records(self):
data.insert_records(self.text_box_surname.get("1.0", END).strip(),int(self.text_box_group.get("1.0", END).strip()),self.text_box_faculty.get("1.0", END).strip())
self.get_all_records()
def clear_list_box(self):
self.list_box.delete(0, END)
def add_values_into_list(self, values_list):
for item in values_list:
self.list_box.insert(0, item[0] + " " + str(item[1]) + " " + item[2])
def get_all_records(self):
self.clear_list_box()
self.add_values_into_list(data.get_all_records())
def close_window(self):
root.destroy()
def find_records(self):
self.clear_list_box()
self.add_values_into_list(data.find_record(self.text_box.get("1.0", END)))
root = Tk()
root.geometry("400x200")
app = App(root)
root.mainloop()
|
a45fa7b0bc2562f2acd9e0e7268319cfce7e3410 | adamcarlton/CTCI | /chapter3.py | 3,958 | 4.0625 | 4 | import sys
class Stack():
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
if self.isEmpty():
print("Stack underflow exception")
exit(1)
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def size(self):
return len(self.items)
class Queue():
def __init__(self):
self.items = []
def dequeue(self):
if self.isEmpty():
print("Queue underflow exception")
exit(1)
item, self.items = self.items[0], self.items[1:]
return item
def enqueue(self, item):
self.items.append(item)
def isEmpty(self):
return self.items == []
def size(self):
return len(self.items)
# Question 3.1
# Divide the array into 3 slots and modify the push, pop, peek methods to take in a specific stack requirement
# Question 3.2
# Create a variable inside the stack to hold the min that is initially set to MAXINT, then upon pushing you would compare
# the value you're pushing to the current min value
class StackMin():
def __init__(self):
self.items = []
self.smallest = sys.maxint
def isEmpty(self):
return self.items == []
def push(self, item):
if item < self.smallest:
self.smallest = item
self.items.append(item)
def pop(self):
if self.isEmpty():
print("Stack underflow exception")
exit(1)
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def lowest(self):
return self.smallest
# Question 3.3
class SetOfStacks():
def __init__(self):
self.stackSet = []
self.stackSet.append(Stack())
self.curIdx = 0
self.limit = 10
self.currentStack = self.stackSet[self.curIdx]
def size(self):
return len(self.currentStack)
def isEmpty(self):
return self.currentStack == [] or self.stackSet == []
def push(self, item):
if len(self.currentStack) == self.limit:
self.stackSet.append(Stack())
self.curIdx += 1
self.currentStack = self.stackSet[self.curIdx]
self.currentStack.append(item)
def pop(self):
if self.isEmpty() and self.curIdx == 0:
print("Stack underflow exception")
exit(1)
elif self.isEmpty():
self.stackSet = self.stackSet[:self.curIdx]
self.curIdx -= 1
self.currentStack = self.stackSet[self.curIdx]
return self.currentStack.pop()
def peek(self):
return self.currentStack[len(self.currentStack)-1]
# Question 3.4
class QueueStack():
def __init__(self):
self.stack1 = Stack()
self.stack2 = Stack()
def isEmpty(self):
return self.stack1.isEmpty()
def enqueue(self, item):
self.stack1.push(item)
def dequeue(self, item):
if self.isEmpty():
print("Underflow exception")
exit(1)
while not self.isEmpty():
self.stack2.push(self.stack1.pop())
value = self.stack2.pop
while not self.stack2.isEmpty():
self.stack1.push(self.stack2.pop())
return value
def size(self):
return self.stack1.size()
# Question 3.5
def stackSort(stack):
tempStack = Stack()
while not stack.isEmpty():
temp = stack.pop()
while not tempStack.isEmpty() and tempStack.peek() > temp:
stack.push(tempStack.pop())
tempStack.push(temp)
return tempStack
def printStack(stack):
while not stack.isEmpty():
print(stack.pop())
stack = Stack()
stack.push(1)
stack.push(5)
stack.push(4)
stack.push(3)
sorted = stackSort(stack)
printStack(sorted)
|
4fc52f2b80e1fb648b1b2cc3677655575c21846e | gearoidmurphy/PRACTICAL-PI | /6_morsecode.py | 443 | 3.71875 | 4 | #! /use/bin/python
import os
from time import sleep
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(22,GPIO.OUT)
loop_count = 0
#define a function called morsecode
def morsecode():
#out
GPIO.output(22,GPIO.HIGH)
sleep(.1)
GPIO.output(22,GPIO.HIGH)
sleep(.1)
os.system('clear')
print "Morse Code"
loop_count = input("How many times would you like SOS to loop?:")
while loop_count>0:
loop_count = loop_count - 1
morsecode()
|
8f196d1a33426214d34b503d05856abfbc19f9a7 | SuperGuy10/LeetCode_Practice | /Python/937. Reorder Log Files.py | 1,544 | 3.625 | 4 | '''
Tag: String; Difficulty: Easy
You have an array of logs. Each log is a space delimited string of words.
For each log, the first word in each log is an alphanumeric identifier. Then, either:
Each word after the identifier will consist only of lowercase letters, or;
Each word after the identifier will consist only of digits.
We will call these two varieties of logs letter-logs and digit-logs.
It is guaranteed that each log has at least one word after its identifier.
Reorder the logs so that all of the letter-logs come before any digit-log.
The letter-logs are ordered lexicographically ignoring identifier, with the identifier used in case of ties.
The digit-logs should be put in their original order.
Return the final order of the logs.
Example 1:
Input: ["a1 9 2 3 1","g1 act car","zo4 4 7","ab1 off key dog","a8 act zoo"]
Output: ["g1 act car","a8 act zoo","ab1 off key dog","a1 9 2 3 1","zo4 4 7"]
Note:
0 <= logs.length <= 100
3 <= logs[i].length <= 100
logs[i] is guaranteed to have an identifier, and a word after the identifier.
'''
class Solution(object):
def reorderLogFiles(self, logs):
"""
:type logs: List[str]
:rtype: List[str]
"""
alpha = []
num = []
for i in logs:
if i.split()[1].isalpha():
alpha.append(i)
else:
num.append(i)
alpha.sort(key = lambda x: x.split()[0]) #key part
alpha.sort(key = lambda x: x.split()[1:])
return alpha+num
|
8cb9b9efc26141a808b38252e560465bdf19dc52 | shubhsahu/Python | /Sort_list_wrt_str.py | 563 | 4.25 | 4 | """
Given a string str and an array of strings strArr[], the task is to sort the array according to the alphabetical order defined by str.
Note: str and every string in strArr[] consists of only lower case alphabets.
"""
s1 = 'fguecbdavwyxzhijklmnopqrst'
strArr1 = ['game', 'is', 'the', 'best', 'place', 'for', 'learning']
s2 = 'avdfghiwyxzjkecbmnopqrstul'
strArr2 = ['rainbow', 'consists', 'of', 'colours', 'ashu', 'bablu']
def shubh(p,y):
sortstr=sorted(y, key= lambda x:p.find(x[0]))
print(sortstr)
print(s1)
shubh(s1,strArr1)
print(s2)
shubh(s2,strArr2) |
98383854cd512aa12f560ea7c745c59c1a32edda | diskpart123/xianmingyu | /3.python第五章学习/29实例研究.py | 5,137 | 3.71875 | 4 | """
第五章:实例研究
"""
"""
5-1 程序清单
回顾程序清单4-4,它给出一个提示用户输入一个数学题答案的程序.现在通过循环,你可以重写这个程序,让用户一直输入答案
直到输入正确的答案为止;
import random
number1 = random.randint(1, 10)
number2 = random.randint(1, 10)
if number1 < number2:
number1, number2 = number2, number1
print(str(number1) + "-" + str(number2) + "=?")
sign_out = 1
while sign_out:
answer = eval(input("请输入答案:"))
if answer == number1 - number2:
print("答案正确.." + str(number1) + "-" + str(number2) + "=" + str(number1 - number2))
sign_out = 0
else:
print("答案不正确,请重新输入....")
"""
"""
5-2 程序清单
这里的问题是猜出电脑里存储的数字是什么.你将要编写一个能够随机生成一个0到100之间且包括0和100的数字的程序.这个程序提示用户连续的输入数字
直到它与那个随机生成的数字相同.对于每个用户输入的数字,程序提示它是否过高还是过低,所以用户可以更明智的选择下一个输入的数字.下面是一个简单
的运行
import random
number=random.randint(0,100)
input_up=int(input("请输入数字:"))
if input_up>number:
print("你输入的数字过大...")
elif input_up<number:
print("你输入的数字太小...")
else:
print("你猜对了...")
#进阶:修改上面的代码,利用while循环直到用户把数字猜对后退出循环
import random
number=random.randint(0,100)
print(number)
input_up=-1
while number != input_up:
input_up=int(input("请输入数字:"))
if input_up>number:
print("你输入的数字过大...")
elif input_up<number:
print("你输入的数字太小...")
else:
print("你猜对了...")
"""
"""
5-4 程序清单
在程序清单4-4的减法测试程序中,它只会在每次运行时生成一个问题.你可以使用一个循环来连续生成问题.那么该怎样
编写一个能生成5个问题的程序呢?按照循环设计策略:
第一步:确定需要被循环的语句,这些语句包括获取两个随机数,提示用户做减法,然后给这个题打分.
第二部:将这些语句放到一个循环里
第三步:添加循环控制变量和循环继续条件来执行5次循环
import random
count = 0
num = 5
while count < 5:
count += 1
number1 = random.randint(0, 9)
number2 = random.randint(0, 9)
if number1 < number2:
number1, number2 = number2, number1
print(str(number1) + "-" + str(number2) + "=?")
answer = input("请输入答案:")
if answer.isdigit():
answer = int(answer)
if answer == number1 - number2:
pritn("恭喜你答对了....")
else:
print("答错了,请重新输入答案,你还有%d次机会" % (num - count))
else:
print("你输入的不是数字,请重新输入...")
"""
"""
5-5 程序清单(使用哨兵值控制循环)
让程序读取并计算一组不确定个数的整数的和.输入0表明输入结束,你不必为每一个输入的值设置一个新的变量.
而是只需要使用一个名为data的变量来存储输入值,使用名为sum的变量来存储这些值的和,只要读入一个值并且
它不为0,那就把它赋给data,并把data添加到sum中
import time
data = eval(input("请输入数字:"))
sum = 0
while data != 0:
data = eval(input("请输入数字:")) # data在程序中起到的作用就是"哨兵"的作用,如果输入的data的值为0循环结束
sum += data
print(sum)
print(sum)
"""
"""
5-6 程序清单
使用嵌套for循环来显示乘法口诀表
#示例1
for i in range(1,10):
for j in range(1,i+1):
print(str(j)+"x"+str(i)+"="+str(j*i),end=" ")
print()
示例2:
print(" MuliplicationTable")
print(" ", end="")
for i in range(1, 10):
print(format(i, "3d"), end=" ")
print()
print("----------------------------------------")
for i in range(1, 10):
print(i, "|", end="")
for j in range(1, 10):
print(" ", format(i * j, "2d"), end="")
print()
"""
"""
5-9 程序清单
问题:预测学费
假设今年你所在的大学学费为10000美元并且它以每年7%的速度增长.那么多少年之后学费会翻倍?
思考:在你尝试编写程序之前,首先考虑如何手动解决这个问题.第二年的学费是第一年的学费*1.07,因此,以后每一年的学费都是其前一年学费的*1.07
tuition = 10000 # 学费的初始值
year = 0 # 年数
while tuition < 20000: # 学费递增小于20000
tuition *= 1.07 # 学费按照每一年百分之七的速度增长
year += 1 # 每循环一次年数加1
print("%d年之后学费会翻倍" % (year))
print("翻倍后的学费为:$" + format(tuition, ".2f"))
"""
"""
绘制18*18的网格
import turtle
for y in range(0, 360, 20):
for x in range(0, 380, 20):
turtle.goto(x, y)
turtle.pendown()
turtle.penup()
for x in range(0, 380, 20):
for y in range(0, 360, 20):
turtle.goto(x, y)
turtle.pendown()
turtle.penup()
turtle.penup()
turtle.done()
"""
|
8293bc8bb0408e205964dbf88581d1f43c3ffc6b | superhy/med-ques-intent-rec | /run_rec.py | 5,892 | 3.515625 | 4 | # -*- coding: UTF-8 -*-
'''
Created on 2016年11月22日
@author: super
'''
'''
1. laod train and test data
2. train network predictor model
3. evaluate network predictor model
*4. run predict by network model
'''
'''
1. train model
2. evaluate the model
'''
import time
from core import layer
from interface.testMedQuesRec import testLoadBasicData, testTrainNetPred, \
testEvalNetPred, testLoadAttentionData, testGetNpyData
def one_data(lb_data=9, name_net='BiDirtLSTM_Net', encode_type=0):
# exp_param
# xy_data, input_shape = testLoadBasicData(lb_data=lb_data)
xy_data, input_shape = testGetNpyData(lb_data=lb_data, encode_type=encode_type)
print('x_train: {0}'.format(xy_data[0]))
print(xy_data[0].shape)
print('y_train: {0}'.format(xy_data[1]))
print(xy_data[1].shape)
# print(len(set(xy_data[1]])))
print('x_test: {0}'.format(xy_data[2]))
print('y_test: {0}'.format(xy_data[3]))
# print(len(set(xy_data[3])))
print('input_shape: {0}'.format(input_shape))
model_path, history_metrices = testTrainNetPred(xy_data, input_shape, name_net=name_net, lb_data=lb_data)
score = testEvalNetPred(xy_data, model_path)
del(xy_data, input_shape)
# testRunNetPred(xy_data, model_path)
''' write the exp-res into file '''
resFileName = 'RES_{0}_mat{1}_data{2}-1000.txt'.format(name_net, encode_type, lb_data)
resStr = str(history_metrices) + '\n' + str(score)
fw = open(resFileName, 'w')
fw.write(resStr)
fw.close()
del(model_path, history_metrices)
# one_data(encode_type=1)
'''
batch process as above operation from data 0~9
'''
def batch_allData(name_net='BiDirtGRU_Net', encode_type=1):
for i in range(10):
one_data(lb_data=i, name_net=name_net, encode_type=encode_type)
# batch_allData()
'''
bacth all model on one data, switch data by manual
'''
def batch_allModel_oneData(lb_data=9, encode_type=1):
name_nets = ['CNNs_Net', 'GRU_Net', 'BiDirtGRU_Net', 'LSTM_Net', 'BiDirtLSTM_Net']
# name_nets = ['CNNs_Net', 'GRU_Net', 'LSTM_Net', 'BiDirtLSTM_Net', 'StackLSTMs_Net']
# name_nets = ['CNNs_Net', 'LSTM_Net', 'BiDirtLSTM_Net']
for name_net in name_nets:
one_data(lb_data=lb_data, name_net=name_net, encode_type=encode_type)
# batch_allModel_oneData(encode_type=0)
# batch_allModel_oneData(encode_type=1)
'''
batch process all model in all data 0~9
'''
def batch_allModel_allData(encode_type=1):
# name_nets = ['CNNs_Net', 'GRU_Net', 'BiDirtGRU_Net', 'LSTM_Net', 'BiDirtLSTM_Net', 'StackLSTMs_Net']
name_nets = ['CNNs_Net', 'GRU_Net', 'BiDirtGRU_Net', 'LSTM_Net', 'BiDirtLSTM_Net']
#===========================================================================
# '''except CNNs_Net'''
# name_nets = ['GRU_Net', 'BiDirtGRU_Net', 'LSTM_Net', 'BiDirtLSTM_Net', 'StackLSTMs_Net']
#===========================================================================
for name_net in name_nets:
batch_allData(name_net=name_net, encode_type=encode_type)
# batch_allModel_allData()
'''
1. fig the model framework picture
(inux only)
'''
#===============================================================================
# # exp_param
# lb_data = 0
# name_net = 'CNNs_Net'
#
# xy_data, input_shape = testLoadBasicData(lb_data=lb_data)
# testShowNetPred(input_shape=input_shape, name_net=name_net)
#===============================================================================
'''
load attention xy_data and store them into npz
'''
def load_store_matData(lb_data=9, encode_type=0):
'''
@param @encode_type: 0: basic mat data, 1: attention mat data
'''
xy_data = None
input_shape = None
if encode_type == 0:
xy_data, input_shape = testLoadBasicData(lb_data=lb_data)
else:
xy_data, input_shape = testLoadAttentionData(lb_data=lb_data)
print('x_train: {0}'.format(xy_data[0]))
print(xy_data[0].shape)
print('y_train: {0}'.format(xy_data[1]))
print(xy_data[1].shape)
# print(len(set(xy_data[1]])))
print('x_test: {0}'.format(xy_data[2]))
print('y_test: {0}'.format(xy_data[3]))
# print(len(set(xy_data[3])))
print('input_shape: {0}'.format(input_shape))
# load_store_matData(encode_type=0)
# load_store_matData(encode_type=1)
'''
batch load xy_data and store them into npz
'''
def batchload_store_matData(encode_type=1):
for i in range(10):
load_store_matData(lb_data=i, encode_type=encode_type)
# batchload_store_matData()
def evalPreTrainedModel(frame_path, lb_data=9, encode_type=0):
xy_data, input_shape = testGetNpyData(lb_data=lb_data, encode_type=encode_type)
print('x_train: {0}'.format(xy_data[0]))
print(xy_data[0].shape)
print('y_train: {0}'.format(xy_data[1]))
print(xy_data[1].shape)
# print(len(set(xy_data[1]])))
print('x_test: {0}'.format(xy_data[2]))
print('y_test: {0}'.format(xy_data[3]))
# print(len(set(xy_data[3])))
print('input_shape: {0}'.format(input_shape))
testEvalNetPred(xy_data, frame_path)
del(xy_data, input_shape)
# evalPreTrainedModel(frame_path='D:/intent-rec-file/model_cache/keras/2017.1.14 2500 att unicopy/BiDirtGRU_Net1000-5000_2.json', lb_data=9, encode_type=1)
# evalPreTrainedModel(frame_path='D:/intent-rec-file/model_cache/keras/2017.1.16 3500 att unidecay/LSTM_Net1000-5000_2.json', lb_data=9, encode_type=1)
# evalPreTrainedModel(frame_path='D:/intent-rec-file/model_cache/keras/2017.1.9 5000 att unidecay/BiDirtLSTM_Net1000-5000_2.json', lb_data=9, encode_type=1)
# evalPreTrainedModel(frame_path='D:/intent-rec-file/model_cache/keras/2017.1.15 3500 basic/BiDirtGRU_Net1000-5000_2.json', lb_data=9, encode_type=0)
|
894fc6bc6534c1fd392465ce68c4c5d67c2d71a7 | 633-1-ALGO/introduction-python-FrankTheodoloz | /10.1- Exercice - Conditions/condition1.py | 593 | 3.703125 | 4 | # Problème : Etant donné deux variables c et d, on veut savoir si leur produit est négatif ou positif ou nul.
# Contrainte : Ne pas calculer le produit des deux nombres.
# Résultat attendu : Un message affichant "Produit positif" ou "Produit négatif" ou "Produit nul".
# Indications : Vous pouvez changer les valeurs des variables pour vos tests.
c = 42
d = 31
if (c == 0) or (d == 0):
print("Produit nul :", c * d)
# elif (c < 0 and d >= 0) or (d < 0 and c >= 0):
elif (c < 0 <= d) or (d < 0 <= c):
print("Produit négatif :", c * d)
else:
print("Produit positif:", c * d)
|
d4f94308aa23e99842d7ec375b65327400e76b97 | benwei/Learnings | /pySamples/testAsciiToBin.py | 660 | 3.578125 | 4 | import binascii
myString = "0123\r\n"
ba = bytearray(myString)
def padzero(s):
bitstring=s[2:]
bitstring = -len(bitstring) % 8 * '0' + bitstring
return bitstring
def binleadingzero(c):
d = int(binascii.hexlify(c),16)
a = bin(d);
bitstring=a[2:]
bitstring = -len(bitstring) % 8 * '0' + bitstring
return str(d) + " -> " + bitstring
print "====== using string + binascii hexlify ====="
balen = len(myString)
i = 0
while i < balen:
print binleadingzero(myString[i])
i = i + 1
print "====== using bytearray ====="
i = 0
balen = len(ba)
while i < balen:
print str(ba[i]) + " -> " + padzero(bin(ba[i]))
i = i + 1
|
31e1851686d2cd8e95989d559a7c4299f97a257d | RDAW1/Programacion | /Practica 5/Ejercicio 8.py | 392 | 3.71875 | 4 | print 'Escribe un limite'
a=input()
print 'Escribe un valor que no supere' ,(a)
b=input()
while b>a:
print (b), 'es mayor a' ,(a), 'intentalo otra vez'
b=input()
li=[b]
a=a-b
while a>0:
print 'Introduce un valor'
b=input()
while b>a:
print (b), 'es demasiado grande, intentalo otra vez'
b=input()
li=li+[b]
a=a-b
print (li)
|
72cc72d64708599edc7e0117e6419a1bd6c0200c | kayanpang/champlain181030 | /190224_revision/slide1-38_while-loop.py | 135 | 3.890625 | 4 | # a while loop tests the validity of the boolean value before the statement(s) are executed
a = 1
while a < 10:
print(a)
a += 1 |
d8f0e727137808b86003298e3bc6adc7b4c3a928 | DAVIDnHANG/Sprint-Challenge--Intro-Python | /src/oop/oop1.py | 1,313 | 3.984375 | 4 | # Write classes for the following class hierarchy:
#
# [Vehicle]->[FlightVehicle]->[Starship]
# | |
# v v
# [GroundVehicle] [Airplane]
# | |
# v v
# [Car] [Motorcycle]
#
# Each class can simply "pass" for its body. The exercise is about setting up
# the hierarchy.
#
# e.g.
#
# class Whatever:
# pass
#
# Put a comment noting which class is the base class
#base
class Vehicle():
def __init__(self, Name = "asdf"):
self.Name = Name
def getflightVehicle(self):
return self.Name
def getStarShip(self):
return self.Name
pass
# Vehicle has a flight Vehicle
class FlightVehicle(Vehicle):
def __init__(self, starship = "star2"):
pass
def getStarship(self):
self.starship = starship
pass
#Flight vehcile has a starship
class Starship(FlightVehicle):
pass
#GroundVehicle inheritance Vehicle
class GroundVehicle(Vehicle):
def __init__(self, Name = "toy", model = "h1"):
self.Name = Name
self.model=model
#a car is a ground vehicle
class Car(GroundVehicle):
pass
#motorcycle is a ground vehicle
class Motorcycle(GroundVehicle):
pass
#airplane is a flight vehicle
class Airplane(FlightVehicle):
pass
|
032249f16591b59976474632602aa152b902dee3 | Lyppeh/PythonExercises | /Repetition Structure Exercises/ex056.py | 950 | 3.515625 | 4 | soma = 0
media = 0
idade_homem_mais_velho = 0
nome_homem_mais_velho = 0
mulheres_com_menos_de_20_anos = 0
for d in range(1, 5):
print('----------- {} PESSOA ----------'.format(d))
nome = str(input('Digite seu nome: ')).strip()
idade = int(input('Sua idade: '))
sexo = str(input('Seu sexo [M/F]: ')).strip()
soma += idade
if d == 1 and sexo in 'Mm':
idade_homem_mais_velho = idade
nome_homem_mais_velho = nome
if sexo in 'Mm' and idade > idade_homem_mais_velho:
idade_homem_mais_velho = idade
nome_homem_mais_velho = nome
if sexo in 'Ff' and idade < 20:
mulheres_com_menos_de_20_anos += 1
media = soma / 4
print('A média de idade do grupo é de {:.1f} anos'.format(media))
print('A idade do homem mais velho é de {} anos, e seu nome é {}'.format(idade_homem_mais_velho, nome_homem_mais_velho))
print('{} mulheres tem menos de 20 anos'.format(mulheres_com_menos_de_20_anos))
|
e34a600e8fe9759f5a66f14649082e4b9e71dd51 | falecomlara/CursoEmVideo | /ex043 - IMC.py | 657 | 3.921875 | 4 | '''
peso e altura
calcular o IMC
18.5 < abaixo do peso
18.5 e 25 = peso ideal
25 a 30 = sobre peso
30 a 40 = obsesidade
40 acima = obesidade morbida
'''
mensagem = 'INDICE IMC'
traco = len(mensagem)
print ('='*traco)
print(mensagem)
print ('='*traco)
peso = float(input('Digite o seu peso: '))
altura = float(input('Digite sua altura: '))
imc = peso / (altura**2)
print ('Seu IMC é {}.'.format(round(imc,1)))
if imc < 18.5:
print('Abaixo do peso')
elif imc >= 18.5 and imc <= 25:
print('Peso ideal')
elif imc > 25 and imc <= 30:
print('Sobrepeso')
elif imc > 30 and imc <= 40:
print ('Obesidade')
else:
print ('Obesidade mórbida') |
b10e460039ceeb677c14044fe4b4c0d5400469bc | Allison-Fernandez/mis3640 | /Session 8/In-class-session-8.py | 1,813 | 3.953125 | 4 | team = "New England Patriots"
# letter = team[19]
# print(letter)
# index = 0
# while index < len(team):
# letter = team[index]
# print(letter)
# index = index + 1
# # Another way
# for letter in team:
# print(letter)
# prefixes = 'JKLMNOPQ'
# suffix = 'ack'
# for letter in prefixes:
# if letter == 'O' or letter == 'Q':
# print(letter + 'u' + suffix)
# else:
# print(letter + suffix)
team = 'New England Patriots'
# print(team[0:3]) #from index 0 to index 2 (3 not inclusive)
# print(team[0:4]) #from index 0 to index 3
# print(team[0:11])
# print(team[12:20]) #slicing the string (just one section fo the string)
# print(team[:11]) #same as [0:11]
# print(team[0:20:2]) #from index 0 to index 20 but only every 2 characters
# print(team[::2]) #same as above
# print(team[::-2]) #same as above but back to front
# #Strings are IMMUTABLE: they cannot be changed (you would need a new variable)
# new_team = team[:12]+'Beavers'
# print(new_team)
# print(team)
# def find(word, letter):
# index = 0
# while index < len(word):
# if word[index] == letter:
# return index
# index = index + 1
# return -1
# print(find(team, 'E'))
# for i in range(len(team)):
# if team[i] == 'a':
# print(i)
# for i, letter in enumerate(team):
# if letter == 'a':
# print(i, letter)
# word = 'New England Patriots'
# # count = 0
# # for letter in word:
# # if letter == 'a':
# # count = count + 1
# # print(count)
# def count(s, letter):
# c = 0
# for each in s:
# if each == letter:
# c += 1
# return c
# print(count(team, 'a'))
# new_team = team.upper() #print team in uppercase letter
# print(new_team)
# print(team.split())
# print(team.split('e')) #gets rid of the e
|
27c55de2e96ca58eb23d4634c06c3ea5b49d75a1 | HuipengXu/leetcode | /generateMatrix.py | 557 | 3.765625 | 4 | # @Time : 2019/6/3 9:05
# @Author : Xu Huipeng
# @Blog : https://brycexxx.github.io/
from typing import List
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
res = [[0] * n for _ in range(n)]
i, j, di, dj = 0, 0, 0, 1
for num in range(1, n ** 2 + 1):
res[i][j] = num
if res[(i + di) % n][(j + dj) % n] != 0:
di, dj = dj, -di
i += di
j += dj
return res
if __name__ == '__main__':
s = Solution()
print(s.generateMatrix(3))
|
625a8f6a918139d862306b34c4ed3b4f301518ce | Beto-Amaral/HalloWelt | /ex063 - Sequência de Fibonacci v1.0.py | 440 | 4.125 | 4 | '''Escreva um programa que leia um número N inteiro qualquer
e mostre na tela os N primeiros elementos de uma Sequência de Fibonacci.'''
print('-' * 35)
print('Sequencia de Fibonacci')
print('-' * 35)
n = int(input('Quantos termos voce quer mostrar? '))
t1 = 0
t2 = 1
print('~' * 35)
print(f'{t1}, {t2}', end='')
cont = 3
while cont <= n:
t3 = t1 + t2
print(f', {t3}', end='')
t1 = t2
t2 = t3
cont += 1
print(' FIM')
|
eb2228c2b560d9410d18f7c1df7713e037df20c7 | lodiatif/etl_pipeline | /example/simple_transfer.py | 1,930 | 3.53125 | 4 | """
In this example a list of user records is fetched from JSONPlaceholder fake REST API and loaded into CSV file.
This example doesnt perform any transformation to data so we wont cover Transformers in it.
"""
from etl import pipe
from etl.extractors import HttpJSONExtractor
from etl.loaders import CSVLoader
import os
# Initialise instream that fetches data from API.
#
# instream by itself doesnt fetch data, it needs an extractor to do that. Extractors are callable classes that have
# the logic of reading data from source and handing it over to instream in the form of an iterator.
#
# Our source data is JSON list of users from https://jsonplaceholder.typicode.com/users
# etl-pipeline has a default extractor for reading JSON from REST API - HttpJSONExtractor
# To initialise instream, we pass HttpJSONExtractor and provide parameters needed to initialize it.
data_source_api = 'https://jsonplaceholder.typicode.com/users'
instream = pipe.instream(extractor=HttpJSONExtractor, extractor_config={'url': data_source_api})
# Initialise outstream to load data coming from instream to CSV file.
#
# Just like instream, outstream doesn't load data by itself, it need a loader to do that. Loaders are callable classes
# that have the logic of loading data into storage, outstream provides loaders with data, one record at a time.
#
# We will load the incoming data to a CSV file.
# etl-pipeline has a default loader for loading data in CSV file.
# To initialise outstream, we pass CSVLoader class and provide parameters needed to initialize it.
filepath = "%s/'simple_transfer.csv'" % os.path.dirname(__file__)
headers = ['id', 'name', 'username', 'email', 'address', 'phone', 'website', 'company']
outstream = pipe.outstream(loader=CSVLoader, loader_config={'filepath': filepath, 'headers': headers})
# Eventually we run the ETL pipeline like so..
pipe.flow(instream, outstream)
# The data should be in CSV file by now.
|
8829348b5318c217d2a17fe8a30347ca4a44e5f5 | richnamk/python_nov_2017 | /richardN/pythFundamentals/coinToss/coinToss.py | 598 | 3.796875 | 4 | import random
def coinToss(num):
attempt = 1
heads = 0
tails = 0
results = ""
count = 0
for x in range(1,num):
toss = random.randint(0,1)
if toss == 1:
heads += 1
result = "heads"
print "attempt #", count, ": Throwing coin, it's a ", result, "got", heads, "heads for far and ", tails, "so far"
else:
tails +=1
result = "tails"
print "attempt #", count, ": Throwing coin, it's a ", result, "got", heads, "heads for far and ", tails, "so far"
count +=1
coinToss(5001)
|
a63c063b4f8a8c786b58153761886ce16fad2275 | LizethPatino/Python_3_Fundamentos | /operadorAsignacion.py | 370 | 3.78125 | 4 | "operadores de asignación"
numero = 2
"Esto es igual a decir que numero + 9 = numero"
numero += 9
print(numero)
"operadores de identidad"
fruta1 = ["pera", "manzana", "fresa"]
fruta2 = ["uva","fresa", "durazno"]
fruta4 = "manzana"
fruta3 = fruta1
print(fruta3 is fruta1)
fruta3.append("limon")
print(fruta3)
print(fruta4 in fruta1)
|
69293c00e6adeba4d88a889b0f563516d904ea40 | Chritian92/AT06_API_Testing | /ChristianGalarza/Python/Session2/Practice1OfNextSlide.py | 369 | 4.1875 | 4 | print("Example: This is my web page http://holamundo.html ")
text = input('Enter a String with a url please ')
print("*****************************************************")
def valid_link(text):
end_url = text.split(" ")
for url in end_url:
if url.lower().startswith('http://'):
print("Is a valid url {} ".format(url))
valid_link(text)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.