blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
e5654460c1849e1bc7930a70bab8e82a17433a51 | akhvn/Matlab | /Dynamic chaos/1_1.py | 280 | 3.546875 | 4 | import matplotlib.pyplot as plt
import numpy as np
from random import*
f=lambda x:4*r*x*(1-x)
x0=random()
r=float(input('введите r:'))
x=[f(x0)]
n=[i+1 for i in range(60)]
for i in range(59):
x.append(f(x[-1]))
ax = plt.subplots()
plt.plot(n,x)
plt.show()
|
8d2074377552df05d8c63082d8a74953ebe6d575 | chaosWsF/Python-Practice | /leetcode/1021_remove_outermost_parentheses.py | 1,955 | 3.59375 | 4 | """
A valid parentheses string is either empty (""), "(" + A + ")", or A + B, where A and B are valid parentheses
strings, and + represents string concatenation. For example, "", "()", "(())()", and "(()(()))" are all valid
parentheses strings.
A valid parentheses string S is primitive if it is nonempty, and there does not exist a way to split it into
S = A+B, with A and B nonempty valid parentheses strings.
Given a valid parentheses string S, consider its primitive decomposition: S = P_1 + P_2 + ... + P_k, where P_i
are primitive valid parentheses strings.
Return S after removing the outermost parentheses of every primitive string in the primitive decomposition of S.
Example 1:
Input: "(()())(())"
Output: "()()()"
Explanation:
The input string is "(()())(())", with primitive decomposition "(()())" + "(())".
After removing outer parentheses of each part, this is "()()" + "()" = "()()()".
Example 2:
Input: "(()())(())(()(()))"
Output: "()()()()(())"
Explanation:
The input string is "(()())(())(()(()))", with primitive decomposition "(()())" + "(())" + "(()(()))".
After removing outer parentheses of each part, this is "()()" + "()" + "()(())" = "()()()()(())".
Example 3:
Input: "()()"
Output: ""
Explanation:
The input string is "()()", with primitive decomposition "()" + "()".
After removing outer parentheses of each part, this is "" + "" = "".
Note:
1. S.length <= 10000
2. S[i] is "(" or ")"
3. S is a valid parentheses string
"""
class Solution:
def removeOuterParentheses(self, S: str) -> str:
res, stack = [], 0
for s in S:
if s == '(':
if stack > 0:
res.append(s)
stack += 1
else:
stack -= 1
if stack > 0:
res.append(s)
return ''.join(res)
|
40af9b8278fb77a315be3df2e2d595748202493d | Leticiamkabu/globalCode-18 | /advPython/Map,Filter & Lambda/lambda.py | 481 | 4.53125 | 5 | print("Using the Lambda Function: \n")
# the Lambda Function also called an anonymous func,
# does not have a name and is called implicitly
originalList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
#using the filter func & a Lambda Function, each value in originalList
#is tested even if true add to the newList
newlist = list(filter(lambda x: x % 2 == 0,originalList))
#print the two lists
print("The original list: {}".format(originalList))
print("The filtered list: {}".format(newlist)) |
1d56cf702ca94e61628c3d9a1867114b2421b32b | shenbanakshetha24/set5 | /4.py | 66 | 3.609375 | 4 | c=int(input())
if(c>1 and c<10):
print("yes")
else:
print("no")
|
dd8cf4a07fc72eadf74bb3ae948c99af0d861e40 | hanyanru0719/vip5 | /20200314homework.py | 2,289 | 4.09375 | 4 | # Python练习题:
# 1、打印小猫爱吃鱼,小猫要喝水
# class Animal(object):
# name = 'cat'
# def eat(self,food):
# print("%s爱吃%s"%(self.name,food))
#
# def drink(self):
# print("%s要喝水"%(self.name))
#
# a =Animal()
# a.name = '小猫'
# a.eat('鱼')
# a.drink()
# 2、小明爱跑步,爱吃东西。
# 1)小明体重75.0公斤
# 2)每次跑步会减肥0.5公斤
# 3)每次吃东西体重会增加1公斤
# 4)小美的体重是45.0公斤
# class Person(object):
# def __init__(self,name,weight):
# self.name = name
# self.weight = float(weight)
# def run(self,n):
# for i in range(1,n+1):
# self.weight -= 0.5
# print('%s跑步%d次,体重是%s'%(self.name,i,self.weight))
# def eat(self,m):
# for j in range(1,n+1):
# self.weight += 1
# print('%s吃东西%d次,体重是%s'%(self.name,j,self.weight))
#
#
# n = int(input('请输入跑步次数:'))
# m = int(input('请输入吃东西次数:'))
# a = Person('小明','75')
# a.run(n)
# a.eat(m)
# 3、摆放家具
# 需求:
# 1).房子有户型,总面积和家具名称列表
# 新房子没有任何的家具
# 2).家具有名字和占地面积,其中
# 床:占4平米
# 衣柜:占2平面
# 餐桌:占1.5平米
# 3).将以上三件家具添加到房子中
# 4).打印房子时,要求输出:户型,总面积,剩余面积,家具名称列表
# class House(object):
#
# def __init__(self,huxing,area):
#
# self.huxing = huxing
# self.area = float(area)
# self.jiajulist = []
#
#
#
# def Addjiaju(self,jiaju):
#
# self.jiajulist.append(jiaju)
# if jiaju == '床':
# self.area -= 4
# elif jiaju == '衣柜':
# self.area -= 2
# else:
# self.area -= 1.5
# print(self.huxing,self.area,self.jiajulist)
#
#
# a =House('两居一卫',90)
# listj = ['床','衣柜','餐桌']
# for i in listj :
# a.Addjiaju(i)
#
# 4.士兵开枪
# 需求:
# 1).士兵瑞恩有一把AK47
# 2).士兵可以开火(士兵开火扣动的是扳机)
# 3).枪 能够 发射子弹(把子弹发射出去)
# 4).枪 能够 装填子弹 --增加子弹的数量
|
afd33a280b7622b0d724c2aff9f73d328e607570 | Laharah/advent_of_code | /2017/day07.py | 1,817 | 3.5625 | 4 | from common import Input
import re
class Node:
def __init__(self, name, weight):
self.name = name
self.weight = weight
self.children = []
class UnbalancedTree(Exception):
pass
def build_tree(base, parents, weights):
tree = Node(base, weights[base])
for n in (name for name, p in parents.items() if p == base):
tree.children.append(build_tree(n, parents, weights))
return tree
def weigh_balanced_tree(tree):
if not tree.children:
return tree.weight
weights = {n: weigh_balanced_tree(n) for n in tree.children}
weights_list = list(weights.values())
if all(w == weights_list[0] for w in weights_list):
return tree.weight + sum(weights_list)
weight_count = lambda x: weights_list.count(x)
odd_weight, correct_weight, *_ = sorted(weights_list, key=weight_count)
diff = odd_weight - correct_weight
odd_child = [w for w in weights if weights[w] == odd_weight][0]
message = 'Tree is unbalanced: "{}" weighs {}, but should weigh {}.'
message = message.format(odd_child.name, odd_child.weight, odd_child.weight - diff)
raise UnbalancedTree(message)
if __name__ == '__main__':
parent = {}
weight = {}
for line in Input(7):
m = re.match(r'^(\w+) \((\d+)\)(?: -> (.*))?$', line)
name, w, children = m.groups()
weight[name] = int(w)
if name not in parent:
parent[name] = None
if not children: continue
for c in children.split(', '):
parent[c] = name
base = [n for n in parent if parent[n] is None][0]
print('Base Program:', base)
tree = build_tree(base, parent, weight)
try:
w = weigh_balanced_tree(tree)
except UnbalancedTree as e:
print(e)
else:
print('Tree weighs', w)
|
25144b43aa4bb60a48d77d12febddea63229d0b1 | robgoyal/CodingChallenges | /HackerRank/Algorithms/Strings/0-to-10/hackerrankInString.py | 840 | 4.3125 | 4 | # Name: hackerrankInString.py
# Author: Robin Goyal
# Last-Modified: November 17, 2017
# Purpose: Determine if 'hackerrank' is in a string in the correct order
def hackerrankInString(s):
'''
s: string
return: "YES" or "NO"
YES if hackerrank is in s in the order of the characters
in hackerrank
'''
index = 0
string_to_match = "hackerrank"
for char in s:
# Only increment index if it matches in order
if char == string_to_match[index]:
index += 1
# Break out if string has been matched
if index == len(string_to_match):
return "YES"
return "NO"
def main():
q = int(input().strip())
for a0 in range(q):
s = input().strip()
result = hackerrankInString(s)
print(result)
if __name__ == "__main__":
main() |
7b9409134ca6ff7238a9ade74740fce3d670aa51 | SAURAVBORAH22/toxic_comment_classifier | /app.py | 3,915 | 3.765625 | 4 | import streamlit as st
import pandas as pd
from PIL import Image
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
import pickle
import numpy as np
def main():
activities=['About','Toxic Comment Classification System','Developer']
option=st.sidebar.selectbox('Menu Bar:',activities)
if option=='About':
html_temp = """
<div style = "background-color: yellow; padding: 10px;">
<center><h1>ABOUT PROJECT</h1></center>
</div><br>
"""
st.markdown(html_temp, unsafe_allow_html=True)
st.title("Problem Statement and Background")
st.subheader("The background for the problem originates from the multitude of online forums, where-in people participate actively and make comments. As the comments some times may be abusive, insulting or even hate-based, it becomes the responsibility of the hosting organizations to ensure that these conversations are not of negative type. The task was thus to build a model which could make prediction to classify the comments into various categories. Consider the following examples :")
image=Image.open('1.png')
st.image(image,use_column_width=True)
st.header("The exact problem statement was thus as below:")
st.subheader("Given a group of sentences or paragraphs, used as a comment by a user in an online platform, classify it to belong to one or more of the following categories — toxic, severe-toxic, obscene, threat, insult or identity-hate with either approximate probabilities or discrete values (0/1).")
st.header("Multilabel vs Multiclass classification ?")
st.subheader("As the task was to figure out whether the data belongs to zero, one, or more than one categories out of the six listed above, the first step before working on the problem was to distinguish between multi-label and multi-class classification.")
st.subheader("In multi-class classification, we have one basic assumption that our data can belong to only one label out of all the labels we have. For example, a given picture of a fruit may be an apple, orange or guava only and not a combination of these.")
st.subheader("In multi-label classification, data can belong to more than one label simultaneously. For example, in our case a comment may be toxic, obscene and insulting at the same time. It may also happen that the comment is non-toxic and hence does not belong to any of the six labels.")
st.subheader("Hence, I had a multi-label classification problem to solve. The next step was to gain some useful insights from data which would aid further problem solving.")
elif option=='Toxic Comment Classification System':
st.title("Toxic Comment Classification System")
#image=Image.open('Magnify_Monitoring.jpg')
#st.image(image,use_column_width=True)
f=open("final_model.pkl", "rb")
model = pickle.load(f)
v= pickle.load(f)
st.write("""final project""")
st.write('---')
st.header('Specify Input Parameters')
text = st.text_input("input text")
lis=[]
for i in range(6):
lis.append(model[i].predict_proba(v.transform([text]))[:, 1])
list=['toxic', 'severe_toxic', 'obscene', 'threat', 'insult', 'identity_hate']
st.header('Output')
for i in range(6):
st.subheader(list[i])
st.write(lis[i])
st.write('---')
elif option=='Developer':
st.balloons()
st.title('Prepared by:-')
st.header('SAURAV BORAH')
st.subheader('Machine Learning Intern, Technocolab')
st.subheader('Source Code:-')
st.write('https://github.com/SAURAVBORAH22/toxic-comment-classifier')
if __name__ == '__main__':
main()
|
f000f33571fe758b20ec8c999d3e5fd4e3e4c814 | i386net/w3resource | /Python basic part I/22.py | 161 | 3.84375 | 4 | # 22. Write a Python program to count the number 4 in a given list.
def counter(lst):
return lst.count(4)
l = [4, 1 ,2 , 4, 6 , 5]
c = counter(l)
print(c) |
b571c6441b37188abff2adf2cfd3ec377429d745 | masipcat/Informatica | /Q1/s6/EOT-46.py | 658 | 3.859375 | 4 | def foraVocals(cadena):
r = ""
vocals = "aeiouAEIOU"
for char in cadena:
if char not in vocals:
r += char
return r
def modificaCadena(cadena):
count = len(cadena)
i = 0
r = ""
a = "bogeria"
while i < count:
r += cadena[i:i+3] + a
print "(", i,")", r
i += 3
return r
cadena = raw_input("Introdueix una cadena: ")
cadena = foraVocals(cadena)
print "El primer pas genera:", cadena, "\n"
start = input("Introdueix el primer index de la subcadena: ")
end = input("Introdueix el segon index de la subcadena: ")
cadena = cadena[start:end]
print "El segon pas genera:", cadena
print "La teva cadena resultant es:", modificaCadena(cadena)
|
f725419b9eef3279a3cecd3f65c995c3fe49ff2e | Jbiloki/Cryptography | /caesar.py | 515 | 3.796875 | 4 | #!/usr/bin/python3
class Caesar:
def __init__(self):
self.key = None
return
def setKey(self, key):
try:
self.key = int(key)
return True
except:
print("Key is not able to convert to int")
return False
def encrypt(self, text):
ct = ''
for i in range(len(text)):
ct += chr((((ord(text[i]) + self.key) - 97) % 26) + 97)
print(ct)
def decrypt(self, text):
pt = ''
for i in range(len(text)):
pt += chr((((ord(text[i]) - (self.key%26)) - 97) % 26) + 97)
print(pt)
|
74e9fe36f9bbdb2a949d222d3bf677ab07137225 | nevesrye/project_euler | /euler005.py | 626 | 3.8125 | 4 | ##Smallest multiple
##Problem 5
##2520 is the smallest number that can be divided by
##each of the numbers from 1 to 10 without any remainder.
##
##What is the smallest positive number that
##is evenly divisible by all of the numbers from 1 to 20?
def sm(n):
for i in range(n, factorial(n) + 1, n):
if multiple(i, n):
return i
return -1
def multiple(x, n):
for i in range(1, n):
if x % i != 0:
return False
return True
def factorial(n):
if n > 1: return n * factorial(n - 1)
elif n >= 0: return 1
else: return -1
print (sm(20))
|
8d6f0060047cbcf9241535afb31f35c9d25afc75 | kitbitsks/ib_Solutions | /ib_linkedList_reverseLinkList2.py | 1,434 | 3.96875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param A : head node of linked list
# @param B : integer
# @param C : integer
# @return the head node in the linked list
def reverseBetween(self, A, B, C):
middleList = ListNode(None)
firstList = ListNode(None)
lastList = ListNode(None)
headOfAllList = ListNode(None)
headOfAllList.next = firstList
headOfLastList = ListNode(None)
headOfLastList.next = lastList
count = 0
temp = A
while temp is not None:
count += 1
if count >= B and count <= C :
new_node = ListNode(temp.val)
new_node.next = middleList.next
middleList.next = new_node
if count < B:
firstList.next = ListNode(temp.val)
firstList = firstList.next
if count > C:
lastList.next = ListNode(temp.val)
lastList = lastList.next
temp = temp.next
if count == 1:
return ListNode(1)
firstList.next = middleList.next
while middleList.next is not None:
middleList = middleList.next
middleList.next = (headOfLastList.next).next
headOfAllList = headOfAllList.next
return headOfAllList.next |
318d9e1a596fc7601ecc6384ddae6f159b5a9e5f | danielraf23/pythonProject | /DanielRaf/EX_1.6.py | 103 | 4.1875 | 4 | radius=int(input("circle_radius: "))
PI=3.141
h=2*PI*radius
s=PI*radius*radius
print(h)
print(s)
|
34116335da09a7c4766811e305de502b9bc8f121 | 13950090228/Web-Python-LearningNotes | /Web+Python学习笔记/day12(函数名使用和闭包和迭代器)/作业练习.py | 184 | 3.75 | 4 | n=int(input('请输入要几行:'))
for i in range(1,n+1):
for j in range(2*n-2*i):
print('',end=' ')
for k in range(2*i-1):
print('*',end=' ')
print('')
|
3bfe60a6dbc1b384b7bf511d45bdce52dc2bdb3a | oneytlam/mlwithpython | /mouse_control_with_head.py | 2,207 | 3.5 | 4 | # Adapted from https://www.analyticsvidhya.com/blog/2020/12/deep-learning-with-google-teachable-machine/
# Import necessary modules
import numpy as np
import cv2
from time import sleep
import tensorflow.keras
from keras.preprocessing import image
import tensorflow as tf
import pyautogui
# Using laptop's webcam as source of video
cap = cv2.VideoCapture(0)
# Labels - The various possibilities
labels = ['Neutral','Up','Down','Left','Right']
# Loading the model weigths
model = tensorflow.keras.models.load_model('keras_model.h5')
while True:
success, image = cap.read()
if success == True:
# Necessary to avoid conflict between left and right
image = cv2.flip(image,1)
cv2.imshow("Frame",image)
#Take pic
image_array = cv2.resize(image,(224,224))
# Normalize the image
normalized_image_array = (image_array.astype(np.float32) / 127.0) - 1
# Load the image into the array
data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)
data[0] = normalized_image_array
# run the inference
prediction = model.predict(data)
print(prediction)
# Map the prediction to a class name
predicted_class = np.argmax(prediction[0], axis=-1)
predicted_class_name = labels[predicted_class]
# Using pyautogui to get the current position of the mouse and move accordingly
current_pos = pyautogui.position()
current_x = current_pos.x
current_y = current_pos.y
print(predicted_class_name)
if predicted_class_name == 'Neutral':
sleep(1)
elif predicted_class_name == 'Left':
pyautogui.moveTo(current_x-80,current_y,duration=1)
sleep(1)
elif predicted_class_name == 'Right':
pyautogui.moveTo(current_x+80,current_y,duration=1)
sleep(1)
elif predicted_class_name == 'Down':
pyautogui.moveTo(current_x,current_y+80,duration=1)
sleep(1)
elif predicted_class_name == 'Up':
pyautogui.moveTo(current_x,current_y-80,duration=1)
sleep(1)
# Release open connections
cap.release()
cv2.destroyAllWindows()
|
ee055afe4b6b9224f2e2980165344f9145867da6 | kanglicheng/Adventure-in-Data-Science | /Data-Structures-and-Algorithms/quickSort.py | 1,345 | 4.03125 | 4 | def quickSort(array):
helper(array, 0, len(array)-1)
return array
# Recursion
def helper(array, first, last): # need first & last index as func argument
if first >= last:
return
else:
splitpoint = partition(array, first, last)
helper(array, first, splitpoint-1)
helper(array, splitpoint+1, last)
# Partition Operation: put pivotvalue into right place; return the index (splitpoint)
def partition(array, first, last):
pivotvalue = array[first]
leftmark = first + 1
rightmark = last
done = False
while not done:
while leftmark <= rightmark and array[leftmark] <= pivotvalue:
leftmark += 1
while rightmark >= leftmark and array[rightmark] >= pivotvalue:
rightmark -= 1
if rightmark < leftmark:
done=True
else:
# swap rightmark element with leftmark element
array[leftmark], array[rightmark] = array[rightmark], array[leftmark]
# swap rightmark element with pivot element(which is the first element)
array[first], array[rightmark] = array[rightmark], array[first]
# return pivot index (which equals to the rightmark after partition)
return rightmark
test = [21, 4, 1, 3, 9, 20, 25, 6, 21, 14]
print quicksort(test)
|
5bf2471afd3b6f0ba45d51fcfc043ee9f1e39b22 | juhyun0/python_turtle5 | /Korean_flag.py | 308 | 3.75 | 4 | import turtle
def draw_shape(radius,color1):
t.left(270)
t.width(3)
t.color("black",color1)
t.begin_fill()
t.circle(radius/2.0,-180)
t.circle(radius,180)
t.left(180)
t.circle(-radius/2.0,-180)
t.end_fill()
t=turtle.Turtle()
t.reset()
draw_shape(200,"red")
t.setheading(180)
draw_shape(200,"blue")
|
af383752efa60c3101c45149672df6df3d8fa3c5 | Rukshani/udacity-cs373 | /hw3.py | 1,091 | 3.78125 | 4 | #! /usr/bin/env python
# 1. empty cell
print "what is the probability that zero particles are in stat A?"
print "4 states, N uniform particles"
print "when N = 1, 4, 10?"
def pN(N):
return (3./4.)**N
print pN(1.), pN(4.), pN(10.)
# 2. motion question
print "consider 4 states, [[a b],[c d]]. motion step"
print "50% = p(move horizontally), 50% = p(vertically), 0% diagonal"
print "never stays in same cell"
print "after 1 step, how many do we expect in each cell,"
print "given we start with [[5 3] [3 1]]?"
print "also what do we expect after infinite steps?"
print "A = .5 * 3 + .5 * 3 = ", .5 * 3 + .5 * 3
print "B = .5 * 5 + .5 * 1 = ", .5 * 5 + .5 * 1
print "C = .5 * 1 + .5 * 5 = ", .5 * 1 + .5 * 5
print "D = .5 * 3 + .5 * 5 = ", .5 * 3 + .5 * 3
print "3. single particle"
print "particle filter with N=1 particle. what happens?"
print "works fine"
print "ignores robot measurements"
print "ignores robot motion"
print "it likely fails"
print "none of the above"
print "answer: ignores robot measurements and it likely fails"
print "4. circular motion"
print "see hw3.4.py"
|
56cfd653835b8faaff928eef401032ccd4e46f5c | s21911-pj/ASD | /Heap sort.py | 1,358 | 3.75 | 4 | import datetime
import random
def heapify(arr, n, i):
largest = i
l = 2 * i + 1
r = 2 * i + 2
if l < n and arr[i] < arr[l]:
largest = l
if r < n and arr[largest] < arr[r]:
largest = r
if largest != i:
arr[i], arr[largest] = arr[largest], arr[i]
heapify(arr, n, largest)
def build_heap(arr):
n = len(arr)
for i in range(n // 2-1, -1, -1):
heapify(arr, n, i)
def heapSort(arr):
build_heap(arr)
n = len(arr)
for i in range(n - 1, 0, -1):
arr[i], arr[0] = arr[0], arr[i]
heapify(arr, i, 0)
arr = [random.randint(1, 50000) for _ in range(50000)]
n = len(arr)
start_time = datetime.datetime.now()
heapSort(arr)
end_time = datetime.datetime.now()
elapsed_time = end_time - start_time
print(elapsed_time.seconds, ":", elapsed_time.microseconds)
print("end first sorting")
start_time = datetime.datetime.now()
arr.reverse()
start_time = datetime.datetime.now()
heapSort(arr)
end_time = datetime.datetime.now()
elapsed_time = end_time - start_time
print(elapsed_time.seconds, ":", elapsed_time.microseconds)
print("end second sorting")
arr.sort()
start_time = datetime.datetime.now()
heapSort(arr)
end_time = datetime.datetime.now()
elapsed_time = end_time - start_time
print(elapsed_time.seconds, ":", elapsed_time.microseconds)
print("end third sorting")
|
48f5ecb3097d45abe4d87081c94ce5124579d332 | acid9reen/Artezio | /Lesson_8_http_regexp/task2.py | 622 | 4.09375 | 4 | '''Convert currency from one to another'''
import requests
def converter(amount: float, from_curr: str, to_curr: str) -> float:
'''Convert currency from one to another'''
url = 'https://api.exchangerate-api.com/v4/latest/' \
+ from_curr
response = requests.get(url)
data = response.json()
result = amount * data["rates"][to_curr]
return result
def main():
'''Call converter function with user amount value'''
amount = int(input("Enter the amount to convert from USD to RUB: "))
print(f'{converter(amount, "USD", "RUB"):.2f}')
if __name__ == '__main__':
main()
|
7723977ccf4e5c414024d6541cc271d2f474f991 | ivoryli/myproject | /class/phase1/day03/exercise01.py | 716 | 3.78125 | 4 | # n = input("季节")
#
# if n == '春':
# print("1,2,3")
# elif n == '夏':
# print("4,5,6")
# elif n == '秋':
# print("7,8,9")
# elif n == '冬':
# print("10,11,12")
# else:
# print("请输入正确季度")
#-----------------------------------------
'''
输入月份得天数
'''
# n = int(input("输入月份"))
#
# if n < 1 or n > 12:
# print("请输入正确月份")
#
# elif n == 2:
# print("28")
#
# elif n == 4 or n == 6 or n == 9 or n ==11:
# print("30")
#
# else:
# print("31")
#------------------------------------------------
n1 = 8
n2 = 6
n3 = 10
n4 = 5
n = 0
if n < n1:
n = n1
if n < n2:
n = n2
if n < n3:
n = n3
if n < n4:
n = n4
print(n)
|
56840ca9ef184c643f6db59c5eed9c0b634fd16a | cu-swe4s-fall-2019/trees-mchifala | /binary_tree.py | 1,293 | 3.9375 | 4 | import sys
sys.setrecursionlimit(10**6)
class Node:
"""
This class serves as the nodes of a tree.
Attributes:
- left(Node): the left child of the node
- right(Node): the right child of the node
- key(int): the key of the node
- value(varies): the value of the node
"""
def __init__(self, key, value=None, left=None, right=None):
"""
This constructor initializes the node
"""
self.left = None
self.right = None
self.key = key
self.value = value
def insert(root, key, value=None):
new_node = Node(key, value)
if root is None:
root = new_node
else:
insert_helper(root, new_node)
def insert_helper(root, node):
if root is None:
root = node
elif root.key < node.key:
if root.right is None:
root.right = node
else:
insert_helper(root.right, node)
else:
if root.left is None:
root.left = node
else:
insert_helper(root.left, node)
def search(root, key):
while root is not None and key != root.key:
if key < root.key:
root = root.left
else:
root = root.right
if root:
return root.value
else:
return None
|
990a41c55bb8b8b7b288a6c2f6887911cec8e5ef | Aritra222/area_python | /index.py | 932 | 4.25 | 4 | x = "The area of Circle"
y = "The area of Rectanngle"
z = "The area of square"
t = "The area of triangle"
g = ''
print (x)
print (g*6)
a = 6
print ("Supoose radius of circle is :" , a)
areaofcircle = 3.14*a*a
print (g*6)
print ("Area of Circle is:",areaofcircle)
print (g*6)
print (y)
b= 12
c= 23
d=b*c
print (g*6)
print ("Suppose the height of rectangle is :", b)
print (g*2)
print ("supoose the width of rectangle", c)
print (g*6)
print ("The area of rectangle is :", d)
print (g*6)
print (t)
t1=6
t2=5.21
areaoftriangle = 0.5*t1*t2
print (g*2)
print ("supoose the base of triangle is :", t1)
print (g*2)
print ("Supoose the height of triangle is :",t2)
print (g*6)
print ("The area of triangle :", areaoftriangle)
print (g*6)
print (z)
s1=4.5687
areaofsquare=s1*s1
print (g*3)
print ("Suppose the side of the square is",s1)
print ("The area of square is ", areaofsquare)
#End of Program
|
73a0e00ec9e91543f23b0363f59bf33844cce67f | PalashMatey/Project_BigData | /NLTK_modules/final_chunk.py | 960 | 3.734375 | 4 | '''
Basically implies that, you can use some part of data and ignore the rest.
A method of elimination, unlike that of chunking.
Chunking is a method of selection.
You chink something from a chunk basically
'''
import nltk
from nltk.corpus import state_union
from nltk.tokenize import PunktSentenceTokenizer
from nltk import pos_tag
t = []
with open("TextFiles/Kim_Kardashian_Train.txt","r") as f:
for p in f.readlines():
t.append(p)
train_text = ' '.join(t).decode('utf-8')
s = []
with open("TextFiles/Kim_Kardashian_Sample.txt","r") as f:
for p in f.readlines():
s.append(p)
sample_text = ' '.join(s).decode('utf-8')
def process_content():
try:
tagged_sent = pos_tag(train_text.split())
propernouns = [word for word,pos in tagged_sent if pos == 'NNP']
for p in propernouns[:100]:
t = open("Kim_Kardashian_Chunk.txt","a")
t.write('\n')
t.write(p)
t.close()
except Exception as e:
print(str(e))
process_content()
|
9cccd97302b4d7fcdf94f788421d0b02a4c5f715 | manishrana93/python_trg | /33_is_prime.py | 480 | 3.90625 | 4 | from _typeshed import StrPath
def is_prime(n):
start=2
stop=n-1
i= start
while ( i <= stop):
if n % i ==0:
return False
i = i + 1
return True
def print_is_prime_status(n):
if is_prime(n):
print(f"{n} is a prime number")
else:
print(f"{n} is not a prime number")
def main():
print_is_prime_status(2)
print_is_prime_status(5)
print_is_prime_status(7)
print_is_prime_status(8)
main()
|
95e73dc7932734b4d2df7cd5ab11a6936c841af5 | eddiegz/Personal-C | /DMOJ/CCC/telemaker or not.py | 177 | 3.75 | 4 | a=int(input())
b=int(input())
c=int(input())
d=int(input())
if a==9 or a==8:
if b==c:
if d==9 or d==8:
print('ignore')
else:
print('answer') |
eb46aa65ba9f86627bb369bac2072aaf8cbca4de | Bangatto/Voting_Simulator | /instant_run_off.py | 3,927 | 3.6875 | 4 | # COMP 202 A3
# Name GATTUOCH KUON
# ID:260-877-635
from single_winner import *
################################################################################
def votes_needed_to_win(ballots, num_winners):
'''
(list, int)-> int
want to return the number of votes a candidate need to win using the Droop Quota.
>>> votes_needed_to_win([{'CPC':3, 'NDP':5}, {'NDP':2, 'CPC':4}, {'CPC':3, 'NDP':5}], 1)
2
>>> votes_needed_to_win(['g']*20, 2)
7
'''
#the length of the ballots represent total votes which i divide number of winners plus one
# add the floor division(// rounds the decimal down) of it to one
return (len(ballots)//(num_winners + 1)) + 1
def has_votes_needed(result, votes_needed):
'''
(dict, int)-> bool
We want to return a Boolean whether a candidate with most votes in the election,
has at least votes needed.
>>> has_votes_needed({'NDP': 4, 'LIBERAL': 3}, 4)
True
>>> has_votes_needed({'NDP': 5, 'LIBERAL': 8}, 6)
True
>>> has_votes_needed({'NDP': 2, 'LIBERAL': 3}, 4)
False
'''
# if my get_winner value in the helpers function is greater or equal to votes
# -needed i return true else i return false
if (result):
return result[get_winner(result)] >= votes_needed
else:
return False
################################################################################
def eliminate_candidate(ballots, to_eliminate):
'''
(list)-> list
want to return a list of ranked ballots where all the candidates,
in to_eliminate have been removed.
If all the candidates on the ballot have eliminated the return an
empty list.
>>> eliminate_candidate([['NDP', 'LIBERAL'], ['GREEN', 'NDP'], ['NDP', 'BLOC']], ['NDP', 'LIBERAL'])
[[], ['GREEN'], ['BLOC']]
'''
new_ballots = []
#loop through each ballot in the ballots
for ballot in ballots:
new_ballot =[]
#loop through each cadidate in each ballot.
for candidate in ballot:
if candidate not in to_eliminate:
new_ballot.append(candidate) # if the candidate has not been eliminated, we append it to the ballot.
new_ballots.append(new_ballot) #append all the ballot into the main ballots
return new_ballots
################################################################################
def count_irv(ballots):
'''
(list)-> dict
We want to get the winner and the number of votes the candidate get after counting with Instant Run-off Votes.
>>> count_irv([['NDP'],['LIBERAL','NDP'],['BLOC', 'GREEN', 'NDP'], ['LIBERAL', 'CPC'], ['LIBERAL', 'GREEN']])
{'NDP': 1, 'LIBERAL': 3, 'BLOC': 1, 'GREEN': 0, 'CPC': 0}
>>> count_irv([['LIBERAL', 'NDP'], ['NDP', 'GREEN','LIBERAL'], ['LIBERAL', 'GREEN']])
{'LIBERAL': 2, 'NDP': 1, 'GREEN': 0}
>>> count_irv([['LIBERAL', 'NDP'], ['GREEN', 'NDP'], ['LIBERAL', 'GREEN', 'CPC'], ['LIBERAL', 'CPC' , 'GREEN']])
{'LIBERAL': 3, 'NDP': 0, 'GREEN': 1, 'CPC': 0}
'''
# count first winners
# if winner has majority we return the winner
# if not we eliminate the last place and make the second place candidate the first choice
winner_results = count_first_choices(ballots)
winner_found = False # to keep track of While Loop to avoid infinite loop
while not winner_found:
if has_votes_needed(winner_results, votes_needed_to_win(ballots,1)):
winner_found = True
return winner_results
#if we have no winner yet, we remove the last place and go back to the first statement execution
else:
last_place_remove = last_place(winner_results)
#update the ballots after the last place is remove
ballots = eliminate_candidate(ballots,last_place_remove)
################################################################################
if __name__ == '__main__':
doctest.testmod()
|
9426a9009201c32985225eb8b931df787178ce60 | Akshata2704/APS-2020 | /58-strings_anagram.py | 450 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 28 23:33:52 2020
@author: AKSHATA
"""
def is_anagram(a,b):
a=list(a)
b=list(b)
if(len(a)!=len(b)):
return 0
else:
a=sorted(a)
b=sorted(b)
for i in range(0,len(a)):
if(a[i]!=b[i]):
return 0
return 1
a=input()
b=input()
if(is_anagram(a,b)):
print("YES")
else:
print("NO")
|
e542a324945ea7f354ddbfe6dd39448a80ed77fb | TyDunn/hackerrank-python | /CTCI/queue_via_stacks.py | 906 | 3.859375 | 4 | #!/bin/python3
import sys
class Stack:
def __init__(self):
self.items = []
def empty(self):
return not self.items
def push(self, item):
self.items.append(item)
def pop(self):
val = self.items.pop()
return val
class Queue:
def __init__(self):
self.new_stack = Stack()
self.old_stack = Stack()
def size(self):
return len(self.new_stack) + len(self.old_stack)
def add(self, item):
self.new_stack.push(item)
def _shift_stacks(self):
if self.old_stack.empty():
while not self.new_stack.empty():
self.old_stack.push(self.new_stack.pop())
def peek(self):
self._shift_stacks()
return self.old_stack[-1]
def remove(self):
self._shift_stacks()
return self.old_stack.pop()
if __name__ == '__main__':
queue = Queue()
queue.add(1)
queue.add(2)
queue.add(3)
print(queue.remove())
print(queue.remove())
print(queue.remove()) |
8563b8d82c7e8acdb12baaa0172cb68d8c11a9c5 | saikatsahoo160523/python | /Ass17.py | 449 | 4 | 4 | # 17. With two given lists [1,3,6,78,35,55] and [12,24,35,24,88,120,155], write a program to make a list whose elements are intersection of the above given lists.
def intersect(a, b):
""" return the intersection of two lists """
return list(set(a) & set(b))
if __name__ == "__main__":
a = [1,3,6,78,35,55]
b = [12,24,35,24,88,120,155]
print intersect(a, b)
''' OUTPUT :
[root@python PythonPrograms]# python Ass17.py
[35]
'''
|
480be8d49cd8bb67222eaa4611a3b3d00544e4ca | TSAI-HSIAO-HAN/Signal_Processing | /animation/tryBar.py | 1,002 | 3.59375 | 4 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.widgets import Slider
TWOPI = 2*np.pi
fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.2, left=0.3)
t = np.arange(0.0, TWOPI, 0.001)
s = np.sin(t)
l = plt.plot(t, s)
redDot, = plt.plot([0], [np.sin(0)], 'ro')
ax = plt.axis([0,TWOPI,-1,1])
axcolor = 'lightgoldenrodyellow'
om1 = plt.axes([0.25, 0.1, 0.65, 0.03], facecolor = axcolor)
som1 = Slider(om1, r'$\omega_1$', 0, TWOPI, valinit = 0)
def spv(i):
return (i, np.sin(i))
def update(val):
s1 = som1.val
x,y = spv(s1)
redDot.set_xdata(x)
redDot.set_ydata(y)
fig.canvas.draw_idle()
som1.on_changed(update)
def animate(i):
redDot.set_data(i, np.sin(i))
return redDot,
# create animation using the animate() function
#myAnimation = animation.FuncAnimation(fig, animate, frames=np.arange(0.0, TWOPI, 0.1), \
# interval=10, blit=True, repeat=True)
plt.show()
|
88e7637ece727d1fd45984d0423645847a7c09bf | frankieliu/problems | /leetcode/python/403/sol.py | 1,011 | 3.890625 | 4 |
Elegant Python Simple Solution
https://leetcode.com/problems/frog-jump/discuss/88887
* Lang: python3
* Author: vimukthi
* Votes: 0
class Solution(object):
def canCross(self, stones):
map = {val:idx for idx, val in enumerate(stones)}
visited = {}
return self.jump(1, 1, stones[-1], map, visited)
def jump(self, current, last_step, goal, map, visited):
if current not in map:
return False
if current == goal:
return True
if (current, last_step) in visited:
return visited[(current, last_step)]
can_go_forward = False
for next_step in [last_step - 1, last_step, last_step + 1]:
if next_step > 0:
can_go_forward = can_go_forward or self.jump(current + next_step, next_step, goal, map, visited)
visited[(current, last_step)] = can_go_forward
return can_go_forward
|
107ca69346d27a16b7875277ac157b165fa63e91 | MarioLinJueSheng/VmixFootballControl | /a0.95.py | 24,843 | 3.53125 | 4 | # -*- coding: utf-8 -*
#!/usr/bin/env python3
#球队名
file = open('away.txt', mode='r', encoding="utf-8")
t = file.readlines() # 读取整个文件内容
file.close() # 关闭文件
away_list = [x.strip() for x in t]
file = open('home.txt', mode='r', encoding="utf-8")
a = file.readlines() # 读取整个文件内容
file.close() # 关闭文件
home_list = [x.strip() for x in a]
#读队名
file = open('team_name.txt', mode='r', encoding="utf-8")
teamname_home = file.readlines()[0].replace("\n", "") # 读取整个文件内容
file.close()
file = open('team_name.txt', mode='r', encoding="utf-8")
teamname_away = file.readlines()[1] # 读取整个文件内容
file.close() # 关闭文件
#比分
score_home = "0"
score_away = "0"
session_period = "上半场"
file = open('scoreboard.csv', mode='w+',encoding="utf-8")#写入csv文件
file.write(teamname_home + "," + str(score_home) + '\n' + teamname_away + "," + str(score_away) + '\n' + session_period)
file.close()
from tkinter import *
from tkinter import ttk
from tkinter import StringVar
class MY_GUI():
def __init__(self,init_window_name):
self.init_window_name = init_window_name
#设置窗口
def set_init_window(self):
self.init_window_name.title("绝笙Vmix字幕软件足球比赛控制面板 0.95(20190228) by:林嘉瑜") #窗口名
#self.init_window_name.geometry('800x580+10+10') #290 160为窗口大小,+10 +10 定义窗口弹出时的默认展示位置
self.init_window_name.resizable(0,0) #固定窗口大小
self.init_window_name["bg"] = "snow" #窗口背景色,其他背景色见:blog.csdn.net/chl0000/article/details/7657887
self.init_window_name.attributes("-alpha",1) #虚化,值越小虚化程度越高
self.frame_root = Frame(self.init_window_name,bg="red",width=1200,height=720)#最外层frame
self.canvas_root = Canvas(self.frame_root,bg="#f4e7fc",borderwidth=0)#canvas
self.frame_container = Frame(self.canvas_root,bg="#f7f7f7")#canvas内部frame
self.frame_root.grid(row=0,column=0)
self.frame_container.grid(row=0,column=0)
self.canvas_root.pack(side="left", fill="both", expand=True)
self.canvas_root.create_window((4,4), window=self.frame_container, anchor="nw")#canvas创建窗口
self.frame_root.pack_propagate(0)#固定大小
self.scrollbar_y = Scrollbar(self.frame_root)#创建scrollbar
self.canvas_root.config(yscrollcommand=self.scrollbar_y.set)#关联canvas
self.scrollbar_y.config(command=self.canvas_root.yview)#反相关联
self.scrollbar_y.pack(side="right", fill="y")
self.frame_container.bind("<Configure>", self.onFrameConfigure)#触发条件
self.sessionVar = StringVar()#
self.sessionVar.set("上半场")
self.scoreHomeVar = IntVar()#
self.scoreHomeVar.set(0)
self.scoreAwayVar = IntVar()#
self.scoreAwayVar.set(0)
'''各模块frame'''
#球队名单
self.frame_player_list = Frame(self.frame_container,bg="#E6E6F0")
self.frame_player_list.grid(row=0,column=0,padx=10,pady=10,sticky="NW")
#换人模块
self.frame_sub = Frame(self.frame_container,bg="#C3D7DF")
self.frame_sub.grid(row=25,column=0,padx=10,pady=10,sticky="NW")
#红黄牌模块
self.frame_red_yellow_card = Frame(self.frame_container,bg="#B1EDE7")
self.frame_red_yellow_card.grid(row=0,column=100,padx=10,pady=10,sticky="NW")
#记分板模块
self.frame_scoreboard = Frame(self.frame_container,bg="#E0D9CE")
self.frame_scoreboard.grid(row=25,column=100,padx=10,pady=10,sticky="NW")
#组件
'''名单显示'''
#主队名称
self.home_list_title = Label(self.frame_player_list, text= "主:"+teamname_home,font=('YaHei', 18), bg="#E6E6F0")
self.home_list_title.grid(row=2,column=0,sticky=W,rowspan=2,pady=8)
#客队名称
self.away_list_title = Label(self.frame_player_list, text= "客:"+teamname_away,font=('YaHei', 18), bg="#E6E6F0")
self.away_list_title.grid(row=2,column=38,sticky=W,rowspan=2,pady=8)
#主队名单
self.list_home = Listbox(self.frame_player_list, selectmode=SINGLE,height=len(home_list),bg ="#E9D2CD", bd=0,font=('YaHei', 14))
for item in home_list:
self.list_home.insert(END, item)
self.list_home.grid(row=4,column=0,rowspan=30, columnspan=8)
#客队名单
self.list_away = Listbox(self.frame_player_list, selectmode=SINGLE,height=len(away_list),bg ="#E9D2CD", bd=0,font=('YaHei', 14))
for item in away_list:
self.list_away.insert(END, item)
self.list_away.grid(row=4,column=38,rowspan=30, columnspan=8)
'''换人模块'''
#换人标题
self.sub_module_title = Label(self.frame_sub, text= "换人模块",font=('YaHei', 20), bg="#C3D7DF")
self.sub_module_title.grid(row=40,column=0,sticky=W,rowspan=2,pady=6)
self.sub_away_title = Label(self.frame_sub, text= "客队("+teamname_away+")换人",font=('YaHei', 14), bg="#C3D7DF")
self.sub_away_title.grid(row=60,column=0,sticky=W,rowspan=2,pady=1)
self.sub_away_out_title = Label(self.frame_sub, text= "客队换下",font=('YaHei', 10), bg="#C3D7DF")
self.sub_away_out_title.grid(row=62,column=0,sticky=W,pady=1, rowspan=2)
self.sub_away_in_title = Label(self.frame_sub, text= "客队换上",font=('YaHei', 10), bg="#C3D7DF")
self.sub_away_in_title.grid(row=64,column=0,sticky=W,pady=1, rowspan=2)
self.sub_home_title = Label(self.frame_sub, text= "主队("+teamname_home+")换人",font=('YaHei', 14), bg="#C3D7DF")
self.sub_home_title.grid(row=80,column=0,sticky=W,rowspan=2,pady=1)
self.sub_home_out_title = Label(self.frame_sub, text= "主队换下",font=('YaHei', 10), bg="#C3D7DF")
self.sub_home_out_title.grid(row=82,column=0,sticky=W,pady=1, rowspan=2)
self.sub_home_in_title = Label(self.frame_sub, text= "主队换上",font=('YaHei', 10), bg="#C3D7DF")
self.sub_home_in_title.grid(row=84,column=0,sticky=W,pady=1, rowspan=2)
#客队换上球员选择
self.sub_away_choose_in = ttk.Combobox(self.frame_sub)
self.sub_away_choose_in.grid(row=63,column=0,pady=1, rowspan=2)
self.sub_away_choose_in['value'] = away_list
self.sub_away_choose_in["state"] = "readonly"
self.sub_away_choose_in.current(0)
self.sub_away_choose_in.bind("<<ComboboxSelected>>", self.sub_away_choose)
#客队换下球员选择
self.sub_away_choose_out = ttk.Combobox(self.frame_sub)
self.sub_away_choose_out.grid(row=65,column=0,pady=1, rowspan=2)
self.sub_away_choose_out['value'] = away_list
self.sub_away_choose_out["state"] = "readonly"
self.sub_away_choose_out.current(0)
self.sub_away_choose_out.bind("<<ComboboxSelected>>", self.sub_away_choose)
#客队换人结果显示
self.sub_away_info = Text(self.frame_sub, width=20, height=2) #处理结果展示
self.sub_away_info.grid(row=60, column=15, rowspan=2,columnspan=20,padx=4,pady=4)
#客队换人按钮
self.sub_away_button = Button(self.frame_sub, text="客队换人", background="MintCream",width=10, height=4, command=self.sub_away, font=('YaHei', 16)) # 换人按钮
self.sub_away_button.grid(row=64, column=15, rowspan=2,columnspan=10,padx=4,pady=4)
#客队清空按钮
self.sub_clear_away_button = Button(self.frame_sub, text="清空", foreground = "red", width=5,height=2,command=self.sub_clear_away) # 换人清空按钮
self.sub_clear_away_button.grid(row=64, column=26, rowspan=2,columnspan=5,padx=4,pady=4)
#主队换上球员选择
self.sub_home_choose_in = ttk.Combobox(self.frame_sub)
self.sub_home_choose_in.grid(row=83,column=0,pady=1, rowspan=2)
self.sub_home_choose_in['value'] = home_list
self.sub_home_choose_in["state"] = "readonly"
self.sub_home_choose_in.current(0)
self.sub_home_choose_in.bind("<<ComboboxSelected>>", self.sub_home_choose)
#主队换下球员选择
self.sub_home_choose_out = ttk.Combobox(self.frame_sub)
self.sub_home_choose_out.grid(row=85,column=0,pady=1, rowspan=2)
self.sub_home_choose_out['value'] = home_list
self.sub_home_choose_out["state"] = "readonly"
self.sub_home_choose_out.current(0)
self.sub_home_choose_out.bind("<<ComboboxSelected>>", self.sub_home_choose)
#主队换人结果显示
self.sub_home_info = Text(self.frame_sub, width=20, height=2) #处理结果展示
self.sub_home_info.grid(row=80, column=15, rowspan=2,columnspan=20,padx=4,pady=4)
#主队换人按钮
self.sub_home_button = Button(self.frame_sub, text="主队换人", background="MintCream",width=10, height=4, command=self.sub_home, font=('YaHei', 16)) # 换人按钮
self.sub_home_button.grid(row=84, column=15, rowspan=2,columnspan=10,padx=4,pady=4)
#主队清空按钮
self.sub_clear_home_button = Button(self.frame_sub, text="清空", foreground = "red", width=5,height=2,command=self.sub_clear_home) # 换人清空按钮
self.sub_clear_home_button.grid(row=84, column=26, rowspan=2,columnspan=5,padx=4,pady=4)
'''红黄牌'''
#红黄牌标题
self.red_yellow_card_title = Label(self.frame_red_yellow_card, text= "红黄牌",font=('YaHei', 20), bg="#B1EDE7")
self.red_yellow_card_title.grid(row=0,column=0,sticky=W,rowspan=2,pady=6)
self.red_home_title = Label(self.frame_red_yellow_card, text= "主队("+teamname_home+")红黄牌",font=('YaHei', 14), bg="#B1EDE7")
self.red_home_title.grid(row=10,column=0,sticky=W,rowspan=2,pady=1)
self.red_away_title = Label(self.frame_red_yellow_card, text= "客队("+teamname_away+")红黄牌",font=('YaHei', 14), bg="#B1EDE7")
self.red_away_title.grid(row=20,column=0,sticky=W,rowspan=2,pady=1)
self.red_away_title = Label(self.frame_red_yellow_card, text= "历史记录",font=('YaHei', 14), bg="#B1EDE7")
self.red_away_title.grid(row=30,column=0,sticky=W,rowspan=2,pady=1)
#主队球员选择
self.red_home_choose = ttk.Combobox(self.frame_red_yellow_card)
self.red_home_choose.grid(row=13,column=0,pady=1, rowspan=2)
self.red_home_choose['value'] = home_list
self.red_home_choose["state"] = "readonly"
self.red_home_choose.current(0)
self.red_home_choose.bind("<<ComboboxSelected>>", self.red_card_home_read_list)
#主队红牌按钮
self.red_home_button = Button(self.frame_red_yellow_card, text="主队红牌", background="MintCream",foreground="red",width=6, height=2, command=self.red_home, font=('YaHei', 12))
self.red_home_button.grid(row=13, column=15, rowspan=2,columnspan=6,padx=4,pady=4)
#主队黄牌按钮
self.yellow_home_button = Button(self.frame_red_yellow_card, text="主队黄牌", background="MintCream",foreground="DarkKhaki",width=6, height=2, command=self.yellow_home, font=('YaHei', 12))
self.yellow_home_button.grid(row=13, column=25, rowspan=2,columnspan=6,padx=4,pady=4)
#客队球员选择
self.red_away_choose = ttk.Combobox(self.frame_red_yellow_card)
self.red_away_choose.grid(row=23,column=0,pady=1, rowspan=2)
self.red_away_choose['value'] = away_list
self.red_away_choose["state"] = "readonly"
self.red_away_choose.current(0)
self.red_away_choose.bind("<<ComboboxSelected>>", self.red_card_away_read_list)
#客队红牌按钮
self.red_away_button = Button(self.frame_red_yellow_card, text="客队红牌", background="MintCream",foreground="red",width=6, height=2, command=self.red_away, font=('YaHei', 12))
self.red_away_button.grid(row=23, column=15, rowspan=2,columnspan=6,padx=4,pady=4)
#客队黄牌按钮
self.yellow_away_button = Button(self.frame_red_yellow_card, text="客队黄牌", background="MintCream",foreground="DarkKhaki",width=6, height=2, command=self.yellow_away, font=('YaHei', 12))
self.yellow_away_button.grid(row=23, column=25, rowspan=2,columnspan=6,padx=4,pady=4)
#历史记录显示
self.red_yellow_info = Text(self.frame_red_yellow_card, width=20, height=5) #记录文本框
self.red_yellow_info.grid(row=33, column=0, rowspan=5,columnspan=5,pady=4)
#历史记录清空按钮
self.red_clear_button = Button(self.frame_red_yellow_card, text="清空", foreground = "red", width=6,height=2,command=self.red_clear_history) # 历史清空按钮
self.red_clear_button.grid(row=33, column=15, rowspan=2,columnspan=6,padx=4,pady=4)
'''记分板'''
#记分板标题
self.scoreboard_title = Label(self.frame_scoreboard, text= "记分板",font=('YaHei', 20), bg="#E0D9CE")
self.scoreboard_title.grid(row=0,column=0,sticky=W,rowspan=2,pady=6)
self.scoreboard_home_name_title = Label(self.frame_scoreboard, text= teamname_home,font=('YaHei', 14), bg="#E0D9CE") #主队名
self.scoreboard_home_name_title.grid(row=10,column=0,sticky=W,rowspan=2,pady=1)
self.scoreboard_away_name_title = Label(self.frame_scoreboard, text= teamname_away,font=('YaHei', 14), bg="#E0D9CE") #客队名
self.scoreboard_away_name_title.grid(row=10,column=20,sticky=W,rowspan=2,pady=1)
self.scoreboard_vs_title = Label(self.frame_scoreboard, text= ":",font=('YaHei', 72), bg="#E0D9CE")
self.scoreboard_vs_title.grid(row=10,column=10,rowspan=15,padx=80)
self.scoreboard_home_score_title = Label(self.frame_scoreboard, textvariable= self.scoreHomeVar,font=('YaHei', 48), bg="#E0D9CE") #主队比分
self.scoreboard_home_score_title.grid(row=20,column=0,rowspan=2,pady=1)
self.scoreboard_away_score_title = Label(self.frame_scoreboard, textvariable= self.scoreAwayVar,font=('YaHei', 48), bg="#E0D9CE") #客队比分
self.scoreboard_away_score_title.grid(row=20,column=20,rowspan=2,pady=1)
self.scoreboard_session_title = Label(self.frame_scoreboard, textvariable= self.sessionVar,font=('YaHei', 14), foreground="red",bg="#E0D9CE") #上下半场
self.scoreboard_session_title.grid(row=30,column=10,rowspan=2,pady=1)
#上下半场选择
self.scoreboard_session_first_radio = Radiobutton(self.frame_scoreboard, text="上半场", value="上半场",bg="#E0D9CE" ,variable=self.sessionVar, command=self.scoreboard_session_switch, font=('YaHei', 12))
self.scoreboard_session_first_radio.grid(row=40, column=10, rowspan=2,columnspan=6,padx=4,pady=4)
self.scoreboard_session_second_radio = Radiobutton(self.frame_scoreboard, text="下半场", value="下半场",bg="#E0D9CE" , variable=self.sessionVar, command=self.scoreboard_session_switch, font=('YaHei', 12))
self.scoreboard_session_second_radio.grid(row=41, column=10, rowspan=2,columnspan=6,padx=4,pady=4)
#主队比分按钮
self.scoreboard_home_scoreplus_button = Button(self.frame_scoreboard, text="主+1", background="MintCream",width=6, height=2, command=self.scoreboard_home_scoreplus, font=('YaHei', 12))
self.scoreboard_home_scoreplus_button.grid(row=40, column=0, rowspan=2,columnspan=6,padx=4,pady=4)
self.scoreboard_away_scoreplus_button = Button(self.frame_scoreboard, text="客+1", background="MintCream",width=6, height=2, command=self.scoreboard_away_scoreplus, font=('YaHei', 12))
self.scoreboard_away_scoreplus_button.grid(row=40, column=20, rowspan=2,columnspan=6,padx=4,pady=4)
#客队比分按钮
self.scoreboard_home_scoreminus_button = Button(self.frame_scoreboard, text="主-1", background="MintCream",width=6, height=2, command=self.scoreboard_home_scoreminus, font=('YaHei', 12))
self.scoreboard_home_scoreminus_button.grid(row=42, column=0, rowspan=2,columnspan=6,padx=4,pady=4)
self.scoreboard_away_scoreminus_button = Button(self.frame_scoreboard, text="客-1", background="MintCream",width=6, height=2, command=self.scoreboard_away_scoreminus, font=('YaHei', 12))
self.scoreboard_away_scoreminus_button.grid(row=42, column=20, rowspan=2,columnspan=6,padx=4,pady=4)
#清空按钮
self.scoreboard_score_clear_button = Button(self.frame_scoreboard, text="清空", background="MintCream",width=6, height=2,foreground="red",command=self.scoreboard_score_clear, font=('YaHei', 12))
self.scoreboard_score_clear_button.grid(row=46, column=10, rowspan=2,columnspan=6,padx=4,pady=4)
'''换人'''
#客队换人选
def sub_away_choose(self,*args):
trans_a = self.sub_away_choose_out.get() # 读取换下
trans_b = self.sub_away_choose_in.get() # 读取换上
print("客队换人"+'\n'+"换下:"+trans_a+'\n'+"换上:"+trans_b)
#客队换人写入
def sub_away(self,*args):
trans_a = self.sub_away_choose_out.get() # 读取换下
trans_b = self.sub_away_choose_in.get() # 读取换上
file = open('sub_away.csv', mode='w+',encoding="utf-8")#写入csv
file.write(trans_a)
file.write('\n' + trans_b)
file.close()
self.sub_away_info.delete(1.0,END)
self.sub_away_info.insert(1.0,"换下:" + trans_a + '\n' + "换上:" + trans_b)#文本框显示换人信息
#客队清空文本框
def sub_clear_away(self):
self.sub_away_info.delete(1.0,END)#清空显示框
file = open('sub_away.csv', mode='w+',encoding="utf-8")#清空csv文件
file.write('')
file.close()
#主队换人选
def sub_home_choose(self,*args):
trans_a = self.sub_home_choose_out.get() # 读取换下
trans_b = self.sub_home_choose_in.get() # 读取换上
print("主队换人"+'\n'+"换下:"+trans_a+'\n'+"换上:"+trans_b)
#主队换人写入
def sub_home(self,*args):
trans_a = self.sub_home_choose_out.get() # 读取换下
trans_b = self.sub_home_choose_in.get() # 读取换上
file = open('sub_home.csv', mode='w+',encoding="utf-8")#写入csv
file.write(trans_a)
file.write('\n' + trans_b)
file.close()
self.sub_home_info.delete(1.0,END)
self.sub_home_info.insert(1.0,"换下:" + trans_a + '\n' + "换上:" + trans_b)#文本框显示换人信息
#主队清空文本框
def sub_clear_home(self):
self.sub_home_info.delete(1.0,END)#清空显示框
file = open('sub_home.csv', mode='w+',encoding="utf-8")#清空csv文件
file.write('')
file.close()
'''红黄牌'''
#主队红黄牌人选
def red_card_home_read_list(self,*args):
red_choose = self.red_home_choose.get() # 读取换下
#print(red_choose)
#主队红牌写入
def red_home(self,*args):
red_choose = self.red_home_choose.get() # 读取换下
file = open('red_card.csv', mode='w+',encoding="utf-8")#写入csv
file.write(teamname_home + "," + red_choose)
file.close()
self.red_yellow_info.insert(1.0,"主队红牌:" + red_choose + '\n')#文本框显示信息
#主队黄牌写入
def yellow_home(self,*args):
red_choose = self.red_home_choose.get() # 读取换下
file = open('yellow_card.csv', mode='w+',encoding="utf-8")#写入csv
file.write(teamname_home + "," + red_choose)
file.close()
self.red_yellow_info.insert(1.0,"主队黄牌:" + red_choose +'\n')#文本框显示信息
#客队红黄牌人选
def red_card_away_read_list(self,*args):
red_choose = self.red_away_choose.get() # 读取换下
#print(red_choose)
#客队红牌写入
def red_away(self,*args):
red_choose = self.red_away_choose.get() # 读取换下
file = open('red_card.csv', mode='w+',encoding="utf-8")#写入csv
file.write(teamname_away + "," + red_choose)
file.close()
self.red_yellow_info.insert(1.0,"客队红牌:" + red_choose +'\n')#文本框显示信息
#客队黄牌写入
def yellow_away(self,*args):
red_choose = self.red_away_choose.get() # 读取换下
file = open('yellow_card.csv', mode='w+',encoding="utf-8")#写入csv
file.write(teamname_away + "," + red_choose)
file.close()
self.red_yellow_info.insert(1.0,"客队黄牌:" + red_choose +'\n')#文本框显示信息
#清空历史记录
def red_clear_history(self):
self.red_yellow_info.delete(1.0,END)#清空显示框
file = open('red_card.csv', mode='w+',encoding="utf-8")#清空csv文件
file.write('')
file.close()
file = open('yellow_card.csv', mode='w+',encoding="utf-8")#清空csv文件
file.write('')
file.close()
'''记分板'''
#上下半场选择
def scoreboard_session_switch(self):
score_home = self.scoreHomeVar.get()
score_away = self.scoreAwayVar.get()
session_period = self.sessionVar.get()
file = open('scoreboard.csv', mode='w+',encoding="utf-8")#写入csv文件
file.write(teamname_home + "," + str(score_home) + '\n' + teamname_away + "," + str(score_away) + '\n' + session_period)
file.close()
#主队比分增加
def scoreboard_home_scoreplus(self):
score_home = self.scoreHomeVar.get()
score_away = self.scoreAwayVar.get()
session_period = self.sessionVar.get()
score_home = score_home + 1
self.scoreHomeVar.set(score_home)
file = open('scoreboard.csv', mode='w+',encoding="utf-8")#写入csv文件
file.write(teamname_home + "," + str(score_home) + '\n' + teamname_away + "," + str(score_away) + '\n' + session_period)
file.close()
#客队比分增加
def scoreboard_away_scoreplus(self):
score_home = self.scoreHomeVar.get()
score_away = self.scoreAwayVar.get()
session_period = self.sessionVar.get()
score_away = score_away + 1
self.scoreAwayVar.set(score_away)
file = open('scoreboard.csv', mode='w+',encoding="utf-8")#写入csv文件
file.write(teamname_home + "," + str(score_home) + '\n' + teamname_away + "," + str(score_away) + '\n' + session_period)
file.close()
#主队比分减少
def scoreboard_home_scoreminus(self):
score_home = self.scoreHomeVar.get()
score_away = self.scoreAwayVar.get()
session_period = self.sessionVar.get()
if score_home <= 0:
score_home == 0
else:
score_home = score_home - 1
self.scoreHomeVar.set(score_home)
file = open('scoreboard.csv', mode='w+',encoding="utf-8")#写入csv文件
file.write(teamname_home + "," + str(score_home) + '\n' + teamname_away + "," + str(score_away) + '\n' + session_period)
file.close()
#客队比分减少
def scoreboard_away_scoreminus(self):
score_home = self.scoreHomeVar.get()
score_away = self.scoreAwayVar.get()
session_period = self.sessionVar.get()
if score_away <= 0:
score_away == 0
else:
score_away = score_away - 1
self.scoreAwayVar.set(score_away)
file = open('scoreboard.csv', mode='w+',encoding="utf-8")#写入csv文件
file.write(teamname_home + "," + str(score_home) + '\n' + teamname_away + "," + str(score_away) + '\n' + session_period)
file.close()
#清空比分
def scoreboard_score_clear(self):
self.scoreHomeVar.set(0)
self.scoreAwayVar.set(0)
score_home = self.scoreHomeVar.get()
score_away = self.scoreAwayVar.get()
session_period = self.sessionVar.get()
file = open('scoreboard.csv', mode='w+',encoding="utf-8")#写入csv文件
file.write(teamname_home + "," + str(score_home) + '\n' + teamname_away + "," + str(score_away) + '\n' + session_period)
file.close()
'''滚动条'''
#触发scrollbar
def onFrameConfigure(self, event):
'''Reset the scroll region to encompass the inner frame'''
self.canvas_root.configure(scrollregion=self.canvas_root.bbox("all"))
def gui_start():
init_window = Tk() #实例化出一个父窗口
AAA_PORTAL = MY_GUI(init_window)
# 设置根窗口默认属性
AAA_PORTAL.set_init_window()
init_window.mainloop() #父窗口进入事件循环,可以理解为保持窗口运行,否则界面不展示
gui_start() |
fa87a729cfc4b1d9a92b96f4fe2e1e5bb3b7ce05 | khknopp/wiigamers | /summarize_wybiorcze.py | 1,260 | 3.734375 | 4 | def summarize(text):
# importing libraries
import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize, sent_tokenize
nltk.download('punkt')
nltk.download('stopwords')
stopWords = set(stopwords.words("english"))
words = word_tokenize(text)
freqTable = dict()
for word in words:
word = word.lower()
if word in stopWords:
continue
if word in freqTable:
freqTable[word] += 1
else:
freqTable[word] = 1
sentences = sent_tokenize(text)
sentenceValue = dict()
for sentence in sentences:
for word, freq in freqTable.items():
if word in sentence.lower():
if sentence in sentenceValue:
sentenceValue[sentence] += freq
else:
sentenceValue[sentence] = freq
sumValues = 0
for sentence in sentenceValue:
sumValues += sentenceValue[sentence]
average = int(sumValues / len(sentenceValue))
i=0
summary=[]
for sentence in sentences:
if (sentence in sentenceValue) and (sentenceValue[sentence] > (0.1 * average) and i<10):
i+=1
summary.append(sentence)
return summary
|
efcb203febc0907f2230ba05fe0c1be5e922ec54 | rachel619/paths-to-cs-public | /m7/clock 2.py | 603 | 4.15625 | 4 | class Clock():
def __init__(self, time):
self.time = time
def get_time(self):
return self.time
def __str__(self):
return "Time: " + self.time
class AlarmClock(Clock):
def __init__(self, time, alarm):
self.time = time
self.alarm = alarm
def get_alarm(self):
return self.alarm
def __str__(self):
return "Time: " + self.time + " (Alarm: " + self.alarm + ")"
c1 = Clock("9am")
c2 = Clock("11am")
a1 = AlarmClock("1pm", "5pm")
a2 = AlarmClock("1pm", "7pm")
clocks = [c1, c2, a1, a2]
for clock in clocks:
print clock |
62e8fda4c21aef0bae385bd491a2742a23b35155 | greenfox-zerda-lasers/brigittaforrai | /week-04/day-02/02.py | 490 | 3.96875 | 4 | class Rectangle():
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
self.x2 = x + width
self.y2 = y + height
def is_over(self, other_rect):
return other_rect.x2 > self.x and other_rect.x < self.x2 and other_rect.y2 > self.y and other_rect.y < self.y2
rectangle1 = Rectangle(-10, -9, 100, 100)
rectangle2 = Rectangle(100, 0, 5, 5)
print(rectangle1.is_over(rectangle2))
|
3ac980c4a45bb36424b4e4705a1ce724b7d95df9 | Xenomorphims/Python3-examples | /new folder/continue.py | 411 | 3.609375 | 4 | while True:
s = input ('Enter something: ')
if s == 'quit':
break
if s == 'q':
break
if s == 'exit':
break
if len(s) < 5:
print ('Too small')
if len(s) > 10:
print ('Too large')
continue
print ('Input is a sufficient length')
print ('Done')
print ('\t *WRITTEN BY XENORM*')
#Do other kinds of processing here...
|
fb214b83e90d1a79d854162e37461b477e93e63d | alivcor/leetcode | /215. Kth Largest Element in an Array/main.py | 370 | 3.6875 | 4 | import Queue, random
def findKthLargest(nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
q = Queue.PriorityQueue()
for x in nums:
q.put(x)
if(q.qsize() > k):
q.get()
return q.get()
random_nums = [random.randint(0,50) for _ in xrange(8)]
print random_nums
print findKthLargest(random_nums, 4) |
8d3e3ee75a0d8ce2f400dac9f5cd5320592c815e | BestBroBradley/movie-collection | /app.py | 2,645 | 3.828125 | 4 | menu = "You can add a movie (a), list all movies (l), search for a title (s), or quit (q): "
user_library = []
def query_user():
user_selection = input(menu)
if user_selection == "a":
add_movie()
query_user()
elif user_selection == "l":
view_all()
query_user()
elif user_selection == "s":
search()
query_user()
elif user_selection == "q":
print("Thank you for using our movie service.")
else:
print("You must select a valid option.")
query_user()
def get_gen_rating(new_title):
genre = input(f"What genre is {new_title}? ")
rating = input(f"What rating would you like to give {new_title}? (?/10) ")
verify_gen_rating(new_title, genre, rating)
def verify_title(new_title):
verify_query = input(f"Would you like to add {new_title} to your library? (y/n) ")
if verify_query == "y":
get_gen_rating(new_title)
elif verify_query == "n":
add_movie()
else:
print("You must type either 'y' or 'n'.")
verify_title(new_title)
def add_to_library(new_title, genre, rating):
user_library.append({"title": new_title, "genre": genre, "rating": rating + "/10"})
query_user()
def verify_gen_rating(new_title, genre, rating):
verify_final = input(f"Would you like to add {new_title} with a genre of {genre} and a rating of {rating}/10 to your library? (y/n) ")
if verify_final == "y":
add_to_library(new_title, genre, rating)
elif verify_final == "n":
get_gen_rating(new_title)
else:
print("You must type either 'y' or 'n'.")
verify_gen_rating(new_title, genre, rating)
def add_movie():
new_title = input("What is the title of the movie you would like to add? ")
verify_title(new_title)
def view_all():
if len(user_library) > 0:
print("Your library:")
for movie in user_library:
title = movie["title"]
genre = movie["genre"]
rating = movie["rating"]
print(f"{title} | {genre} | {rating}")
query_user()
else:
print("There are no titles in your library.")
query_user()
def search():
search_term = input("What title would you like to search for? ")
for movie in user_library:
if movie["title"].lower() == search_term.lower():
title = movie["title"]
genre = movie["genre"]
rating = movie["rating"]
print("Movie Details:")
print(f"{title} | {genre} | {rating}")
break
else:
print("Looks like that title isn't in your library.")
query_user()
query_user()
|
ba89a3cd90c1ecc31b5dfc3038e357cff20e4f7f | kimtaeuk-AI/Study | /keras1/keras33_LSTM4_irirs.py | 2,055 | 3.5625 | 4 | # sklearn 데이터셋
# LSTM 으로 모델링
#Dense 와 성능비교
# 다중분류
import numpy as np
import tensorflow as tf
from sklearn.datasets import load_iris
# x, y= load_iris(retrun_X_y=True) # 이것도 있다.
dataset = load_iris()
x = dataset.data
y = dataset.target
# print(dataset.DESCR)
# print(dataset.feature_names)
x = x.reshape(150,4,1)
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, train_size=0.8, shuffle=True, random_state=66)
# from sklearn.preprocessing import MinMaxScaler
# scaler = MinMaxScaler()
# scaler.fit(x_train)
# x_train = scaler.transform(x_train)
# x_test = scaler.transform(x_test)
# print(x.shape) #(150, 4)
# print(y.shape) #(150, )
# print(x[:5])
# print(y)
from tensorflow.keras.utils import to_categorical
# from keras.utils.np_utils import to_categorical 위에랑 동일
y_train = to_categorical(y_train)
y_test = to_categorical(y_test)
print(y_train)
print(y_train.shape)#(120,3) #print(y.shape) (150,3)
print(y_test)
print(y_test.shape) #(30,3)
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, LSTM
model = Sequential()
model.add(LSTM(10, input_shape=(4,1), activation='relu'))
model.add(Dense(3, activation='softmax'))
from tensorflow.keras.callbacks import EarlyStopping
early_stopping = EarlyStopping(monitor='loss', patience=20, mode='min')
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['acc'])
model.fit(x_train, y_train, epochs=100, validation_split=0.2, verbose=1, callbacks=[early_stopping])
loss= model.evaluate(x_test, y_test)
print('loss : ', loss)
# from sklearn.metrics import r2_score
# r2= r2_score(x, y)
# print('r2 = ', r2_score)
y_pred = model.predict(x[-5:-1])
# print(y_pred)
# print(y[-5:-1])
# 결과치 나오게 수정argmax
np.argmax(y_pred,axis=1)
print(y_pred[0].argmax())
# print(y.argmax())
# loss : [0.15085560083389282, 1.0] - LSTM
# loss : [0.6759670376777649, 0.7333333492279053] - LSTM , early_stopping |
8274a7053589208bd813e2c0c0baa82809c995b4 | dthinley/Interview-Questions_2 | /interviews4.py | 2,584 | 3.90625 | 4 | class Node(object):
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BinaryTree(object):
def __init__(self, root):
self.root = Node(root)
def question4(T, r, n1, n2):
# Build a tree from the matrix
bst = build_tree(T, r)
return lca(bst.root, n1, n2)
# Lowest Common Ancestor
def lca(N, n1, n2):
if not N:
return None
cur_node = N
if cur_node.value > max(n1, n2):
return lca(cur_node.left, n1, n2)
elif cur_node.value < min(n1, n2):
return lca(cur_node.right, n1, n2)
else:
return cur_node.value
def build_tree(T, r):
tree = BinaryTree(r)
insert_node(T, tree.root)
return tree
def insert_node(T, node):
stack = [node]
while (stack):
new_node = None
#print node.value
for index, e in enumerate(T[node.value]):
#print e, index
if e and index < node.value:
new_node = node.left = Node(index)
stack.append(node.left)
insert_node(T, node.left)
elif e and index > node.value:
new_node = node.right = Node(index)
stack.append(node.right)
insert_node(T, node.right)
return new_node
stack.pop()
return None
def test_question4():
print ("Result for Question 4:")
print (question4([[0, 1, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[1, 0, 0, 0, 1],
[0, 0, 0, 0, 0]],
3,
1,
4))
print ('Testing BST with LST to the right of root')
print (question4([[0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0]],
3,
4,
6))
print ('Testing BST with LST to the left of root')
print (question4([[0, 0, 0, 0, 0, 0, 0, 0],
[1, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0]],
3,
0,
1))
test_question4()
|
6948615afe675e37ba923e6375844d3f716afab9 | MysteriousSonOfGod/python-workshop-demos-june-27 | /src/structures.py | 1,142 | 4 | 4 |
# lists
nums = [1,2,3,4, 20]
names = ['kevin', 'hayk', 'dan']
print(names)
print("The first name: {}".format(names[0]))
print("The last name: {}".format(names[-1]))
# add new people
names.append('michael')
names.append('hannah')
names.append('ted')
names.append('rob')
print(names)
print(names[0][0])
print( names[1:4] )
print( names[4:7] )
print( names[4:] )
print( names[:4] )
print( names[-3:] )
print( names[::-1] )
print("This can be reversed"[::-1])
first_letters = []
for name in names:
first_letters.append(name[0])
print(first_letters)
first_letters = [
n[0] # thing to add
for n in names # set to take from
if len(n) > 3 # condition
]
print(first_letters)
# tuples:
t = ('michael', 'rob', 'ted')
m, r, _ = t
m = t[0]
r = t[1]
_ = t[2]
m
import collections
m = (23, 73, 1.02)
Measurement = collections.namedtuple("Measurement", 'x y ph')
m = Measurement(23, 73, 1.02)
print(m.ph)
# fast look ups
names = dict()
names = {}
names = {
'm': 'Michael',
'j': 'Jeff',
't': 'Ted'
}
names['m'] = 'Michael'
names['j'] = 'Jeff'
names['t'] = 'Ted'
print(names.get('boo', 'MISSING'))
|
90f61f22e2f74bf1b1e58a55f0ff0eb879c30c3d | ChristopherBare/AckermannFunction | /ackermann.py | 423 | 3.984375 | 4 | def ackermann(m,n):
if m == 0:
return int(2)*int(n)
elif m >= 1 and n==0:
return 0
elif m >= 1 and n==1:
return 2
else:
return ackermann(m - 1, ackermann(m, n - 1))
x=int(input("What is the value for m? "))
print x
y=int(input("What is the value for n? "))
print y
print "\nThe result of your inputs according to the Ackermann Function is:"
print (ackermann(x, y))
|
72e4e4333f023aa06d7b772ec1b7476d79ef580f | sudocrystal/scc-compsci | /CalcGPA-PointSystem.py | 3,484 | 3.875 | 4 | '''
You should be able to run this script in a folder which contains
downloaded grade reports from Canvas.
The script should calculate GPAs and both print to the screen
as well as to an output file the final gpa score to be entered
into instructor briefcase.
'''
import os, csv, math
def gpa(decimal):
# this is the GPA mapping, you can alter. Format is:
# decimal : gpa,
map = {95 : 4.0,
94 : 3.9, 93 : 3.8, 92 : 3.7, 91 : 3.6, 90 : 3.5,
89 : 3.4, 88 : 3.4, 87 : 3.3, 86 : 3.3, 85 : 3.2, 84 : 3.2,
83 : 3.1, 82 : 3.1, 81 : 3.0, 80 : 3.0, 79 : 2.9, 78 : 2.9,
77 : 2.8, 76 : 2.8, 75 : 2.7, 74 : 2.7, 73 : 2.6, 72 : 2.5,
71 : 2.4, 70 : 2.3, 69 : 2.2, 68 : 2.1, 67 : 2.0, 66 : 1.9,
65 : 1.8, 64 : 1.7, 63 : 1.6, 62 : 1.6, 61 : 1.5, 60 : 1.5,
59 : 1.4, 58 : 1.4, 57 : 1.3, 56 : 1.3, 55 : 1.2, 54 : 1.2,
53 : 1.1, 52 : 1.1, 51 : 1.0, 50 : 1.0, 49 : 0.9}
# returns the gpa, 0.0 if not in the map
return map.get(decimal) if decimal in map else 0.0
def c_round(per):
if per % 1 >= 0.5:
return math.ceil(per)
else:
return math.floor(per)
def process(file,output):
# opens output file
out = open(output,'w')
class_gpa = []
bell = [0,0,0,0,0]
# opens the input file (file)
with open(file, 'r') as csvfile:
reader = csv.DictReader(csvfile)
# writes the header row
out.write('GPA,NAME,,~POINTS~\n')
# cycles through all the students in the report
for row in reader:
student = row['Student']
#print(student)
# as long as it's not the weird extra row
if student != "" and student.find("Points") == -1 and student != "Test Student":
#=================CHECK THAT THE FOLLOWING IS THE RIGHT FINAL GRADE COLMUMN IN SPREADSHEET===================
grade = float(row['Final Points'])
orig_grade = grade
if grade > 95:
grade = 95
# rounds and int's the decimal grade for lookup using gpa function
gpa_grade = '{0:.2}'.format(gpa(int(c_round(grade))))
# prints to screen
print(str(gpa_grade) + '\t' + str(orig_grade) + '\t' + student)
# writes to output file
out.write(gpa_grade + ',' + student + ',' + str(orig_grade) + '\n')
# calculates class stats
class_gpa += [float(gpa_grade)]
if grade >= 90:
bell[0] += 1
elif grade >= 80:
bell[1] += 1
elif grade >= 70:
bell[2] += 1
elif grade >= 66:
bell[3] += 1
else:
bell[4] += 1
avg = 0
for c in class_gpa:
avg += c
avg = avg / len(class_gpa)
out.write("\n\n,average gpa," + str(avg))
out.write("\n,As," + str(bell[0]))
out.write("\n,Bs," + str(bell[1]))
out.write("\n,Cs," + str(bell[2]))
out.write("\n,Ds," + str(bell[3]))
out.write("\n,Fs," + str(bell[4]))
out.close()
#---------------------------
for file in os.listdir('.'):
if file.endswith('.csv') and file.startswith('GRADE_REPORT_') == False:
output = 'GRADE_REPORT_' + file[file.index('-')+1:].replace('_','')
print('Processing: ' + file)
process(file, output)
print("\n")
|
b3415478810e06448d7260ad75bea69a20a2c396 | rlavanya9/cracking-the-coding-interview | /chapt-04-bits/reverse.py | 139 | 3.53125 | 4 | def reverse_bit(nums):
i = 0
m= 0
while i < 32:
m = m << 1 + (nums & 1)
nums >> 1
i += 1
return m
|
097527ad3bc607972bb58b5c64a0efe64d8df13d | Nishith170217/Python-Self-Challenge | /Array programs/Python Program for array rotation.py | 230 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Apr 28 09:43:49 2021
@author: Nishith
"""
def arryRotation(arr,d,l):
arr[:]=arr[d:l]+arr[0:d]
return arr
arr=[1,2,4,5,7,22]
l=len(arr)
print(arryRotation(arr,4,l)) |
ee5519ee595eb789d0cdb0ef05db56e6e9a3f300 | tomyc/workshop-python | /_bin/podstawy-oceny.py | 1,099 | 4.0625 | 4 | """
Napisz program, który wczytuje od użytkownika kolejne oceny i:
* sprawdza czy wprowadzona ocena jest na liście dopuszczalnych na wydziale ocen
* jeżeli ocena jest na liście dopuszczalnych na wydziale ocen, dodaje ją na listę otrzymanych ocen
* jeżeli wciśnięto sam Enter, oznacza to koniec listy otrzymanych ocen
* wyświetla wyliczoną dla listy otrzymanych ocen średnią arytmetyczną.
"""
DOPUSZCZALNE_OCENY = [1, 2, 3, 4, 5, 6]
otrzymane_oceny = list()
while True:
wpisana_ocena = input('Wpisz ocenę: ')
try:
wpisana_ocena = int(wpisana_ocena)
except ValueError:
if wpisana_ocena:
print('Wpisana ocena "{}" nie jest cyfrą całkowitą.'.format(wpisana_ocena))
continue
else:
break
if wpisana_ocena in DOPUSZCZALNE_OCENY:
otrzymane_oceny.append(wpisana_ocena)
else:
print('Ocena nie znajduje się na liście dopuszczalnych ocen: ', DOPUSZCZALNE_OCENY)
continue
suma = sum(otrzymane_oceny)
ilosc_ocen = len(otrzymane_oceny)
srednia = suma / ilosc_ocen
print(srednia)
|
3bca777791e9b24834c6d842dff1ec63419f6a7b | Sarthak-Singhania/Work | /Class 11/longest word.py | 222 | 3.609375 | 4 | a=input('Enter a sentence:')
b=''
lenght=0
cnt=0
for i in range(len(a)):
if a[i]!=' ':
b+=a[i]
else:
if len(b)>lenght:
lenght=len(b)
else:
break
b=''
print(b) |
9afdfb063b86544403f9174d9494cd68780622bf | archanasheshadri/Python-coding-practice | /binarytreepath.py | 1,134 | 4.1875 | 4 | #Given a binary tree, return all root-to-leaf paths.
'''
For example, given the following binary tree:
1
/ \
2 3
\
5
All root-to-leaf paths are:
["1->2->5", "1->3"]
'''
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
if not root:
return []
if not root.left and not root.right:
return [str(root.val)]
return ['{}->{}'.format(root.val, p)
for subtree in (root.left, root.right) if subtree
for p in self.binaryTreePaths(subtree)]
"""
Test cases
1) []
Empty tree. The root is a reference to NULL (C/C++), null (Java/C#/Javascript), None (Python), or nil (Ruby).
2) [1,2,3]
1
/ \
2 3
3) [1,null,2,3]
1
\
2
/
3
4) [5,4,7,3,null,2,null,-1,null,9]
5
/ \
4 7
/ /
3 2
/ /
-1 9
"""
|
702f3d226613c225a20ce896efb7fbc6b8500880 | serignefalloufall/Python_Repository | /exercice26.py | 718 | 3.9375 | 4 | my_liste = []
print("Saisir le nombre d'element de la liste")
n = int(input())
for i in range(1,n+1):
print("Saisir un entier : ")
my_liste.append(int(input())) # Remplissage de la liste
print(my_liste) # Affichage de la liste
resultat = False
elementPrecedent = my_liste[0] # Recuperation de la premier element de la liste
for element in my_liste:
if(elementPrecedent > element):
resultat=True
elementPrecedent=element
else:
resultat=False
elementPrecedent=element
#print("prece : ",elementPrecedent,"elem : ",element)
if (resultat == True):
print("Est croissant")
elif (resultat == False):
print("Est dcroissant")
else:
print("Est quelconque")
|
b143e84cc17fc1c15bb178f9bc938e08747140e5 | snigdhasen/myrepo | /examples/ex17.py | 2,671 | 3.984375 | 4 | '''
Using private variables and public properties
'''
class Person:
def __init__(self, **kwargs):
self.name = kwargs.get('name', None)
self.age = kwargs.get('age', None)
# overriding the inherited (from object class) method
def __str__(self):
return 'Person [name={}, age={}]'.format(self.name, self.age)
# return '{} is {} years old.'.format(self.__name, self.__age)
# readable property for the private __name
@property
def name(self):
return self.__name
# writable property 'name', which can assign value to __name
@name.setter
def name(self, value):
if value != None and type(value) != str:
raise TypeError('name must be string')
self.__name = value
@property
def age(self):
return self.__age
@age.setter
def age(self, value):
if value != None and type(value) not in (int, float):
raise TypeError('age must be a number')
if value != None and (value<1 or value>120):
raise ValueError('age must be between 1 and 120 years')
self.__age = value
def __iadd__(self, value):
if value==None: return self
if type(value) in (int, float):
self.age += value
if type(value) == str:
self.name += value
return self
def __lt__(self, value):
if value!=None and type(value) in (int, float):
return self.age < value
if value!=None and type(value) == type(self):
return self.age < value.age
raise TypeError('Invalid type for < operator')
def main():
p1 = Person(name='John', age = 22)
p2 = Person(name='Miller', age = 24)
if p1 < p2: # executes p1.__lt__(p2)
print('{} is younger than {}'.format(p1.name, p2.name))
else:
print('{} is older (or same age) than {}'.format(p1.name, p2.name))
def main_2():
p1 = Person(name='James', age=30)
print(p1)
p1 += 5 # expect p1's age to be added with 5
p1 += ' Bond' # expect p1's name to be appended with ' Bond'
print(p1)
def main_1():
p1 = Person(name='Krishna', age=50)
p2 = Person(name='Harish', age=15)
p1.age = 22 # try with non-numeric or outside range of 1-120
print('p1.name is', p1.name) # p1.name calls the @propert name
p1.name = 'Krishna Kumar' # p1.name = .. calls the @name.setter
print('p1.name is', p1.name)
# print(dir(p1))
print(p1)
print(p2.__str__())
print('-'*50)
# adds new attributes to p1
p1.__name = 1230
p1.__age = 'asdf'
# print(dir(p1))
print(p1)
if __name__=='__main__': main() |
ff7e51820fd73485779d418f7d2a5a358d5d859e | SamuelNunesDev/starting-point-in-python | /venv/Scripts/ex102.py | 531 | 3.90625 | 4 | def fatorial(n, show=False):
'''
-> Calcula o fatorial de um número.
:param n: Valor a ser calculado o fatorial.
:param show: Opção de ocultar ou mostrar o processo do cálculo.
:return: O fatorial do número n.
'''
f = 1
if show == True:
for c in range(n, 1, -1):
f *= c
print(f'{c} x ', end='')
print(f'1 = ', end='')
return f
else:
for c in range(n, 1, -1):
f *= c
return f
print(fatorial(5))
help(fatorial) |
c3d241ff3342b2ed78948eb4f9be3c65b978a110 | chetandekate1/CovidIndiaData | /fetchCovidIndiadata.py | 1,823 | 3.5 | 4 | import urllib.request as request
import urllib
import json
"""from dictor import dictor"""
class Covid19IndiaData():
"""
Covid19IndiaData class implements all the functionality to fetch data of India Covid19 data
"""
__CODECACHE__ = None
def __init__(self):
self._Covid19India_data_url = "https://api.covid19india.org/data.json"
self._Covid19India_data=dict()
def fetch_Covid19India_json_data(self):
covid19Url = request.urlopen(self._Covid19India_data_url)
if covid19Url.getcode() == 200:
data = covid19Url.read()
#get_covid19_json( data )
return json.loads( data )
else:
print( "Recieved Error, Cannot parse Code :",str(covid19Url.getcode()))
def get_state_today_data(self,state):
StateWisedata = self.fetch_Covid19India_json_data()
for stateData in StateWisedata["statewise"]:
if (stateData["state"] == state):
return stateData
def get_statewise_data(self):
StateWisedata = self.fetch_Covid19India_json_data()
return StateWisedata['statewise']
def get_time_series_data(self):
TimeSeriesdata = self.fetch_Covid19India_json_data()
return TimeSeriesdata['cases_time_series']
def get_tested_data(self):
Testeddata = self.fetch_Covid19India_json_data()
return Testeddata['tested']
def get_raw_data(self):
Rawdata = self.fetch_Covid19India_json_data()
return Rawdata
def main():
test = Covid19IndiaData()
'''StateWise = test.get_statewise_data()
for state in StateWise:
print(state)
print(test.get_time_series_data())
print( test.get_tested_data())
print(test.get_raw_data())'''
main()
|
0ea59b9e2710d87b3503f30fdad59cb3d0c43e5c | himabinduU/Python | /Code for hangman game/hangman_game.py | 1,224 | 4.0625 | 4 | print "It's time to play Hangman game"
print "Start guessing the letters in the secret word..."
f = open("hangman_text")
lines = f.readlines()
print "Enter any integer number between 1 to 10"
num = int(raw_input())
line = lines[num]
word = ''
ct = 0
for c in line :
word += c
ct += 1
if ct == (len(line) - 1):
break
turns = 10
guesses = '0'
guess = ''
string = ''
cnt = 0
count = 0
for i in word :
for j in word :
if i == j :
count += 1
#correction factor for the repetation of charectors.
r = (count - len(word)) / 2
while turns > 0:
flag = 0
guess = raw_input("guess a character:")
string += guess
print "Input string : ", string
for char in word :
if char == guess :
for ch in guesses :
if char == ch :
flag = 0
break
else :
flag = 1
if flag == 1 :
print "char : ", char
guesses += guess
cnt += 1
if guess not in word :
turns -= 1
print "Wrong guess"
print "You have", turns, "more chance to guess"
print "Correct guesses : ", guesses
if (r + cnt) == len(word) :
print "You own"
print "The secret word is ", word
exit(0)
if turns == 0 :
print "Sry you loosed the game"
print "The secret word is ", word
|
eea2df6d471e246ac23310fbe105278b3f2f0ad3 | sreekanth-bg/python-snippets | /fact.py | 160 | 3.953125 | 4 | def fact(x):
f = 1
for i in range(1,x+1):
print (i)
f = f * i
return f
if __name__=="__main__":
print ("factorial of 3=",fact(3)) |
8f4e3985ec00c0cb6a6648f0cb0331b07dd39821 | erickmiller/AutomatousSourceCode | /AutonomousSourceCode/data/raw/squareroot/f6718608-eba5-4780-bcff-77117493b0ea__squareroot.py | 285 | 4.25 | 4 | #!/usr/bin/env python3
import sys
def squareRoot(number):
num1 = 1
num2 = 0.5*(1+int(number))
while abs(num1 - num2) > 0.0001:
num2 = num1
num1 = 0.5*(num2 + int(number)/num2)
return num1;
print ("The square root of " + sys.argv[1] + " is " + str(squareRoot(sys.argv[1]))) |
8e041abfaffd99ae5d93c6a9c81fd795953b5219 | sodrian/codewars | /kt17_the_highest_profit_wins.py | 1,693 | 3.5625 | 4 | """Title: The highest profit wins!
URL: https://www.codewars.com/kata/the-highest-profit-wins
Description:
### Story
Ben has a very simple idea to make some profit: he buys something and sells it again. Of course, this wouldn't give him any profit at all if he was simply to buy and sell it at the same price. Instead, he's going to buy it for the lowest possible price and sell it at the highest.
### Task
Write a function that returns both the minimum and maximum number of the given list/array.
### Examples
```haskell
minMax [1,2,3,4,5] `shouldBe` (1, 5)
minMax [2334454,5] `shouldBe` (5, 2334454)
minMax [1] `shouldBe` (1, 1)
```
```javascript
minMax([1,2,3,4,5]) == [1,5]
minMax([2334454,5]) == [5, 2334454]
minMax([1]) == [1, 1]
```
```coffeescript
minMax [1..5] == [1, 5]
minMax [2334454,5] == [5, 2334454]
minMax [1] == [1, 1]
```
```python
min_max([1,2,3,4,5]) == [1,5]
min_max([2334454,5]) == [5, 2334454]
min_max([1]) == [1, 1]
```
```ruby
min_max([1,2,3,4,5]) == [1,5]
min_max([2334454,5]) == [5, 2334454]
min_max([1]) == [1, 1]
```
```java
MinMax.minMax(new int[]{1,2,3,4,5}) == {1,5}
MinMax.minMax(new int[]{2334454,5}) == {5, 2334454}
MinMax.minMax(new int[]{1}) == {1, 1}
```
```csharp
MinMax.minMax(new int[]{1,2,3,4,5}) == {1,5}
MinMax.minMax(new int[]{2334454,5}) == {5, 2334454}
MinMax.minMax(new int[]{1}) == {1, 1}
```
### Remarks
All arrays or lists will always have at least one element, so you don't need to check the length. Also, your function will always get an array or a list, you don't have to check for `null`, `undefined` or similar.
"""
def min_max(lst):
return [min(lst), max(lst)] |
79320fc872c2d778c86e07e3079b09674b2b486e | tashaylee/reddit-cmd-tool | /command_tool/RedditPost.py | 2,240 | 3.984375 | 4 | import json
import requests
""" This class represents all RedditPosts """
class _RedditPost:
def __init__(self, url):
self.__url = url
self._response = self._get_response()
"""
Sends a request to reddit api.
Returns:
A json response.
"""
def _get_response(self):
response = requests.get(self.__url, headers = {'User-agent': 'Bot 1.0'})
return response.json()
"""
Gets all reddit posts within a reddit listing.
Params:
response: A JSON response.
Returns:
A list of individual reddit posts.
"""
def _getChildren(self, response):
return response["data"]["children"]
"""
Sets the title, author, url from a reddit post.
Params:
listing: A list of individual reddit posts.
post: A dictionary containing information that represents a single reddit post.
"""
def _get_title(self, listing, post):
return listing[post]['data']['title']
def _get_author(self, listing, post):
return listing[post]['data']['author']
def _get_permalink(self, listing, post):
return 'https://www.reddit.com' + listing[post]['data']['permalink']
"""
Gets all information from a list of reddit posts.
Params:
listing: A list of individual reddit posts.
"""
def _get_info(self, listing):
for post in range(len(listing)-1):
print("Title:\t" + self._get_title(listing, post))
print("Author:\t" + self._get_author(listing, post))
print("URL:\t" + self._get_permalink(listing, post)+ '\n')
"""
Setter for the reddit api url.
Params:
url: String representing an api request.
"""
def set_url(self, url):
self.__url = url
"""
Gets the reddit api url .
Returns:
String representing an api request.
"""
def get_url(self):
return self.__url
""" Extracts reddit post information. """
def extract(self):
listing = self._getChildren(self._get_response())
self._get_info(listing)
if __name__ == '__main__':
post = _RedditPost('https://www.reddit.com/r/oddlysatisfying.json')
post.extract() |
c25b6e77e940951edeec10920213815baa285dd4 | brianhaines/TreasuryCurve | /getCurveFromDB.py | 674 | 3.71875 | 4 | """
This will retrieve specified curves from the database.
"""
import sqlite3
import sys
#Where is the DB located?
str=''
dbPath = []
#dbPath.append('/home/bhaines/Documents/HackerSchool/Python/XMLparse/') # This can be left out
dbPath.append('curveDB') #without the path, this db is created in the current directory
dbLoc = str.join(dbPath)
#print(dbLoc) #Here it is...
db = None
try:
#create or open existing db
db = sqlite3.connect(dbLoc)
# Get a cursor object
cursor = db.cursor()
#Call the db
cursor.execute('''SELECT * FROM curves ORDER BY id''')
for row in cursor:
print(row)
except Exception as e:
print("Error: ", e)
sys.exit
finally:
db.close
|
1b32b7e7b390935275cf2bad95658567895bd32a | chris-jantzen/AI_AStar_And_BFS_Search | /priority_queue.py | 1,088 | 3.796875 | 4 | class PriorityQueue(object):
def __init__(self):
self.queue = []
def __str__(self):
return " ".join([str(i.state) for i in self.queue])
def __iter__(self):
return PriorityQueueIterator(self)
def isEmpty(self):
return len(self.queue) == []
def insert(self, node):
self.queue.append(node)
def remove(self, node):
self.queue.remove(node)
def pop(self):
try:
min = 0
for i in range(len(self.queue)):
if self.queue[i].priority < self.queue[min].priority:
min = i
item = self.queue[min]
del self.queue[min]
return item
except IndexError:
print()
exit()
class PriorityQueueIterator:
def __init__(self, queue):
self._queue = queue
self._index = 0
def __next__(self):
if self._index < len(self._queue.queue):
result = self._queue.queue[self._index]
self._index += 1
return result
raise StopIteration
|
8b92651bc9f7027509ed43f4eef1cff35867b338 | TomaszBorusiewicz/diet_algoritm | /test_diet.py | 891 | 3.5 | 4 | import diet_algoritm.diet
import csv
algoritms = diet_algoritm.diet.Algorithms("products.csv", 1000)
# def test_get_sample_product():
sample_product = algoritms.get_product_from_csv(0)
print(sample_product)
all_ids = algoritms.get_random_product_from_csv()
print(all_ids)
# dieet = diet.Diet(100, 180, "male")
#
#
# def test_daily_demand():
# test = dieet.makroelements_demand_for_month()
# print(test)
# waga = input("Podaj swoją wagę: ")
# wzrost = input("Podaj swój wzrost: ")
# plec = input("podaj swoją płeć: ")
#
# dieta = diet.Diet(int(waga), int(wzrost), plec)
# print(dieta.print_monthly_mekroelements_demand())
# def get_product_from_csv(id):
# with open("products.csv", encoding="utf8") as file:
# products = csv.reader(file, delimiter=",")
# for row in products:
# print(row)
#
#
# dupa = get_product_from_csv(1)
# print(dupa)
|
32ff5b06cafd6ea5085fee431027ff639d85dae4 | chintan8195/Leetcode-practice | /leetcode/395. Longest Substring with At Least K Repeating Characters.py | 1,359 | 3.84375 | 4 | """
Input:
s = "aaabb", k = 3
Output:
3
The longest substring is "aaa", as 'a' is repeated 3 times.
Example 2:
Input:
s = "ababbc", k = 2
Output:
5
The longest substring is "ababb", as 'a' is repeated 2 times and 'b' is repeated 3 times.
"""
# Solve using template from https://leetcode.com/problems/minimum-window-substring/discuss/26808/here-is-a-10-line-template-that-can-solve-most-substring-problemsa
def longestSubstring(s, k):
count = 0
for i in range(1, 27):
count = max(count, helper(s, k, i))
return count
def helper(s, k, numUniqueTarget):
start = end = numUnique = numNoLessThanK = count = 0
chMap = [0]*128
while end < len(s):
if chMap[ord(s[end])] == 0: numUnique += 1
chMap[ord(s[end])] += 1
if chMap[ord(s[end])] == k: numNoLessThanK += 1
end += 1
while numUnique > numUniqueTarget:
if chMap[ord(s[start])] == k: numNoLessThanK -= 1
chMap[ord(s[start])] -= 1
if chMap[ord(s[start])] == 0: numUnique -= 1
start += 1
if numUnique == numNoLessThanK: count = max(count, end-start)
return count
def test():
assert longestSubstring("ababbc",2) == 5,"should be equal to 5"
assert longestSubstring("aaabb",3) == 3, "should be equal to 5"
test()
|
669563710a76da0b0965af59920ba5fa960381db | Alrin12/ComputerScienceSchool | /source_code/python/python_advanced/strings/bytes.py | 129 | 3.671875 | 4 | b = b"abcde"
#print(b)
#print(b.upper())
#print(b.startswith(b"ab"))
#bytes -> string
string = b.decode('UTF-8')
print(string)
|
f042e349d08bdbfdda097be85169be066ba0d3e2 | SkiAqua/CEV-Python-Ex | /exercícios/ex059.py | 1,059 | 3.671875 | 4 | from os import system
from time import sleep
def lin(txt):
print(txt+'-'*(30-int(len(txt))))
opt = '0'
chos = ['1','2','3','4','5']
lin('MenuPython')
while opt != '5':
opt = '0'
st = int(input('Digite o primeiro número: '))
nd = int(input('Digite o segundo número: '))
lin('')
while opt not in ['4','5']:
opt = str(input('(1)Somar\n(2)Multiplicar\n(3)Maior\n(4)Números diferentes\n(5)Sair\n\nDigite sua escolha: ')).strip()
if opt not in chos:
system('cls')
print('Escolha uma opção válida.')
if opt == '1':
print('A soma de {} e {} é: {}.'.format(st,nd,st+nd))
elif opt == '2':
print('O produto de {} e {} é: {}.'.format(st,nd,st*nd))
elif opt == '3':
if st > nd:
print('Entre {} e {}, {} é o maior.'.format(st,nd,st))
elif nd > st:
print('Entre {} e {}, {} é maior.'.format(st,nd,nd))
elif nd == st:
print('Os dois são iguais.')
sleep(2) |
14cb42a62c095fe8472f8d743f5e35e847cc9f7e | doraemon1293/Leetcode | /archive/2593SumSmaller.py | 712 | 3.625 | 4 | # coding=utf-8
'''
Created on 2016?12?14?
@author: Administrator
'''
class Solution(object):
def threeSumSmaller(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
nums.sort()
ans = 0
for i in xrange(len(nums) - 2):
j = i + 1
k = len(nums) - 1
while j < k:
if nums[i] + nums[j] + nums[k] >= target:
k -= 1
else:
ans += k - j
j += 1
return ans
nums = [3, 2, -2, 6, 2, -2, 6, -2, -4, 2, 3, 0, 4, 4, 1]
target = 3
print Solution().threeSumSmaller(nums, target)
|
a600370f288075d8a1d2899c4e293f4ab747715b | mdar4/Projetos_python_blue | /ProjetoJokenpo.py | 2,408 | 3.78125 | 4 | import random
from time import sleep
resp = None
pedra = 'Pedra'
papel = 'Papel'
tesoura = 'Tesoura'
jogador = 0
pc = 0
while True:
while resp != 'N':
rod = int(input('Número de Partidas: '))
for c in range(rod):
pcEsc = [pedra, papel, tesoura]
escolha = random.choice(pcEsc)
print('''
Faça sua escolha:
1 - Pedra
2 - Papel
3 - Tesoura
''')
resp = int(input('Escolha: '))
# Pedra
if resp == 1:
print('Você escolheu Pedra.')
sleep(1)
print('O computador está escolhendo...')
sleep(2)
print(f'O computador escolheu {escolha}.')
sleep(1)
# Configurando escolhas do computador
if escolha == 'Papel':
print('Papel embrulhou Pedra !')
pc += 1
if escolha == 'Tesoura':
print('Pedra quebra Tesoura!')
jogador += 1
if escolha == 'Pedra':
print('Empate.')
# Papel
elif resp == 2:
print('Você escolheu Papel.')
sleep(1)
print('O computador está escolhendo...')
sleep(2)
print(f'O computador escolheu {escolha}.')
sleep(1)
if escolha == 'Pedra':
print('Papel embrulhou Pedra !')
jogador += 1
if escolha == 'Tesoura':
print('Tesoura cortou Papel !')
pc += 1
if escolha == 'Papel':
print('Empate.')
# Tesoura
elif resp == 3:
print('Você escolheu Tesoura.')
sleep(1)
print('O computador está escolhendo...')
sleep(2)
print(f'O computador escolheu {escolha}.')
sleep(1)
if escolha == 'Pedra':
print('Pedra quebrou Tesoura !')
pc += 1
if escolha == 'Papel':
print('Tesoura cortou Papel !')
jogador += 1
if escolha == 'Tesoura':
print('Empate.')
if jogador > pc:
print(f'O jogador foi o grande campeão com {jogador} vitórias !')
elif jogador == pc:
print('Houve um empate.')
elif jogador == 0 and pc == 0:
print('Não houve vencedor.')
else:
print(f'O computador foi o grande campeão com {pc} vitórias !')
print(f'O computador venceu {pc} rodadas e o jogador {jogador} rodadas.')
print()
resp = str(input('Deseja jogar novamente? [S/N]: ')).strip().upper()[0]
if resp == 'N':
break
|
e7025e31895eeccac54f104704dbb04af6377c95 | RePierre/metis | /pipeline/parsers/dictquery.py | 738 | 3.515625 | 4 | class DictQuery(dict):
"""Handles nested dictionaries
Taken from https://www.haykranen.nl/2016/02/13/handling-complex-nested-dicts-in-python/
"""
def get(self, path, default=None):
keys = path.split("/")
val = dict.get(self, keys[0], default)
for key in keys[1:]:
val = self._get_recursive(key, val, default)
if not val:
break
return val
def _get_recursive(self, key, val, default):
if not val:
return None
if isinstance(val, dict):
return val.get(key, default)
if isinstance(val, list):
return [self._get_recursive(key, v, default) if v else None for v in val]
return None
|
499bd7ca5319401a02e54093c7bf5482ea224d9b | DaDudek/Monopoly | /board.py | 2,651 | 3.96875 | 4 | from banker import Banker
class Board:
"""
This is a class for represent board on game - most of the logic need this class
Attributes:
player_number (int) : how many players play on this game (basic 4)
"""
def __init__(self, player_number=4):
"""
The constructor for ComplexNumber class.
:param player_number: how many players play on this game (basic 4)
board: (dict) this represent board with cells - key is a cell number,
board[cell][0] is always cell card, board[cell][x], x>0 -> player who stand on the cell
id_type_cells: (dict) key is a kind of cell (cities, power_stations etc)
value is list of number of that kind cells
hidden: (list) this is list of all hidden card
(in this version is only one event but it is prepare for future when will be more events)
players_queue: (list (of players)) this represent players_queue, is used to control players order
sector: (dict) this represent countries, key is country kind (yellow, red etc),
value is list of coordinates cell from that country
actual_player: (player) represent current player
"""
self.player_number = player_number
self.board = {x: [] for x in range(40)}
self.id_type_cells = {}
self.hidden = []
self.players_queue = []
self.sector = {}
self.actual_player = None
def make_board(self):
"""
The function to init board with all the cells - banker create there and put on the board
:return: void -> only change object
"""
banker = Banker(open("monopoly_cards.csv"))
banker.make_all_cards()
for i in range(40):
self.board[i] = [banker.cards[i]]
self.id_type_cells = banker.id
self.hidden = banker.hidden_cards
self.sector = banker.sector
def check_transport_cells(self):
"""
This function is used to check how many transport cards player have
:param players_queue: (list) list of player thats play the game
:return: void -> only change object
"""
for player in self.players_queue:
#print(player.countries)
if "transport" not in player.countries:
player.countries["transport"] = []
for transport in player.countries["transport"]:
self.board[transport][0].number_of_houses = len(player.countries["transport"]) - 1
|
7b73275902ecf6699da596aa8a7be8f870734f06 | kipflip1125/client-server | /client.py | 5,445 | 3.765625 | 4 |
# *******************************************************************
# This file illustrates how to send a file using an
# application-level protocol where the first 10 bytes
# of the message from client to server contain the file
# size and the rest contain the file data.
# *******************************************************************
import socket
import os
import sys
def recvAll(sock, numBytes):
# The buffer
recvBuff = ""
# The temporary buffer
tmpBuff = ""
# Keep receiving till all is received
while len(recvBuff) < numBytes:
# Attempt to receive bytes
tmpBuff = sock.recv(numBytes).decode('ascii')
# The other side has closed the socket
if not tmpBuff:
break
# Add the received bytes to the buffer
recvBuff += tmpBuff
return recvBuff
# Receive Data
def get_command(file, serverAddr, serverPort):
# Create a TCP socket and connect to the address and socket port
try:
connSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except:
print('Failed to create a socket')
try:
connSock.connect((serverAddr, int(serverPort)))
except:
print('Failed to connect to ', severAddr, ':', serverPort)
print("Connected to ", serverAddr, ":", serverPort)
connSock.send(b'g')
fNamelen = len(file)
while len(file) < 3:
fNamelen = "0" + fNamelen
connSock.send(str(fNamelen).encode('ascii'))
connSock.send(file.encode('ascii'))
# The buffer to all data received from the
# the client.
fileData = ""
# The temporary buffer to store the received
# data.
recvBuff = ""
# The size of the incoming file
fileSize = 0
# The buffer containing the file size
fileSizeBuff = ""
# Receive the first 10 bytes indicating the
# size of the file
fileSizeBuff = recvAll(connSock, 10)
# Get the file size
fileSize = int(fileSizeBuff)
print("The file size is ", fileSize)
# Get the file data
fileData = recvAll(connSock, fileSize)
print("The file data is: ")
print(fileData)
# Close our side
print('Received ', fileSize, ' bytes')
connSock.close()
# Send Data
def put_command(file, serverAddr, serverPort):
# Create a TCP socket and connect to the address and socket port
try:
connSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except:
print('Failed to create a socket')
try:
connSock.connect((serverAddr, int(serverPort)))
except:
print('Failed to connect to ', severAddr, ':', serverPort)
print("Connected to ", serverAddr, ":", serverPort)
connSock.send(b'p')
# Open the file
fileObj = open(file, "r")
# The number of bytes sent
numSent = 0
# The file data
fileData = None
# Keep sending until all is sent
while True:
# Read 65536 bytes of data
fileData = fileObj.read(65536)
# Make sure we did not hit EOF
if fileData:
# Get the size of the data read
# and convert it to string
dataSizeStr = str(len(fileData))
# Prepend 0's to the size string
# until the size is 10 bytes
while len(dataSizeStr) < 10:
dataSizeStr = "0" + dataSizeStr
# Prepend the size of the data to the
# file data.
fileData = dataSizeStr + fileData
# The number of bytes sent
numSent = 0
# Send the data!
while len(fileData) > numSent:
try:
numSent += connSock.send(fileData[numSent:].encode('ascii'))
except:
print('Failed to send message')
# The file has been read. We are done
else:
break
print("Sent ", numSent, " bytes.")
fileObj.close()
# Print out directory
def ls_command(serverAddr, serverPort):
# Create a TCP socket and connect to the address and socket port
try:
connSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except:
print('Failed to create a socket')
try:
connSock.connect((serverAddr, int(serverPort)))
except:
print('Failed to connect to ', severAddr, ':', serverPort)
print("Connected to ", serverAddr, ":", serverPort)
connSock.send(b'l')
numBytes = 0
numFiles = int(connSock.recv(2).decode('ascii'))
for i in range(numFiles):
length = connSock.recv(2).decode('ascii')
ls_data = connSock.recv(int(length)).decode('ascii')
print(ls_data)
numBytes = numBytes + len(ls_data)
print('Received ', numBytes, ' bytes.')
connSock.close()
# Quit
def quit_command():
# Create a TCP socket and connect to the address and socket port
try:
connSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except:
print('Failed to create a socket')
try:
connSock.connect((serverAddr, int(serverPort)))
except:
print('Failed to connect to ', severAddr, ':', serverPort)
print("Connected to ", serverAddr, ":", serverPort)
connSock.send(b'q')
quit()
if __name__ == '__main__':
# Command line checks
if len(sys.argv) < 2:
print("USAGE python " + sys.argv[0] + " <FILE NAME>")
# Server address
serverAddr = socket.gethostbyname(sys.argv[1])
# Server port
serverPort = sys.argv[2]
while True:
# Get client command
text = input('ftp> ')
args = text.split(' ')
if(args[0] == 'get'):
get_command(args[1], serverAddr, serverPort)
if(args[0] == 'put'):
put_command(args[1], serverAddr, serverPort)
if(args[0] == 'ls'):
ls_command(serverAddr, serverPort)
if(args[0] == 'quit'):
quit_command()
|
f290f405ddcf7c10eb46fdbd89fafd0287d9bb18 | pengboyun/project2 | /Course1/class4homwork3.py | 678 | 4.0625 | 4 | class multiplication(object):
def __init__(self):
self.take_several_times = 0
def pithy_formula(self):
x = 0
for x in range(1,self.take_several_times):
y = ' '
for i in range(1, x+1):
y = y + str(i) + '*' + str(x) + '=' + str(i * x) + ' '
print(y)
def addition(self):
x = 0
for x in range(1,self.take_several_times):
y = ''
for i in range(1, x+1):
y = y + str(i) + '+' + str(x) + '=' + str(i + x) + ' '
print(y)
result = multiplication()
result.take_several_times = 10
result.pithy_formula()
result.addition()
|
47bbbe57bf629dbe8df53f04eafe3e5c7316b530 | diegoglozano/TFG | /Preprocesado/variablesOrdinales.py | 256 | 3.8125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 6 11:06:32 2018
@author: diego
"""
import numpy as np
import pandas as pd
datos = pd.DataFrame([2,3,2,'NA','NA','NA',5,3],columns=['num'])
datos[datos['num']=='NA'] = 0
print(datos) |
ba09f26b67567f2fd2bf4f408ce7155d0b5679a1 | acarcher/lmpthw | /ex7_grep.py | 1,022 | 3.546875 | 4 | # grep
# get cmd line args
# load the file
# read the file into a list
# iterate through the list searching for pattern
#
import argparse
import re
def parse_args():
ap = argparse.ArgumentParser()
ap.add_argument("pattern", type=str, help="pattern to search for")
ap.add_argument("file", type=str, help="file to search in")
ap.add_argument("-i", action="store_true", help="make case insensitive")
ap.add_argument("-n", action="store_true", help="")
# ap.add_argument("-r", action="store_true", help="")
return ap.parse_args()
def grep(args):
result = []
pattern = args.pattern
file = args.file
with open(file) as f:
listified = f.readlines()
for line in listified:
if args.i:
if re.search(pattern, line, flags=re.I):
result.append(line)
else:
if re.search(pattern, line):
result.append(line)
for line in result:
print(line.rstrip())
args = parse_args()
grep(args)
|
46113fa4f8ac25d943ca4616cc6468028bcfa3d5 | Chinna2002/Python-Lab | /L4-Adding Two Sparse Matrix.py | 2,527 | 3.765625 | 4 | def add(A1,A2):
sum = []
l1 = len(A1)
l2 = len(A2)
if l1==0 : sum = A2
if l2==0 : sum = A1
i = 0
j = 0
while l1>0 and l2>0:
if A1[i][0]==A2[j][0] and A1[i][1]==A2[j][1]:
sum.append([A1[i][0],A1[i][1],A1[i][2]+A2[j][2]])
i += 1
j += 1
else:
m = min(A1[i],A2[j])
sum.append(m)
if m==A1[i]:
i += 1
else:
j += 1
if i>=l1:
for x in range(j,l2):
sum.append(A2[x])
break
if j>=l2:
for x in range(i,l1):
sum.append(A1[x])
break
return sum
def dispmatrix(a):#Function1(For dispalying matrix)
for row in matrix:
for ele in row:
print(ele, end=" ")
print()
def sparse(a):#Function2(For converting to sparse matrix)
sparseMatrix = []
Threshold=int(input("Enter threshold value:"))
for i in range(len(matrix)):
for j in range(len(matrix[2])):
if (matrix[i][j]<=Threshold):
matrix[i][j]=0
if(matrix[i][j]!=0):
temp = []
temp.append(i)
temp.append(j)
temp.append(matrix[i][j])
sparseMatrix.append(temp)
return sparseMatrix
#Taking Input
row1 = int(input("Enter the number of rows:"))
col1 = int(input("Enter the number of columns:"))
# Initialize matrix
matrix = []
print("Enter the entries rowwise:")
for i in range(row1): # A for loop for row entries
a = []
for j in range(col1): # A for loop for column entries
a.append(int(input()))
print()
matrix.append(a)
#for array 1
dispmatrix(matrix)#Calling Funtion1
x=sparse(matrix)#Calling Fuction2
print("SparseMatrix1:",x)
#For array2
#Taking Input
print("Matrix2")
row2 = int(input("Enter the number of rows:"))
col2 = int(input("Enter the number of columns:"))
# Initialize matrix
matrix = []
print("Enter the entries rowwise:")
for i in range(row1): # A for loop for row entries
a = []
for j in range(col1): # A for loop for column entries
a.append(int(input()))
print()
matrix.append(a)
dispmatrix(matrix)#Calling Funtion1
y=sparse(matrix)#Calling Fuction2
print("SparseMatrix2:",y)
z=add(x,y)
print("Addition of two SparseMatrix is:")
for row in z:
for ele in row:
print(ele,end=" ")
print() |
06a961e0c70ff96c7779845a2dba179cd581f119 | Pattriarch/100-apps | /100_apps/diff_3_of_10_Caesar_Cipher/Caesar Cipher.py | 3,365 | 4.03125 | 4 | from art import logo
import time
alphabet = ['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']
# Function that encode and decode text
def caesar(simple_text, shift_amount, directions):
cipher_text = ''
act = -1
# If direction is not encode, then we change shift amount and flag
if directions == 'decode':
shift_amount *= -1
act = 1
for letter in simple_text:
if letter not in alphabet:
cipher_text += letter
else:
# Check every letter in alphabet
for i, char in enumerate(alphabet):
if letter == char:
# If index + shift amount less than length alphabet it's okay
if i + shift_amount < len(alphabet):
cipher_text += alphabet[i + shift_amount]
# If index + shift amount more than length alphabet, then we need to nullify our indexes
elif i + shift_amount > len(alphabet) - 1:
amount = i + shift_amount // 26
cipher_text += alphabet[i + amount * act * 26 + shift_amount]
print(f'The {directions} word is: {cipher_text}')
# Flag was created to check if user wants to end program or restart her
flag = False
while not flag:
print(logo)
direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n")
# Two flags to check if user wrote something in text and in shift
text_is_here = False
shift_is_here = False
text = input("Type your message:\n").lower()
# If nothing in text, we change our flag
if text == '':
print('You need to paste anything!')
time.sleep(1.5)
continue
else:
text_is_here = True
# If something wrong with shift, we change our flag
# noinspection PyBroadException
try:
shift = int(input("Type the shift number:\n"))
shift_is_here = True
except Exception:
print('You need to type integer value!')
time.sleep(1.5)
continue
# If both flags are True then we start our program
if text_is_here and shift_is_here:
caesar(text, shift, direction)
# Check if user wants to restart program
restart = input('Type \'yes\' if you want to start again. Otherwise type \'no\'\n')
if restart == 'yes':
pass
elif restart == 'no':
flag = True
# Less text and easier way
# def caesar(text, shift, direction):
# just_a_text = ''
# if shift > 26:
# shift = shift % 26
# if direction == 'decode':
# shift *= -1
# for letter in text:
# if letter not in alphabet:
# just_a_text += letter
# else:
# position = alphabet.index(letter)
# new_position = position + shift
# just_a_text += alphabet[new_position]
# print(f"The {direction} text is {just_a_text}")
# flag = False
# while flag == False:
# direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n")
# text = input("Type your message:\n").lower()
# shift = int(input("Type the shift number:\n"))
# caesar(start_text=text, shift_amount=shift, cipher_direction=direction)
# restart = input('Do you want to restart program?\n')
# if restart == 'yes':
# pass
# elif restart == 'no':
# flag = True
|
0a08e49c443ac02f3a9667b6fd561d5693022d27 | LQXshane/leetcode | /dp/buyNsellStocks.py | 869 | 3.5625 | 4 |
# coding: utf-8
# Input: [7, 1, 5, 3, 6, 4]
# Output: 5
#
# max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
#
#
# ## A variation of maximum subarray problem and can be solved using Kadane's algo
# In[9]:
import numpy as np
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
cur_profit = opt_profit = 0
n = len(prices)
minprice = np.inf
for i in range(0, n):
if prices[i] < minprice:
minprice = prices[i]
cur_profit = prices[i] - minprice
opt_profit = max(cur_profit, opt_profit)
return opt_profit
# In[10]:
prices = [7, 1, 5, 3, 6, 4]
# In[11]:
sol = Solution()
# In[12]:
sol.maxProfit(prices)
# In[ ]:
5
|
72128ea5fece59062505b46f046c880e97578eff | GeraldoLucas/Python_3.8 | /fundamentals/ex032.py | 572 | 3.78125 | 4 | print('\033[1;33m === EXERCÍCIO 032 === \033[m')
import datetime
print('\033[1;46m-=-\033[m' * 10)
print('\033[1;36mANO BISSEXTO, LEAP YEAR\033[m')
print('\033[1;46m-=-\033[m' * 10)
ano = int(input('\033[1mDigite o valor de um ano, digite 0 para o ano atual: '))
if ano == 0:
ano = datetime.date.today().year
if ano % 4 == 0 and ano % 100 != 0 or ano % 400 ==0:
print('O ano {} é um ano BISSEXTO, LEAP YEAR.'.format(ano))
else:
print('O ano {} NÂO é um ano BISSEXTO, LEAP YEAR.'.format(ano))
print('\033[1;33m === FINALIZADO 032 ===\033[m')
|
2d4ca925c1e20d810d4dfa2956e10ac2187831fc | gondsuryaprakash/Python-Tutorial | /Numerical/Prime Factor Of Number/PrimeFactorOfNumber.py | 447 | 3.953125 | 4 | import math
def getPrimeFactor(n):
arr = []
while n % 2 == 0:
arr.append(2)
n = n // 2
print(int(math.sqrt(n)))
for i in range(3, int(math.sqrt(n))+1, 2):
while n % i == 0:
arr.append(i)
n //= i
if n > 2:
arr.append(n)
print(arr)
return max(arr)
getPrimeFactor(666)
# t = int(input())
# for i in range(t):
# n = int(input())
# print(getPrimeFactor(n))
|
6fb7793831f074ea1aff6e9229e47aaccc98590d | srishtipandey06/Quiz-Hurdle-Race-Game | /Hurdle Jump Game/main.py | 3,969 | 3.78125 | 4 | import pygame
from player import Player # Import our Player class
from hurdle_handler import Hurdle_Handler
WINDOW_SIZE = (720, 360)
GROUND_Y = 280
def event_handler():
""" Returns all pygame events.
Checks and handles the QUIT event.
Returns:
events (list): pygame events
"""
events = pygame.event.get()
for event in events:
# Has the quit button been pressed?
if event.type == pygame.QUIT:
quit()
def show_ground(window, primary_color=(34,139,34), secondary_color=(153, 102, 0), surface_height=15):
""" Show an orange rectange where the ground is.
Parameters:
window (pygame.Surface): Window to show rect on
primary_color (tuple): Main color of the ground
secondary_color (tuple): Color of the surface of the ground
surface_height (int): Height of the surface to display
"""
pygame.draw.rect(window, primary_color, (0, GROUND_Y, WINDOW_SIZE[0], WINDOW_SIZE[1] - GROUND_Y))
pygame.draw.rect(window, secondary_color, (0, GROUND_Y, WINDOW_SIZE[0], surface_height))
def has_player_hit_hurdle(player, hurdles, ground_height):
""" Has the player hit a hurdle?
Parameters:
player (Player): player object to check collision for
hurdles (list): list of hurdles to check
Returns:
touching (bool): has the player hit a hurdle?
"""
player_rect = (player.pos[0] - player.size[0] / 2, player.pos[1] - player.size[1] / 2) + player.size
for hurdle in hurdles:
hurdle_rect = (hurdle.x - hurdle.size[0] / 2, ground_height - hurdle.size[1]) + hurdle.size
if touching(player_rect, hurdle_rect):
return True
return False
def touching(rect1, rect2):
""" Are the two rects touching?
rects to be in the form (left x, right y, width, height)
Parameters:
rect1 (tuple): rect to check for collision with rect2
rect2 (tuple): rect to check for collision with rect1
"""
return (rect1[0] + rect1[2] >= rect2[0] and
rect1[0] <= rect2[0] + rect2[2] and
rect1[1] + rect1[3] >= rect2[1] and
rect1[1] <= rect2[1] + rect2[3])
def show_text(window, text, size, pos, color=(0, 0, 0)):
font = pygame.font.Font("mcFont.ttf", size)
textSurf = font.render(text, True, color)
window.blit(textSurf, pos)
def show_all(items, window, score, high_score):
""" Show all items.
it's assumed every item in items has a show(window) method. """
window.fill((200, 236, 254))
for item in items:
item.show(window)
show_ground(window)
show_text(window, str(score), 60, (10, 10), color=(219, 90, 0))
show_text(window, str(high_score), 60, (10, 70), color=(100, 40, 0))
pygame.display.update()
def main():
""" Main game function.
Sets up the game and calls the game loop """
pygame.init()
window = pygame.display.set_mode(WINDOW_SIZE)
pygame.display.set_caption("Antenna Hurdle Race")
clock = pygame.time.Clock()
player = Player(GROUND_Y)
hurdle_handler = Hurdle_Handler(GROUND_Y)
score = 0
highscore = 0
while True: # Game loop
event_handler()
d_time = clock.tick()
score += d_time / 200
highscore = max(score, highscore)
if (highscore==score and highscore>21):
exec(open("quiz1.py").read(), globals())
break
# Update game
player.update(d_time)
player.stand(GROUND_Y)
hurdle_handler.update(d_time, WINDOW_SIZE[0], 1 + score / 50)
# Show everything
show_all([player, hurdle_handler], window, int(score), int(highscore))
if has_player_hit_hurdle(player, hurdle_handler.hurdles, GROUND_Y):
player = Player(GROUND_Y)
hurdle_handler = Hurdle_Handler(GROUND_Y)
score = 0
if __name__ == "__main__": # If this is the file that was opened/run
main()
|
1993a83cb8185c34f1fa7c3d09f3f39d5173599c | onestepagain/python | /函数/2_形参和实参.py | 347 | 3.546875 | 4 | # -*- coding: utf-8 -*-
def greet(name):
print(name)
greet("libai")
#复杂点的
#关键字实参
#可以指定传入参数的顺序
#使用默认值
def greet(name, gender = "female"):
print(name)
if(gender == "female"):
print("nv")
else:
print("nan")
greet("libai")
greet("libai", "male")
|
e5e2cb8461cc1ad6eb177970312efb19e0ed2510 | zwarshavsky/introtopython | /Exercises/ex_7.3/ex_7.3.py | 609 | 3.734375 | 4 | # Use the file name mbox-short.txt as the file name
fname = input("Enter file name: ")
try:
fh = open(fname)
except:
if fname == "fuck you":
print("got you, asshole")
exit()
else:
print("unkown filename:", fname)
exit()
count = 0
f3 = 0
for line in fh:
line = line.rstrip()
if line.startswith("X-DSPAM-Confidence:"):
f1 = line.find ("0")
f2 = line[f1 : ]
f2 = float(f2)
f3 = f2 + f3
count = count + 1
if not line.startswith("X-DSPAM-Confidence:"):
continue
print("Average spam confidence:",(f3/count))
|
99b32e824ab47b13b5de0a4b625f9583897aa05c | scientiacoder/ALG | /ALG/isSameTree.py | 491 | 3.921875 | 4 | # -*- coding:utf-8 -*-
# __author__=''
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def isSameTree(self, p, q):
if p.val == q.val:
return self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)
return p is q
if __name__ == '__main__':
p = TreeNode(3)
q = TreeNode(3)
print (p.val,q.val,p == q)
|
e54874901ed785e33d41570701a6f38e5e08a543 | Alpha-W0lf/Lambda-Expressions-Anonymous-Functions---Video-Notes | /lambda_functions.py | 1,486 | 4.0625 | 4 | # # This is a sample Python script.
#
# # Press Shift+F10 to execute it or replace it with your code.
# # Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
#
#
# def print_hi(name):
# # Use a breakpoint in the code line below to debug your script.
# print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint.
#
#
# # Press the green button in the gutter to run the script.
# if __name__ == '__main__':
# print_hi('PyCharm')
#
# # See PyCharm help at https://www.jetbrains.com/help/pycharm/
# https://www.youtube.com/watch?v=25ovCm9jKfA
# Write function to compute 3x + 1
def f(x):
return 3*x + 1
print(f(2))
# Anonymous Functions = Lambda Expressions (they mean the same thing)
lambda x: 3*x + 1
g = lambda x : 3*x + 1
print(g(2))
# Combine first name and last name into a single "Full Name"
full_name = lambda fn, ln: fn.strip().title() + " " + ln.strip().title()
print(full_name(" Thomas", "GERTRUD"))
scifi_authors = ["Isaac Asimov", "Ray Bradbury", "Robert Heinlein", "Arthur C. Clarke", "Frank Herbert", "Orson Scott Card", "Douglas Adams", "H. G. Wells", "Leigh Brackett"]
# help(scifi_authors.sort)
scifi_authors.sort(key=lambda name: name.split(" ")[-1].lower())
print(scifi_authors)
def build_quadratic_function(a, b, c):
"""Returns the function f(x) = ax^2 + bx + c"""
return lambda x : a*x**2 + b*x + c
f = build_quadratic_function(2, 3, -5)
print(f(0))
print(f(1))
print(f(2))
print(build_quadratic_function(3, 0, 1)(2)) # 3x^2 + 1 evaluated for x=2
|
3df2b980200f6a5a5546fd465617d4eecc335b7a | park-in-gwon/Python_Summary | /2_ 파이썬의 코어문법/2-4_ 예외처리/4-사용자정의예외,예외만들기.py | 1,138 | 3.578125 | 4 | # 직접 예외 처리 만들기
class KimDongError(Exception):
pass
try:
word = input()
if word == 'kimdong':
raise KimDongError('오류입나이다')
except KimDongError as e:
print(e)
""" 사용자 정의 예외:
파이썬에는 내장된 함수가 있으면 사용자 정의 함수가 있듯이,
내장된 예외(지금까지 사용했던 예외)가 있으면 사용자 정의 예외도 있다.
사용자 정의 예외는 클래스에 Exception 을 상속받아서 만들 수 있으며,
에러이름은 클래스의 이름이며,
에러메시지는
raise 에러이름("에러메시지")
로 raise 문에서 에러메시지를 넣을 수도 있고,
에외 class의 __init__ 안에서
super().__init__("에러메시지")
로 예외 class 부모클래스(Exception)의 __init__ 메쏘드를 호출하면서 인자값으로 에러 메시지를 넣어 줄수도 있다.
"""
class KimSeungError(Exception):
def __init__(self):
super().__init__("김승현에러다!으악!")
try:
word = input()
if word == 'kimseung':
raise KimSeungError
except KimSeungError as e:
print(e) |
7b6616890d9a8e78db0b7cda3a3e2cc67051a820 | shivakarthikd/practise-python | /arrays/string_compress.py | 1,314 | 3.640625 | 4 | import collections
def compress_string(st):
c_dic=collections.defaultdict(int)
c_str=''
for i in st:
c_dic[i]+=1
for key,val in c_dic.items():
c_str= c_str+ key + str(val)
print(c_str)
def compress_string_1(st):
c_str=''
c=0
while(c<len(st)):
count=0
for i in st:
if st[c]==i:
count +=1
if st[c] not in c_str:
c_str+=st[c]+str(count)
c+=1
print(c_str)
def compress(s):
"""
This solution compresses without checking. Known as the RunLength Compression algorithm.
"""
# Begin Run as empty string
r = ""
l = len(s)
# Check for length 0
if l == 0:
return ""
# Check for length 1
if l == 1:
return s + "1"
# Intialize Values
last = s[0]
cnt = 1
i = 1
while i < l:
# Check to see if it is the same letter
if s[i] == s[i - 1]:
# Add a count if same as previous
cnt += 1
else:
# Otherwise store the previous data
r = r + s[i - 1] + str(cnt)
cnt = 1
# Add to index count to terminate while loop
i += 1
# Put everything back into run
r = r + s[i - 1] + str(cnt)
return r
print(compress('AbbAA')) |
b887e7a548059fd919d74dc550df235a1cdfa9f9 | mcloarec001/queens-puzzle | /Queen.py | 1,106 | 3.96875 | 4 | class Queen:
_nb_conflicts = 0
line = 0
column = 0
def __init__(self, new_line: int, new_column: int):
"""Initiate a Queen object
Args:
new_line (int): value of the line position
new_column (int): value of the column position
"""
self.line = new_line
self.column = new_column
def set_conflicts(self, nb_conflicts: int):
"""Set the number of conflicts of the queen
Args:
nb_conflicts (int): the number of conflicts to set
"""
self.nb_conflicts = nb_conflicts
def set_position(self, new_line: int, new_column: int):
"""Set the line and the column of the queen
Args:
new_line (int): value of line to set
new_column (int): value of column to set
"""
self.line = new_line
self.column = new_column
def draw(self):
"""Print the queen's position and number of conflicts"""
print(
f"Position : [{self.line}, {self.column}] ; Nombre de conflits : {self.nb_conflicts} "
)
|
91d278a8b16c3f22c70ebe829b8662088cb79f95 | Maryville-SWDV-630/ip-1-kylekanderson | /Assignment.py | 1,068 | 4.09375 | 4 | # SWDV-630: Object-Oriented Coding
# Kyle Anderson
# Week 1 Assignment
# Using Thonny, Visual Studio or command line interface expand on the Teams class defined as:
class Teams:
def __init__(self, members):
self.__myTeam = members
def __len__(self):
return len(self.__myTeam)
# 1) Add the __contains__ protocol and show whether or not 'Tim' and 'Sam' are part of our team.
def __contains__(self, member):
return member in self.__myTeam
# 2) Add the __iter__ protocol and show how you can print each member of the classmates object.
def __iter__(self):
return iter(self.__myTeam)
# 3) Determine if the class classmates implements the __len__ method.
def hasLen(self):
return hasattr(self, '__len__')
def main():
classmates = Teams(['John', 'Steve', 'Tim'])
print(len(classmates))
print(classmates.__contains__('Tim'))
print(classmates.__contains__('Sam'))
for classmate in classmates:
print(classmate)
print(classmates.hasLen())
main() |
85ccdd9e29f2242a01f1a8474a38fd45c1cc5e5e | BrantLauro/python-course | /module02/ex/ex068.py | 929 | 3.875 | 4 | from random import randint
n = c = 0
while True:
choose = ''
pc = randint(1, 10)
n = int(input('Type a number between 1 and 10: '))
if 1 <= n <= 10:
choose = input('Even or Odd? [E/O] ').strip().upper()[0]
if choose == 'E':
if (pc + n) % 2 == 0:
print(f'Pc choose {pc}. {pc + n} is Even! You won congrats!')
c += 1
else:
print(f'Pc choose {pc}. {pc + n} is Odd! You lost, sorry!')
break
elif choose == 'O':
if (pc + n) % 2 != 0:
print(f'Pc choose {pc}. {pc + n} is Odd! You won congrats!')
c += 1
else:
print(f'Pc choose {pc}. {pc + n} is Even! You lost, sorry!')
break
else:
print('[ERROR] Try Again!')
else:
print('Type a number between 1 and 10!')
print(f'You won {c} times!')
|
2cb99b70438fe3fc8eef2f2a2944d34db9b96c8b | pawelkowalski88/poker_py | /pokerthegame/api/utils/dealer.py | 2,444 | 3.75 | 4 | import random
from pokerthegame.api.utils import Card
from pokerthegame.api.utils import Hand
class Dealer:
"""Represents a dealer responsible for dealing and collecting cards.
"""
def __init__(self, table):
"""Initializes a new instance of the Dealer class with a reference to the main table.
:param table: The main table containing the cards.
"""
self.carddeck = []
self.generate_deck()
self.table = table
def generate_deck(self):
"""Generates a new fresh deck of cards from 2 to A, four colors, no jokers.
:return:
"""
self.carddeck = []
figures = [2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K", "A"]
colors = ['♠', '♣', '♥', '♦']
self.carddeck = [Card(f, c) for f in figures for c in colors]
def deal_cards_to_players(self, players):
"""Gives each player two random cards from the deck.
:param players: The players collection.
:return:
"""
for p in players:
if p.balance == 0:
players.remove(p)
p.active = False
for p in players:
if p.active:
p.cards = Hand(self.table, [], [])
p.add_card(self.pick_a_card())
p.add_card(self.pick_a_card())
def collect_cards(self, players):
"""Collects the cards from the players.
:param players: The players collection.
:return:
"""
for p in players:
p.reset_player()
def pick_a_card(self):
"""Randomly selects a card from the deck.
:return: Returns the selected card.
"""
card = self.carddeck[random.randint(0, len(self.carddeck)-1)]
while card.taken:
card = self.carddeck[random.randint(0, len(self.carddeck)-1)]
card.taken = True
return card
def add_new_card_to_table(self, round_no):
"""Puts cards on the table at the beginning of every betting round (flop, turn and river).
:param round_no: The current round number.
:return:
"""
if round_no == 0 or round_no > 3:
return
if round_no == 1:
self.table.append(self.pick_a_card())
self.table.append(self.pick_a_card())
self.table.append(self.pick_a_card())
if round_no > 1:
self.table.append(self.pick_a_card())
|
94cb6d338cf04f9080184b3b67d1f182708ffeb4 | jjcss/Python-Workshop-CSS | /FinishedProject/Python-Workshop/main.py | 2,272 | 3.875 | 4 | # import turtle from Screen
from carManager import CarManager
# import player from Player
from turtle import Screen
from player import Player
# import car_manager from CarManager
from carManager import CarManager
# import scoreboard from Scoreboard
from scoreBoard import Scoreboard
# import time
import time
def main():
#Screen set up
screen = Screen()
# Create a turtle player, a carManager & score variables to instantiate our objects
screen.setup(width=600, height=600)
screen.tracer(0)
player = Player()
manager = CarManager()
board = Scoreboard()
# Set up commands for the screen and the key the user will need to play game
screen.listen()
screen.onkey(player.moveUp, "Up")
# Create a variable to use as Flag for the game logic
"""Game Logic"""
gameOn = True
# While loop
while gameOn:
# Delaying of the screen and update
time.sleep(0.1)
screen.update()
# Create cars
manager.createCar()
# Move to cars to the right side of screen
manager.moveForward()
# Detect when the turtle player collides with a car and stop the game if this happens.
# Uses a for-loop
for car in manager.allCars:
# Use the distance you'd like but the most accurate is 15-20.
# If the distance of the car to "player" is less than 20.
if car.distance(player) < 20:
# Set flag to false
gameOn = False
# When turtle hits a car, GAME OVER.
board.gameOver()
# Detect when turtle player has reached the finish line.
if player.successfulCross():
# Return the turtle to starting
player.resetPlayer()
# Increase speed of cars.
manager.increaseSpeed()
# Every time the player crosses the level increases.
board.increaseLevel()
# Play again functionality
playAgain = screen.textinput(title="Choose", prompt="Would you like to play again? Type 'y' for yes, or 'n' no")
# If yes, clear screen and start game again.
if playAgain == 'y':
screen.clear()
main()
#Else, exit the screen on click
else:
screen.exitonclick()
main() |
8d69c58f3e7ea8aed88982fe0bb9883b2307400b | shekharpandey89/cursor-execute-python | /insert_record_execute.py | 530 | 3.8125 | 4 | #python insert_record_execute.py
#import the library
import mysql.connector
# creating connection to the database
conn = mysql.connector.connect(
host="localhost",
user="sammy",
password="password",
database="dbTest"
)
mycursor = conn.cursor()
# execute the query with their record value
query = 'INSERT INTO MOVIE (id, name, year) VALUES (%s, %s, %s)'
val = (7, "Merlin", 2001)
mycursor.execute(query,val)
# we commit(save) the records to the table
conn.commit()
print(mycursor.rowcount, "record(s) inserted.")
|
1db179934e58fe6597e3746f4b90e0b91628956c | GeraldineE/Python | /EjemploDiccionarioPython/ejemploDiccionario.py | 172 | 4.09375 | 4 | nom={}
print(nom)
for i in range(5):
nombre=input("Ingrese su nombre:")
cedula=int(input("Ingrese su cedula:"))
nom.update({nombre:cedula})
print(nom)
|
ea6c389ed39e5fb6f4096cb5101dd9c8cd5696a7 | akabraham/practice | /cci/ch1.py | 3,899 | 3.9375 | 4 | from copy import deepcopy
# 1.1
def is_all_unique(s):
return sorted(set(s)) == sorted(s)
# 1.1
def is_all_unique_no_special(s):
"""
Returns whether a string has all unique characters, without use of
additional data structures. Assumes at least 1 character.
"""
ordered = sorted(s)
for i, letter in enumerate(ordered):
if i + 1 == len(ordered):
break
if letter == ordered[i+1]:
return False
return True
# 1.2
def special_reverse(s):
"""Reverse a string without using `reverse` or anything fancy."""
length = len(s)
lst = [s[length - 1 - i] for i, letter in enumerate(s)]
return ''.join(lst)
# 1.3
def is_permutation(a, b):
"""Returns whether a is a permutation of b"""
return sorted(a) == sorted(b)
# 1.4
def replace_spaces(s):
return s.replace(' ', '%20')
# 1.5
def compress_strings(s):
"""
Returns compressed strings. If original string is shorter than the
compressed string, return the original.
e.g. 'aabcccccaaa' ==> 'a2b1c5a3'
"""
cnt = 1
compressed = []
for i, letter in enumerate(s):
if i < len(s) - 1 and letter == s[i+1]:
cnt += 1
else:
compressed.append('{}{}'.format(letter, cnt))
cnt = 1
if len(compressed) >= len(s):
return s
return ''.join(compressed)
# 1.6
def rotate_matrix(m):
"""Rotates an nxn matrix 90 degrees"""
return [list(tup) for tup in zip(*reversed(m))]
# 1.7
def zeroify_matrix(m):
"""
In an mxn matrix, if an element is 0, replaces its row and column with all
0's
"""
m1 = deepcopy(m)
cols = set()
for i, row in enumerate(m):
for j, elem in enumerate(row):
if j in cols:
m1[i][j] = 0
if elem == 0:
cols.add(j)
m1[i] = [0] * len(row)
return m1
# 1.8
def _is_substring(a, b):
"""Returns whether a is a substring of b"""
return a in b
# 1.8
def is_string_rotation(a, b):
"""
Returns whether a is a rotation of b.
e.g. 'waterbottle' is a rotation of 'erbottlewat'
"""
if sorted(a) != sorted(b):
return False
return _is_substring(a, b * 2)
if __name__ == '__main__':
assert special_reverse('theology') == 'ygoloeht'
assert special_reverse('eye') == 'eye'
assert special_reverse('g') == 'g'
assert is_permutation('hater', 'earth') is True
assert is_permutation('haters', 'earth') is False
assert is_permutation('eggs', 'eggs') is True
assert replace_spaces('Mr John Smith') == 'Mr%20John%20Smith'
assert replace_spaces('Star Wars') == 'Star%20Wars'
assert replace_spaces('google') == 'google'
assert compress_strings('aabcccccaaa') == 'a2b1c5a3'
assert compress_strings('shining') == 'shining'
m1 = [['a', 'b'],
['c', 'd']]
m2 = [['a', 'b', 'c'],
['d', 'e', 'f'],
['g', 'h', 'i']]
assert rotate_matrix(m1) == [['c', 'a'],
['d', 'b']]
assert rotate_matrix(m2) == [['g', 'd', 'a'],
['h', 'e', 'b'],
['i', 'f', 'c']]
m3 = [[0, 4, 1],
[7, 9, 2]]
assert zeroify_matrix(m3) == [[0, 0, 0],
[0, 9, 2]]
m4 = [['a', 0, 'c'],
['d', 'e', 'f'],
['g', 'h', 'i']]
assert zeroify_matrix(m4) == [[0, 0, 0],
['d', 0, 'f'],
['g', 0, 'i']]
assert _is_substring('ten', 'tenth') is True
assert _is_substring('tech', 'trench') is False
assert is_string_rotation('waterbottle', 'erbottlewat') is True
assert is_string_rotation('makeshift', 'shimakeft') is False
assert is_string_rotation('watermelon', 'meloncholywater') is False
print('all good')
|
3a1d1319869bf195731eef5fe9fedfd6ee934a9d | broepke/ProjectEuler | /009_special_pythagorean_triplet.py | 714 | 4.15625 | 4 | import time
start_time = time.time()
# A Pythagorean triplet is a set of three natural numbers, a < b < c, for which
#
# a2 + b2 = c2
# For example, 3^22 + 4^2 = 9 + 16 = 25 = 5^2.
#
# There exists exactly one Pythagorean triplet for which a + b + c = 1000.
# Find the product abc.
def pythag(a, b, c):
if a ** 2 + b ** 2 == c ** 2:
return True
return False
a = [x for x in range(1, 1000)]
for num in a:
for dig in range(num, 1000 - num):
for i in range(dig, 1000 - dig):
if num + dig + i == 1000:
if pythag(num, dig, i):
print("Question 9 =", num * dig * i)
print("Program took %s seconds to run." % (time.time() - start_time))
|
6b9287965daee6845d715d792572e9d6eeb1ed51 | lradebe/Practice-Python | /count_occurances_of_string_elements.py | 293 | 4.1875 | 4 | def count_occurances_of_list_element(List,element):
"""count occurances of a specific element in a list"""
count = 0
for i in List:
if i == element:
count += 1
print(count)
List, element = [1, 2, 3, 4, 5, 5], 5
count_occurances_of_list_element(List, element)
|
82fe749dc68cc9d3d2711078ba791b05030987a5 | Nancuharsha/ML | /mymlfolders/sixteenth.py | 2,075 | 3.78125 | 4 | #libraries to load into the program
import numpy as np
from sklearn.cluster import MeanShift
import pandas as pd
#Loading Data using pandas libirary
df = pd.read_csv('Deduplication Problem - Sample Dataset.csv')
#placeing missing data with 0
df.fillna(0,inplace=True)
#Function to convert non-numerical data to numerical data
def handle_non_numerical_data(df):
#coping all columns into columns variable
columns = df.columns.values
# Loopint through each column
for column in columns:
#below dictinoary act as hash table for the column
text_digit_vals = {}
#Getting the index of value of the element
def convert_to_int(val):
return text_digit_vals[val]
# Checking whether that column data type is int or float.If not we convert the column
if df[column].dtype != np.int64 and df[column].dtype != np.float64:
#Taking all element of the column into the list
columns_contents = df[column].values.tolist()
#Making a group of unique elements from the elements set of the column
unique_elements =set(columns_contents)
#Here x is the integer value assigned to the each unqiue element in the column
x=1
#We loop through unique element assign the integer values
for unique in unique_elements:
if unique not in text_digit_vals:
text_digit_vals[unique] = x
x+=1
#Mapping those unquie values on to the column elements
df[column] = list(map(convert_to_int,df[column]))
#returning the modified data
return df
#calling the function to convert the non-numerical data into numerical data
df = handle_non_numerical_data(df)
#classifier is called
clf = MeanShift()
#Clustering onthe data is done
clf.fit(df)
#printing the modified data
print(df)
#Getting the centroids of the clusters
cluster_centers = clf.cluster_centers_
#printing the cluster
print(cluster_centers)
|
992a0a13034760db5a7e74e97e7c4381b5578479 | zhangray758/python-final | /day03_final/3-func.py | 1,800 | 3.859375 | 4 | # Author: ray.zhang
#有参函数:传参 先定义后调用
def my_max(x,y):
if x > y:
print(x)
elif x < y:
print(y)
my_max(2,3) #直接打印结果
res=my_max(2,3) #先执行my_max 打印操作出结果,后赋值。
print(res) # 没有return,结果为NONE,等同于return None
#因此怎么样能够拿到函数的结果呢?用return,上面的可以改写为:
def m_max(x,y):
if x > y:
return x
elif x < y:
return y
m_max(4,5) #这个是没有结果的。
res=m_max(4,5)
print(res) #这样子结果就可以正确打印了。
#通常情况下,有参函数都要有个返回值,return。
#加上return语法,return为函数的结果。比如:
def foo():
print('++++++++')
return 123 #函数内部可以有多个,但只能执行一次return,整个函数就结束了。
print('++++++++')
return 456
print('+++++++=')
foo() #到这的话只返回return前面的结果
result = foo() #如果给函数结果赋值的话,那么return返回的内容会赋值给变量result
print(result) #运行看结果。
#return的返回值没有类型限制,可以返回列表、字典、字符串等。
#如: return value1,value2,vlues3
#结果为元组: (value1,value2,value3)
#空函数
def bar():
pass #占位 定义函数的方法 先空位,定义结构。然后理清思路填充代码。
#函数调用的多种表达形式:
m_max(11,22) #调用函数的语句形式
result=m_max(11,22) #调用函数的语句形式
print(result)
res=m_max(33,44)*10 #调用函数的表达式语句
print(res)
max=m_max(m_max(33,44),55) #函数调用可以当做另外一个函数的参数。
print(max) |
bd8d4ac8d21f46f51bb65f8eb69e6aec1f70030a | jeff-ali/deliverable | /billsearch-with-asterisks.py | 2,892 | 3.78125 | 4 | import os
import sys
import re
from xml.etree import ElementTree
from zipfile import ZipFile
def bill_search_asterisk(regular_expression):
"""
This method will unzip the Data Engineering Deliverable file and scan the XML files for a regex match.
It will return a list of bills that match the regex along with the text summary it contains. The matching
regex will be surrounded by asterisks.
:param regular_expression: A regular expression.
"""
# regex validation checking
try:
regex = re.compile(regular_expression)
except re.error:
print('Please provide a valid regular expression.')
return
input_zip = 'Data Engineering Deliverable - BILLSTATUS-116-sres.zip'
output_folder = input_zip[:-4]
inner_folder = 'BILLSTATUS-116-sres (3)'
bills_to_return = []
# unzip the file
try:
with ZipFile(input_zip, 'r') as zip_file:
zip_file.extractall(output_folder)
except Exception as zip_exception:
print(f'Exception while unzipping: {zip_exception}')
# parse the XML files for the regular expression
try:
for file_path in os.scandir(f'{output_folder}/{inner_folder}'):
if file_path.path.lower().endswith('.xml'):
xml_tree = ElementTree.parse(file_path.path)
root_node = xml_tree.getroot()
# if the billSummaries text does not exist, continue past this XML file
if root_node.find('.//billSummaries').text is None:
continue
bill_summary_text = root_node.find('.//billSummaries//text').text
if regex.search(bill_summary_text):
# parse the bill_summary_text to remove the <p> tags
parsed_text = ElementTree.fromstring(bill_summary_text).text
bill_string = f"{root_node.find('.//billType').text} {root_node.find('.//billNumber').text}: "
# use the tuple provided by match.span() to find the endpoints of the matched regex
# increment the remaining tuples by 2 to account for the added asterisks
matches_replaced = 0
for match in regex.finditer(parsed_text):
index1 = match.span()[0] + matches_replaced
index2 = match.span()[1] + matches_replaced
parsed_text = f'{parsed_text[:index1]}*{parsed_text[index1:index2]}*{parsed_text[index2:]}'
matches_replaced += 2
bills_to_return.append(f'{bill_string}{parsed_text}')
except Exception as search_exception:
print(f'Exception while searching: {search_exception}')
print('Found the following bills:')
for bill in bills_to_return:
print(bill)
if __name__ == "__main__":
bill_search_asterisk(sys.argv[1])
|
4965a4b329afd354418f264c4665ddeb6c6391ea | ftpatrick/bensk.github.io | /Battleship.py | 598 | 4.03125 | 4 | # Create a variable board and set it equal to an empty list.
board = []
board = []
for x in range(0,5):
board_list = ["O","O","O","O","O"]
board.append(board_list)
print board
# Exercise 5
board = []
for x in range(0,5):
board_list = ["O","O","O","O","O"]
board.append(board_list)
def print_board(board):
for row in board:
print row
print_board(board)
# Exercise 6
board = []
for x in range(0,5):
board_list = ["O","O","O","O","O"]
board.append(board_list)
def print_board(board):
for row in board:
print " ".join(row)
print_board(board)
|
28a0206bac0d6be587321c3acadadb60c213785f | JSAbrahams/mamba | /tests/resource/valid/control_flow/for_statements_check.py | 423 | 3.734375 | 4 | b: set[int] = {1,2}
for b in b:
print(b + 5)
new: int = b + 1
new = 30
print(new)
e: set[int] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
for d in e:
print(d)
print(d - 1)
print(d + 1)
for i in range(0, 34, 1):
print(i)
for i in range(0, 345 + 1, 1):
print(i)
a: int = 1
b: int = 112
for i in range(a, b, 1):
print("hello")
c: int = 2451
for i in range(a, c + 1, 20):
print("world")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.