blob_id
stringlengths 40
40
| repo_name
stringlengths 6
108
| path
stringlengths 3
244
| length_bytes
int64 36
870k
| score
float64 3.5
5.16
| int_score
int64 4
5
| text
stringlengths 36
870k
|
---|---|---|---|---|---|---|
2da7bde88eade16264f44da084e65deaf5e09983 | devnandans/Coding-Practice | /16.py | 704 | 3.703125 | 4 | #User function Template for python3
# https://practice.geeksforgeeks.org/problems/doubling-the-value4859/1/?difficulty[]=-1&page=1&query=difficulty[]-1page1#
class Solution:
def solve(self,n : int, a : list, b : int):
# Complete this function
for i in range(n):
if a[i] == b:
b = b*2
return b
#{
# Driver Code Starts
#Initial Template for Python 3
if __name__ == '__main__':
t = int(input())
for _ in range(t):
n , b = map(int, input().split())
arr = [int(x) for x in input().split()]
ob = Solution()
print(ob.solve(n, arr, b))
# } Driver Code Ends |
9b25c1ebf09f4a9812f986c6a4228233e2969034 | Darja-p/python-fundamentals-master | /Labs/13_aggregate_functions/13_03_my_enumerate.py | 387 | 4.25 | 4 | '''
Reproduce the functionality of python's .enumerate()
Define a function my_enumerate() that takes an iterable as input
and yields the element and its index
'''
def my_enumerate(sequence, start=0):
n = start
result = []
for elem in sequence:
# yield n, elem
result.append((n,elem))
n += 1
return result
print(list(my_enumerate([1,3,5,6])))
|
2462bd608102c505a93f10343ba6294d226e6795 | wookim789/baekjoon_algo_note | /동빈좌/tip/list/comprehension.py | 424 | 3.90625 | 4 | list_comprehension = [ x for x in range(10)]
print(list_comprehension)
list_comprehension = [ [x,y] for x in range(10) for y in range(2)]
print(list_comprehension)
list_comprehension = [ x for x in range(10) if x % 2 == 0]
print(list_comprehension)
list_comprehension = [ x for x in range(10) if x % 2 == 0 if x % 3 == 0]
print(list_comprehension)
list_comprehension = [[] for _ in range(3)]
print(list_comprehension)
|
48449fb6a2e629429ceadcd0e996c3d0855e33f4 | Moussaddak/holbertonschool-higher_level_programming | /0x0A-python-inheritance/2-is_same_class.py | 279 | 3.71875 | 4 | #!/usr/bin/python3
''' Documentation of Method is_same_class '''
def is_same_class(obj, a_class):
''' is_same_class is a method that checks if an object
is an instance of a given class'''
if type(obj) == a_class:
return True
else:
return False
|
85e2551aa448f79a810b20b5cb2cc0e8211dddcb | GlaucoPhd/Python_Zero2Master | /PDFsWithPython214.py | 712 | 3.625 | 4 | # PDF is a Binary file and to read it we use rb
# Count number of pages
import PyPDF2
# Tell how many pages its on the PDF
# with open('twopage.pdf', 'rb') as file:
# reader = PyPDF2.PdfFileReader(file)
# print(reader.numPages)
# Tell all the objects it has the PDF
# with open('twopage.pdf', 'rb') as file:
# reader = PyPDF2.PdfFileReader(file)
# print(reader.getPage(1))
# Rotate use a with inside of a with
with open('dummy.pdf', 'rb') as file:
reader = PyPDF2.PdfFileReader(file)
page = reader.getPage(0)
page.rotateCounterClockwise(90)
writer = PyPDF2.PdfFileWriter()
writer.addPage(page)
with open('Rotate.pdf', 'wb') as new_file:
writer.write(new_file)
|
731721d021acb735aa82f7034f15b36e6bac43c3 | fseimb/moviebot-1 | /moviebot/core/shared/utterance/utterance.py | 2,177 | 3.84375 | 4 | """Utterance classes
=======================
Classes that contain basic information about the utterance.
"""
from typing import Text, List, Dict, Any
from abc import ABC
import datetime
from moviebot.nlu.text_processing import Token, Tokenizer
class Utterance(ABC):
"""This is an abstract class for storing utterances. It contains
relevant information about the utterance like what was said, who said
it and when.
"""
def __init__(self, message: Dict[Text, Any]) -> None:
"""Initializes the Utterance class with an utterance and a timestamp.
Args:
message (Dict[Text, Any]): Dictionary should contain text and date
fields.
"""
self._utterance = message.get('text', '')
self._timestamp = self._set_timestamp(message.get('date'))
def get_source(self) -> Text:
"""Returns the name of the inherited class which represents the source
of the utterance.
Returns:
str: Name of the source class.
"""
return self.__class__.__name__
def get_text(self) -> Text:
return self._utterance
def get_timestamp(self) -> Text:
return str(self._timestamp)
def _set_timestamp(self, timestamp: int = None) -> datetime.datetime:
if timestamp:
return datetime.datetime.fromtimestamp(timestamp)
return datetime.datetime.now(datetime.timezone.utc)
def __str__(self):
return '{} - {}:\n\t{}'.format(
self.get_timestamp(),
self.get_source(),
self.get_text(),
)
class UserUtterance(Utterance):
"""Expands the base class with preprocessed and tokenized version of
the utterance.
"""
def get_tokens(self) -> List[Token]:
"""Preprocesses the utterance and returns a list of tokens.
Returns:
List[Token]: List of tokens from the utterance.
"""
if not hasattr(self, '_tokens'):
self._tokens = Tokenizer().process_text(self._utterance)
return self._tokens
class AgentUtterance(Utterance):
"""Stores the utterance that the agent returns.
"""
pass
|
29bc1e2e6b4c555d44733a50dacff92c28941866 | RashakDude/codechef_ps | /DSA Learning/Complexity Analysis + Basic Warmups/lAPIN.py | 240 | 3.609375 | 4 | for _ in range(int(input())):
x = input()
s1 = x[:len(x)//2]
if len(x) % 2==0:
s2 = x[len(x)//2:]
else:
s2 = x[len(x)//2+1:]
if sorted(s1) == sorted(s2):
print("YES")
else:
print("NO") |
e7731e7039d5a7951363d6b10740221348961ab2 | Sabbir2809/Python-For-Beginners | /Week1-Introduction/variables_and_assignment_statements.py | 807 | 4.03125 | 4 | # Variables and Assignment Statements
x = 7
y = 3
print(x+y)
total = x+y
print(total)
name1 = "Sabbir"
name2 = "Shorna"
print(name1, name2)
print("\n")
# Types
x = 10
print(type(x))
x = 10.5
print(type(x))
x = "Sabbir"
print(type(x))
print("\n")
# Arithmetic operators
multiplication = 7 * 4
print(multiplication)
add = 10 + 15
print(add)
sub = 40 - 8
print(sub)
exponentiation = 2**10
print(exponentiation)
# True Division (/) vs. Floor Division (//)
True_Division = 7.4
print(True_Division)
Floor_Division = 7//4
print(Floor_Division)
remainder = 15 % 7
print(remainder)
print("\n")
# Relational Operators
x = 105
y = 100
print(x > y)
print(x < y)
print(x == y)
print(x != y)
print(x >= y)
print(x <= y)
print("\n")
# Chaining Comparisons
x = 3
y = 10
print(1 <= x <= 5)
print(1 <= y <= 5) |
74943c7131e864c098d06cbeb904751bed7c398e | MattCrook/python-book1 | /lists/planet_list.py | 1,066 | 3.859375 | 4 | planet_list = ['Mercury', 'Mars']
planet_list.append("Jupiter")
planet_list.append("Saturn")
# ['Mercury, Mars', 'Jupiter', 'Saturn']
# print(planet_list)
planet_list.extend(["Uranus", "Neptune"])
# print(planet_list)
# ['Mercury, Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
planet_list.insert(1, "Venus")
planet_list.insert(2, "Earth")
planet_list.append("Pluto")
# print(planet_list)
# ['Mercury, Mars', 'Venus', 'Earth', 'Jupiter', 'Saturn', 'Uranus', 'Neptune', 'Pluto']
rocky_planets = planet_list[0: 3]
print(rocky_planets)
# ['Mercury, Mars', 'Venus', 'Earth']
del planet_list[7]
print(planet_list)
# ['Mercury, Mars', 'Venus', 'Earth', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
spacecraft = [
("Cassini", "Saturn"),
("Viking", "Mars"),
("Blue", "Neptune"),
("Storm", "Jupiter"),
("Cold", "Pluto"),
("Home", "Earth"),
("Hot", "Venus"),
("Close", "Mercury"),
("Low Mass", "Uranus")
]
for planet in planet_list:
for satellite in spacecraft:
if planet == satellite[1]:
print(satellite[0])
|
eb7ed6cc5a52ac7415cd467f9d85fb511692fc90 | mititer/python-study | /list3.py | 562 | 4 | 4 | data = [3, 5, 4, 6, 2, 2, 6, 4, 4, 4]
def frequency_sort(data):
dict = {}
result = []
# count the frequency and save in dict dictionary
for item in data:
print(item)
n = data.count(item)
if not dict.get(item):
dict.update({item: n})
# sort the dictionary
dict = sorted(dict.items(), key=lambda item:item[1], reverse=True)
# generate the result
for (k, v) in dict:
for i in range(v):
result.append(k)
return result
print(frequency_sort(data)) |
2ebbedc3687b5f7a45b9039b2f8805a2f751bf85 | koltpython/python-exercises-spring2020 | /section3/solution/nerdySanta-solution.py | 515 | 4.15625 | 4 | age = int(input("Ho ho hooo! What is your age?:"))
isPrime = True
while age > 0:
if age == 1:
print("Sorry, I don't have a gift for you")
else:
for number in range(2, age):
if age % number == 0:
print("Sorry, I don't have a gift for you")
isPrime = False
break
if isPrime:
print("I have a gift for you!")
age = int(input("Ho ho hooo! What is your age?:"))
if age <= 0:
print("Sorry, age is invalid.")
|
1c644a78a4f6585294b217aa12158b890eaf54df | menglaili/Lidar_filter | /run.py | 1,167 | 3.5625 | 4 | from filter import range_filter, median_filter
# from filter_withnp import range_filter, median_filter
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--filter", "-f", help="filter type: 'r' for range and 'm' for median")
args = parser.parse_args()
if args.filter:
if args.filter == 'r':
ra = input("Please enter the range_min and range_max split by comma:")
rmin, rmax = [float(num) for num in ra.split(',')]
rg = range_filter(rmin, rmax)
while True:
scan = input("Please enter one scan in list form:")
# enter s would stop the program
if scan == 's':
break
scan = list(map(float, scan.strip('[]').split(',')))
print(rg.update(scan))
elif args.filter == 'm':
D = int(input("Please enter the number D:"))
med = median_filter(D)
while True:
scan = input("please enter one scan in list form:")
# enter s would stop the program
if scan == 's':
break
scan = list(map(float, scan.strip('[]').split(',')))
print(med.update(scan))
|
2baf917e5e3b6a18be43d838045aae429c9ddc89 | jahumphr/Word-Search-Generator | /__main__.py | 9,567 | 3.609375 | 4 | # =============================================================================
# Word Search Generator Main
# Created by Josh Humphries May 2020
#
# GUI for WordSearch.py
# Created in PyQt5
# =============================================================================
from PyQt5 import QtCore, QtGui, QtWidgets
from WordSearch import WordSearch
ws = WordSearch()
# =============================================================================
# startWindow displays on program start, allows user to enter size of word search
# =============================================================================
class startWindow(object):
def setupUi(self, MainWindow):
"""initiate start window"""
MainWindow.setObjectName("MainWindow")
MainWindow.resize(250, 100)
self.centralwidget = QtWidgets.QWidget(MainWindow)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 1096, 26))
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
MainWindow.setStatusBar(self.statusbar)
#Text box for user to enter size of word search
self.size = QtWidgets.QLineEdit(self.centralwidget)
self.size.setGeometry(QtCore.QRect(20, 30, 113, 22))
#OK button to generate word search once user has entered size
self.generate = QtWidgets.QPushButton(self.centralwidget)
self.generate.setGeometry(QtCore.QRect(140, 30, 71, 21))
self.generate.clicked.connect(self.start)
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(20, 10, 221, 21))
#Error message - displays if user enters invalid size
self.error = QtWidgets.QLabel(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def start(self):
"""Called when user clicks OK button on start window to generate word search.
Checks that user entered a valid size. If size is valid, creates playWindow to
display word search."""
#If size is invalid, display error message
if (not self.size.text().isdigit() or int(self.size.text()) < 10
or int(self.size.text()) > 55):
self.error.setGeometry(QtCore.QRect(20, 50, 221, 21))
self.error.setText("Size must be between 10 and 55")
palette = self.error.palette()
color = QtGui.QColor('red')
palette.setColor(QtGui.QPalette.Foreground, color)
self.error.setPalette(palette)
self.error.show()
return 0
#If size is valid, playWindow is displayed with word search
self.error.close()
self.playWindow = playWindow(int(self.size.text()))
self.playWindow.show()
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.generate.setText(_translate("MainWindow", "OK"))
self.label.setText(_translate("MainWindow", "Enter a size between 10 and 55:"))
# =============================================================================
# playWindow is the main window operating the word search. After user enters a size
# in the start window, playWindow displays generated word search and hidden word bank.
# =============================================================================
class playWindow(QtWidgets.QWidget):
def __init__(self, size):
super().__init__()
self.size = size
self.coordsToCheck = [] #stores currently selected letters to check if winning word
self.initUI()
def initUI(self):
"""Generates word search and displays in new window"""
self.setWindowTitle('Word Search')
ws.buildArray(self.size) #Builds sizexsize matrix of hidden words
#Create tableWidget to store letter matrix with hidden words
self.tableWidget = QtWidgets.QTableWidget()
self.tableWidget.setColumnCount(self.size)
self.tableWidget.setRowCount(self.size)
self.tableWidget.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)
self.tableWidget.setShowGrid(False)
self.tableWidget.verticalHeader().hide()
self.tableWidget.horizontalHeader().hide()
self.tableWidget.setFixedWidth(2 + 19*self.size)
self.tableWidget.setFixedHeight(2 + 17*self.size)
self.tableWidget.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.tableWidget.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
#Populate tableWidget with generated word search matrix
for row in range(self.size):
for col in range(self.size):
item = QtWidgets.QTableWidgetItem(ws.letterArray[row][col])
item.setTextAlignment(QtCore.Qt.AlignVCenter | QtCore.Qt.AlignHCenter)
item.setBackground(QtGui.QColor('white'))
self.tableWidget.setItem(row, col, item)
self.tableWidget.setColumnWidth(col, 19)
self.tableWidget.setRowHeight(row, 17)
#Word bank widget to display hidden words
self.wordsToFind = QtWidgets.QTextBrowser()
self.wordsToFind.setText('\n'.join(ws.wordsAdded))
self.wordsToFind.setFont(QtGui.QFont("Calibri", 10))
self.wordsToFind.setFixedWidth(len(max(ws.wordsAdded,key=len))*13)
#Button to clear all selected letters that aren't part of winning words
self.clearButton = QtWidgets.QPushButton()
self.clearButton.clicked.connect(self.clearSelectedText)
self.clearButton.setText("Clear")
self.vBox = QtWidgets.QVBoxLayout()
self.vBox.addWidget(self.wordsToFind)
self.vBox.addWidget(self.clearButton)
#Main widget that other widgets are added to
self.centralWidget = QtWidgets.QGridLayout()
self.centralWidget.addLayout(self.vBox, 0, 0)
self.centralWidget.addWidget(self.tableWidget, 0, 1)
self.setLayout(self.centralWidget)
self.show()
self.tableWidget.cellClicked.connect(self.leftClickLetter)
def leftClickLetter(self, row, col):
"""Called whenever a letter is clicked in tableWidget. Changes background
color of letter cell to indicate it's been selected, or changes background
color back to normal if letter has been clicked again to de-select.
Checks for winning word each time a new letter is selected."""
item = self.tableWidget.item(row, col)
if (item.background() == QtGui.QColor('white')):
item.setBackground(QtGui.QColor(51,153,255))
self.coordsToCheck.append((row,col)) #adds selection to list to check for win
elif (item.background() == QtGui.QColor(51,153,255)):
item.setBackground(QtGui.QColor('white'))
self.coordsToCheck.remove((row,col)) #removes selection from list if user de-selects
elif (item.background() == QtGui.QColor('lightgreen')):
item.setBackground(QtGui.QColor(0,204,204))
self.coordsToCheck.append((row,col))
elif (item.background() == QtGui.QColor(0,204,204)):
item.setBackground(QtGui.QColor('lightgreen'))
self.coordsToCheck.remove((row,col))
#If coordinates in coordsToCheck are a winning word, the
#word is highlighted green
if self.wordFoundCheck(self.coordsToCheck):
for coordPair in self.coordsToCheck:
item = self.tableWidget.item(coordPair[0], coordPair[1])
item.setBackground(QtGui.QColor('lightGreen'))
self.coordsToCheck = []
self.tableWidget.clearSelection()
def wordFoundCheck(self, coordsToCheck):
"""Checks for win, comparing coordinates in coordsToCheck with
coordinates stored in WordSearch.wordLocations. If there's a win,
returns True and word is removed from word bank."""
for word in ws.wordLocations:
if sorted(ws.wordLocations[word]) == sorted(self.coordsToCheck):
ws.wordsAdded.remove(word)
self.wordsToFind.setText('\n'.join(ws.wordsAdded))
self.wordsToFind.show()
return True
return False
def clearSelectedText(self):
"""Called when user clicks clear button. All selected letters that
are not part of a winning word are cleared on Word Search table"""
for coordPair in self.coordsToCheck:
item = self.tableWidget.item(coordPair[0], coordPair[1])
if item.background() == QtGui.QColor(0,204,204):
item.setBackground(QtGui.QColor('lightGreen'))
else:
item.setBackground(QtGui.QColor('white'))
self.coordsToCheck = [] #selected letters removed from coordsToCheck
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = startWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
|
c423abe29e99d2df62b5c0b6cbd192c07ed6ff26 | bencripps/euler | /python/6.py | 353 | 3.59375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: ben_cripps
# @Date: 2015-01-03 14:06:53
# @Last Modified by: ben_cripps
# @Last Modified time: 2015-01-03 14:29:44
import math
sum_of_squares = math.pow(reduce(lambda x,y: x+y, range(101)), 2)
square_each = sum([math.pow(x, 2) for x in range(101)])
print(abs(sum_of_squares - square_each)) |
b9daa162cf130db481ff0e2dcd9f0aebc0861acc | OhMesch/Algorithm-Problems | /48-Rotate-Image.py | 1,059 | 3.9375 | 4 | '''
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Note:
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
'''
class Solution():
def rotate(self,arr):
n=len(arr)
for j in range(n//2):
for i in range(j,n-1-j):
a1 = arr[j][i]
a2 = arr[i][n-j-1]
a3 = arr[n-j-1][n-i-1]
a4 = arr[n-i-1][j]
arr[j][i],arr[i][n-j-1],arr[n-j-1][n-i-1],arr[n-i-1][j] = a4,a1,a2,a3
driver = Solution()
print('\n')
print('1')
print('**',driver.rotate([[1,2,3],[4,5,6],[7,8,9]]))
print('-- [[7, 4, 1], [8, 5, 2], [9, 6, 3]]')
print('2')
print('**',driver.rotate([[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]))
print('-- [[15, 13, 2, 5], [14, 3, 4, 1], [12, 6, 8, 9], [16, 7, 10, 11]]')
print('3 ')
print('**',driver.rotate([[1,2,3,4,5,6,7],[8,9,10,11,12,13,14],[15,16,17,18,19,20,21],[22,23,24,25,26,27,28],[29,30,31,32,33,34,35],[36,37,38,39,40,41,42],[43,44,45,46,47,48,49]]))
print('-- ') |
3588b9081e58db0c2c416b8248d1a7812f88c7e9 | Yue1Harriet1/GA-Data-Science | /Lab_20140910_Dictionaries.py | 1,783 | 3.5 | 4 | #Lab: Data Munging - Dictionaries
import requests
import csv
web_request = requests.get('http://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data')
web_data = web_request.text
#1. Get count of each instance of education (index 3)
reader = csv.reader(web_data.splitlines())
EdDict = {}
for row in reader:
if row:
if row[3] in EdDict:
EdDict[row[3]] = EdDict[row[3]] + 1 #can also use EdCounter[row[3]] += 1
else:
EdDict[row[3]] = 1
print "Question 1: Count by Education"
for key, value in sorted(EdDict.iteritems()):
print key+':', value
#2. Get count of combinations of gender and education (index 9)
reader = csv.reader(web_data.splitlines())
EdGendDict = {}
for row in reader:
if row:
if str(row[3])+str(row[9]) in EdGendDict:
EdGendDict[str(row[3]) + str(row[9])] += 1
else:
EdGendDict[str(row[3]) + str(row[9])] = 1
print '\n', "Question 2: Count by Gender/Education"
for key, value in sorted(EdGendDict.iteritems()):
print key+':', value
#3. Find average hours per week (index 12) for groups above
reader = csv.reader(web_data.splitlines())
HrsDict = {}
for row in reader:
if row:
if str(row[3])+str(row[9]) in HrsDict:
HrsDict[str(row[3]) + str(row[9])] += int(row[12])
else:
HrsDict[str(row[3]) + str(row[9])] = int(row[12])
print '\n', "Question 3: Average Hours by Gender/Education"
for key, value in sorted(HrsDict.iteritems()):
print key+':', value/EdGendDict[key]
#4. Is any sample size too small to have a meaningful average?
'''
Preschool Female=31 (n=16)
Preschool Male=38 (n=35)
1-4th Female=31 (n=46)
1-4th Male=40 (n=122)
12th Female=31(n=144)
12th Male=37 (n=289)
Sample sizes for these groups are on the smaller side as compared to
other groups, simply comparing numbers in 2 and 3.
'''
|
4d860740ad16d4600f04a14ef81a384275f64a3d | gschen/sctu-ds-2020 | /1906101031-王卓越/作业.py/20200301-text/选做-01.py | 460 | 3.9375 | 4 | # 6. (使用def函数完成)编写一个函数,输入n为偶数时,调用函数求1/2+1/4+...+1/n,当输入n为奇数时,调用函数1/1+1/3+...+1/n
from fractions import Fraction
def method(n):
sums=0
if n%2==0:
x=2
while x<=n:
sums+=Fraction(1,x)
x+=2
return sums
else:
x=1
while x<=n:
sums+=Fraction(1,x)
x+=2
return sums
print(method(7))
|
ff7a815562be05eb391c00c5e77680844d3aba4b | Hikky-8man/SixthForm-Python | /streetly work/sorting/Sorting and searching pyglet/sortingAndSearching.py | 12,153 | 3.671875 | 4 | #The sorting and searching program but with a GUI
#Date created: 10/03/2021
import pyglet
from pyglet.window import key
from pyglet.window import mouse
class Window():
def __init__(self,width,height):
self.window=pyglet.window.Window(width,height)
self.batch=pyglet.graphics.Batch()
self.active=None #the current class that is using the screen
self.size=30 #sets a common text size
self.console=Console() #creates a new console structure
def getConsole(self):
return self.console
def getSize(self):
return self.size
#changes the class which is currently using the window
def setActive(self,active):
self.active=active
print ("[ACTIVE] Set to "+self.active.toString()+"\n")
def getWidth(self):
return self.window.width
def getHeight(self):
return self.window.height
#returns the sprite batch used for drawing things on the screen
def getBatch(self):
return self.batch
#empties the batch list
def overwrite(self):
self.batch=pyglet.graphics.Batch()
#has to be done because of how event handlers work in pyglet
#cant do @self.window.event
def run(self):
window=self.window
@window.event
def on_draw():
#print("[DRAWING] \n")
window.clear()
#self.active.draw()
self.batch.draw()
#handles mouse input events for the other classes
@window.event
def on_mouse_press(x,y,symbol,modifier):
#passes the mouse inputs to the relevant classes submit method
self.active.submitMouseClick(x,y)
@window.event
def on_mouse_motion(x,y,dx,dy):
#passes the mouse inputs to the relevant classes submit method
self.active.submitMouseHover(x,y,dx,dy)
@window.event
def on_key_press(symbol,modifier):
if symbol==key.ESCAPE:
print ("ESC")
quit()
else:
#passes the key input to the relevant classes submit method
self.active.submitKeyPress(symbol,modifier)
#---------------------Main Menu-------------------------
class MainMenu():
def __init__(self,window):
self.window=window #"remembers" the window
self.window.setActive(self) #sets the active window to MM
self.window.overwrite() #clears the window
#retrieves the current dimensions of the screen
self.height=self.window.getHeight()
self.width=self.window.getWidth()
self.quater=self.height/4 #quater of the screen
#creates all of the label sto be used
self.bubble=pyglet.text.Label("Bubble sort",
x=0,y=self.height-(self.quater),
anchor_x="left",anchor_y="bottom",
font_size=self.window.getSize(),
batch=self.window.getBatch())
self.insersion=pyglet.text.Label("Insersion sort",
x=0,y=self.height-(self.quater*2),
anchor_x="left",anchor_y="bottom",
font_size=self.window.getSize(),
batch=self.window.getBatch())
self.linear=pyglet.text.Label("Linear search",
x=0,y=self.quater,
anchor_x="left",anchor_y="bottom",
font_size=self.window.getSize(),
batch=self.window.getBatch())
pyglet.text.Label("press the [ESC] to quit",
x=0,y=self.height,
anchor_x="left",anchor_y="top",
font_size=20,
batch=self.window.getBatch())
def submitKeyPress(self,symbol,modifier):
pass
def submitMouseClick(self,x,y):
#print ("[MOUSE PRESS] X:"+str(x)+" Y:"+str(y)+"\n")
if y>(self.quater*3):
bubble=BubbleSort(self.window)
def submitMouseHover(self,x,y,dx,dy):
#print ("[Hover]: X:"+str(x)+" Y:"+str(y)+" DX:"+str(dx)+" DY:"+str(dy)+"\n")
if y>(self.quater*3):
self.bubble.x=10
self.insersion.x=0
self.linear.x=0
elif y<(self.quater*3) and y>(self.height/4)*2:
self.bubble.x=0
self.insersion.x=10
self.linear.x=0
elif y<(self.quater*2) and y>self.quater:
self.bubble.x=0
self.insersion.x=0
self.linear.x=10
else:
self.bubble.x=0
self.insersion.x=0
self.linear.x=0
def toString(self):
return "MainMenu"
#---------------------Bubble Sort-------------------------
class BubbleSort():
def __init__(self,window):
self.window=window #"remembers" the window
self.window.setActive(self) #sets the window to B.S
self.window.overwrite() #clears the sprite batch
self.console=self.window.getConsole() #retrieves and emembers the console
self.console.overwrite() #clears the console
self.input=False #Flag which enables or disables keyboard inputs (except for ESC key)
self.inputText=">" #String which contains the text that the user entered
self.array=[2,5,4,1,3]#generates a default array
self.quater=self.window.getHeight()/4 #quater of the screen
self.state=None #current state of the screen 0=menu 1=sort 2=array
self.menuState() #sets the state of the window to menu
def menuState(self):
self.state=0
self.window.overwrite()#emties the batch list
contents=pyglet.text.Label("Current list: "+str(self.array),
x=0,y=self.window.getHeight(),
anchor_x="left",anchor_y="top",
font_size=self.window.getSize(),
batch=self.window.getBatch())
self.array=pyglet.text.Label("Make a new list",
x=0,y=self.quater*3,
anchor_x="left",anchor_y="bottom",
font_size=self.window.getSize(),
batch=self.window.getBatch())
self.sort=pyglet.text.Label("Sort the current array",
x=0,y=self.quater*2,
anchor_x="left",anchor_y="bottom",
font_size=self.window.getSize(),
batch=self.window.getBatch())
def sortState(self):
self.state=1
self.window.overwrite()
def arrayState(self):
window=self.window
self.state=2
self.window.overwrite()
print ("[ArrayState]outputting data")
self.console.getData(self.window.getHeight(),
self.window.getSize(),
self.window.getBatch())
def _input(data):
self.console.add(data)
self.inputText=">"
self.input=True
position=0
self.inputLabel=pyglet.text.Label(self.inputText,
x=0,y=10,
anchor_x="left",anchor_y="bottom",
font_size=self.window.getSize(),
batch=self.window.getBatch())
_input("How long do you want the list to be?")
def toString(self):
return "BubbleSort"
def submitKeyPress(self,symbol,modifier):
if self.state==2: #array state
if self.input==True:
if symbol==key.ENTER:
self.console.add(self.inputText) #adds the text to the console
self.inputText=">" #Resets the "text field"
self.input=False #disables keyboard input (except for ESC)
#self.console.getData(self.window.getHeight,
# self.window.getSize(),
# self.window.getBatch())
elif symbol==key.BACKSPACE:
if self.inputText!=">":
self.inputText[:-1]
elif symbol==key._0 or symbol==key.NUM_0:
self.inputText+="0"
elif symbol==key._1 or symbol==key.NUM_1:
self.inputText+="1"
elif symbol==key._2 or symbol==key.NUM_2:
self.inputText+="2"
elif symbol==key._3 or symbol==key.NUM_3:
self.inputText+="3"
elif symbol==key._4 or symbol==key.NUM_4:
self.inputText+="4"
elif symbol==key._5 or symbol==key.NUM_5:
self.inputText+="5"
def submitMouseClick(self,x,y):
if self.state==0: #Menu state
if y>self.window.getHeight()-self.quater: #"Make a new list" option
state=1 #array state
self.arrayState()
def submitMouseHover(self,x,y,dx,dy):
if self.state==0: #Menu state
if y>self.window.getHeight()-self.quater:
self.array.x=10
self.sort.x=0
elif y<self.window.getHeight()-self.quater and y>self.quater*2:
self.array.x=0
self.sort.x=10
else:
self.array.x=0
self.sort.x=0
#---------------------Insersion Sort----------------------
#---------------------Linear Search-----------------------
#---------------------Console-----------------------------
#A queue structure which contains strings
class Console:
def __init__(self):
self.console=[None,None,None,None,None,None,None,None,None,None]
def length(self):
count=0
for item in self.console:
if item!=None:
count+=1
return count
def add(self,data):
if self.length()<=10:
print (str(self.length()))
self.console[len(self.console)-1]=data
else:
count=1
while (count!=10):
self.console[count-1]=console[count]
count+=1
self.console[9]=data
#self.getData()
print ("[CONSOLE] '"+data+"' added")
def overwrite(self):
self.data=[]
def getData(self,height,size,batch): #draws the contents of the console onto the screen
if self.length()!=0:
pos=10
for item in self.console:
if item!=None:
label=pyglet.text.Label(item,
x=0,y=height-pos,
anchor_x="left",anchor_y="bottom",
font_size=size,
batch=batch)
pos+=1
print ("[CONSOLE] YEAH")
print ("[CONSOLE] DONE!")
else:
print ("[CONSOLE] Nothing to output")
# |
# V Empty
#State flow: window -> mainMenu <->[BubbleSort, InsersionSort, LinearSearch]
#sets the window to the main menu and runs it in an inkfinite loop
print ("[CREATING] window \n")
window=Window(800,500)
print ("[CREATING] menu screen \n")
menu=MainMenu(window)
print ("[LAUNCHING] window \n")
window.run()
print ("[RUNNING] menu screen)\n")
pyglet.app.run()
|
44b5ced3205ab981957c4a67d858138dd6018501 | admarko/TicTacToe | /TicTacToe.py | 7,327 | 4.25 | 4 | '''
Simple Tic Tac Toe game that lets users play in Terminal vs. 3 different AIs
By Alex Markowitz
github.com/admarko/TicTac/Toe
Last Modified January 2019
'''
import random
#############################
#### Board Class ####
#############################
class Board:
def __init__(self):
self.game_board = [["-","-","-"],["-","-","-"],["-","-","-"]]
self.moves = 0
self.player_score = [0,0,0]
self.ai_score = [0,0,0]
self.leader = ""
self.is_game_over = False
def print_board(self):
print " 1 2 3"
for i in range(3):
print str(i+1) + " " + "|".join(self.game_board[i])
print ""
def reset_board(self):
self.game_board = [["-","-","-"],["-","-","-"],["-","-","-"]]
self.moves = 0
self.is_game_over = False
def add_move(self, move, r, c):
self.game_board[r][c] = move
self.moves += 1
self.check_board(move)
def row_winner(self, move):
for i in range(3):
if self.game_board[i][0] == self.game_board[i][1] == self.game_board[i][2] == move:
return True
return False
def col_winner(self, move):
for i in range(3):
if self.game_board[0][i] == self.game_board[1][i] == self.game_board[2][i] == move:
return True
return False
def diag_winner(self, move):
return (self.game_board[0][0] == self.game_board[1][1] == self.game_board[2][2] == move) \
or (self.game_board[2][0] == self.game_board[1][1] == self.game_board[0][2] == move)
def is_game_won(self, move):
return self.row_winner(move) or self.col_winner(move) or self.diag_winner(move)
def is_full(self):
return self.moves == 9
def assign_current_leader(self):
if self.player_score[0] > self.ai_score[0]:
self.leader = player_name
elif self.player_score[0] < self.ai_score[0]:
self.leader = "AI"
else:
self.leader = ""
def update_scores(self, move):
if move == "X":
self.player_score[0] += 1 # player win
self.ai_score[1] += 1 # ai lose
round_winner = player_name
elif move == "O":
self.ai_score[0] += 1 # ai win
self.player_score[1] += 1 # player lose
round_winner = "AI"
else:
self.ai_score[2] += 1
self.player_score[2] += 1
return
return round_winner
def end_of_game(self):
while True:
answer = str(raw_input("Would you like to play again? [Y/N]: ")).capitalize()
if answer == "N":
print "*Final score* "
print "{}: {}-{}-{}".format(player_name, self.player_score[0], self.player_score[1], self.player_score[2])
print "AI: {}-{}-{}".format(self.ai_score[0], self.ai_score[1], self.ai_score[2])
print self.leader + " wins!\n" if self.leader else "Tie - Everyone's a winner!"
exit()
elif answer == "Y":
self.reset_board() # loser starts next game
break
else:
print("Invalid option, please select either [Y] for Yes or [N] for No")
def check_board(self, move):
if self.is_full() and not self.is_game_won(move):
print "\nTie! The Board is full - game over!"
self.print_board()
self.player_score[2] += 1
self.ai_score[2] += 1
self.update_scores("Tie")
print "This round ends in a Tie!"
self.is_game_over = True
elif self.is_game_won(move):
round_winner = self.update_scores(move)
self.print_board()
print round_winner + " wins this round!"
self.assign_current_leader()
self.is_game_over = True
if self.is_game_over:
self.end_of_game()
#############################
#### AI Methods #############
#############################
# Helper for Minimax algo for the Unbeatable AI
def evaluate(board):
if board.is_game_won("O"):
return 10
elif board.is_game_won("X"):
return -10
return 0
# Minimax algorithm (helper for the unbeatable AI)
# Help from: https://www.geeksforgeeks.org/minimax-algorithm-in-game-theory-set-3-tic-tac-toe-ai-finding-optimal-move/
def minimax(board, depth, isMax):
score = evaluate(board)
#maximizer wins, return evaluated score
if score == 10:
return score
#minimizer won, return evaluated score
if score == -10:
return score
# if no more moves and no winner, then its a tie
if board.is_full():
return 0
# if this is maximizer's move
if isMax:
best = -1000
for i in range(3):
for j in range(3):
if board.game_board[i][j] == "-":
board.game_board[i][j] = "X"
best = max(best, minimax(board, depth+1, not isMax))
board.game_board[i][j]= "-"
return best
else: # the minimizer's move
best = 1000
for i in range(3):
for j in range(3):
if board.game_board[i][j] == "-":
board.game_board[i][j] = "O"
best = min(best, minimax(board, depth+1, not isMax))
board.game_board[i][j] = "-"
return best
# Choose which AI to play against based on user input
def get_ai_type(ai_name):
# Iteratively scrolls from top left to bottom right corner and moves in the next
# open spot
def simple_ai(board):
print "\nSimple AI's move:"
for i in range(3):
for j in range(3):
if board.game_board[i][j] == "-":
board.add_move("O", i, j)
board.print_board()
return
# AI that randomly places valid move
def random_ai(board):
print "\nRandom AI's move:"
while True:
row = random.randint(0,2)
col = random.randint(0,2)
if board.game_board[row][col] == "-":
board.add_move("O", row, col)
board.print_board()
return
def unbeatable_ai(board):
print "\nUnbeatable AI's move:"
best_value = float('-inf')
best_move_row = -1
best_move_col = -1
for i in range(3):
for j in range(3):
if board.game_board[i][j] == "-":
board.game_board[i][j] = "O"
move_value = minimax(board, 0, False)
board.game_board[i][j] = '-'
if (move_value > best_value):
best_move_row = i
best_move_col = j
best_value = move_value
board.add_move("O", best_move_row, best_move_col)
board.print_board()
return
if ai_name == "random_ai":
return random_ai
elif ai_name == "unbeatable_ai":
return unbeatable_ai
else:
return simple_ai
#############################
#### User + Main Methods ####
#############################
# Method to
def user_move(board):
while True:
print "It's your turn, where would you like to move?"
try:
row = int(raw_input("row: "))
col = int(raw_input("col: "))
except NameError:
print("Must use integers to play tic tac toe!")
continue
if row < 1 or row > 3 or col < 1 or col > 3 or board.game_board[row-1][col-1] != "-":
print("Invalid row or column, retry")
continue
else:
board.add_move("X", row-1, col-1)
board.print_board()
return
def select_opponent():
while "Invalid Response":
ai_input = str(raw_input("\nWhich AI do you want to play against? Random, Simple, or Unbeatable [R/S/U]: \n")).capitalize()
if ai_input == "R":
return "random_ai"
elif ai_input == "S":
return "simple_ai"
elif ai_input == "U":
return "unbeatable_ai"
else:
print("Invalid option, please select either [R] for Random, [S] for Simple or [U] Unbeatable")
# Main game loop
if __name__ == "__main__":
player_name = str(raw_input("\nWelcome to Tic-Tac-Toe. What is your name: \n")).capitalize()
ai_name = select_opponent()
ai_move = get_ai_type(ai_name)
b = Board()
print "\nHi " + player_name + ", you get to start"
b.print_board()
while True:
user_move(b)
ai_move(b)
|
95517cca4648410eed392796931934ae062ab4cf | listenzcc/kata_trainings | /Counting_Change_Combinations.py | 1,490 | 4.1875 | 4 | # code: utf-8
'''
Write a function that counts how many different ways you can make change for an amount of money, given an array of coin denominations. For example, there are 3 ways to give change for 4 if you have coins with denomination 1 and 2:
1+1+1+1, 1+1+2, 2+2.
The order of coins does not matter:
1+1+2 == 2+1+1
Also, assume that you have an infinite amount of coins.
Your function should take an amount to change and an array of unique denominations for the coins:
count_change(4, [1,2]) # => 3
count_change(10, [5,2,3]) # => 4
count_change(11, [5,7]) # => 0
'''
def count_change_good(money, coins):
if money < 0:
return 0
if money == 0:
return 1
if money > 0 and not coins:
return 0
return count_change(money-coins[-1], coins) + count_change(money, coins[:-1])
def count_change(money, coins):
# your implementation here
coins.sort(reverse=True)
print(money, coins)
def one_step(remain, amount, cap):
for c in coins:
if c >= cap:
continue
if remain == c:
amount += 1
if remain > c:
amount = one_step(remain-c, amount, cap)
cap = c
return amount
amount = one_step(money, 0, max(coins)+1)
print(amount)
return amount
pass
count_change(4, [1, 2]) # => 3
count_change(10, [5, 2, 3]) # => 4
count_change(11, [5, 7]) # => 0
|
d47db1504e51fe3ac705bdc423d881a587e3e97f | Aasthaengg/IBMdataset | /Python_codes/p03998/s585111124.py | 388 | 3.625 | 4 | a=list(input())
b=list(input())
c=list(input())
order='a'
while True:
if order=='a':
if len(a)==0:
print('A')
break
else:
order=a[0]
a=a[1:]
elif order=='b':
if len(b)==0:
print('B')
break
else:
order=b[0]
b=b[1:]
elif order=='c':
if len(c)==0:
print('C')
break
else:
order=c[0]
c=c[1:] |
adde0602c9bb25855809b05b56e30ab25a81490f | pasharik95/PythonTasks | /PracticalWork#1/task1.py | 3,759 | 3.875 | 4 | #!/usr/bin/env python
"""
Python. Practical Work #1
This code allows to send packages from input file to addressant(output file)
"""
END_PACKAGE = "end"
FILENAME_EXTENSION = ".txt"
# Addressants
IVASYK = 'I'
DMYTRO = 'D'
OSTAP = 'O'
LESYA = 'L'
# Messages for result of working
EMPTY_FILE_MESSAGE = "File is empty!!!"
NOT_OPEN_MESSAGE = "Can not open file"
SUCCESS_MESSAGE = "Files is created!!!"
def main(path_file='messages'):
"""
Main function of this program.
This function shows result of working program
Parameters
----------
path_file : str
Name of input file
"""
try:
# get all packages
packages = read(path_file + FILENAME_EXTENSION)
# get dictionary with addressants as key and list of packages for addressant as value.
dict = packagesToDictionary(packages)
for item in dict:
# create files with packages for each addressant
generateFile(item + FILENAME_EXTENSION, dict[item])
print SUCCESS_MESSAGE
except IOError:
print NOT_OPEN_MESSAGE
except Exception as e:
print e.message
def read(path_file):
"""
Read lines from file.
If file can not opened then will be thrown exception IOError.
If file is empty then will be thrown my exception.
Parameters
----------
path_file : str
Name of input file
Returns
-------
list
All lines from input file
"""
# open file for read
with open(path_file, 'r') as f:
lines = f.readlines()
if not lines:
raise Exception(EMPTY_FILE_MESSAGE)
return lines
def packagesToDictionary(packages):
"""
This function formates dictionary with addressants as key,
and list of packages for addressant as value.
Parameters
----------
packages : list of str
All packages from input file
Returns
-------
dict
Dictionary with addressants as key,
and list of packages for addressant as value
"""
dict = {IVASYK: [], DMYTRO: [], OSTAP: [], LESYA: []}
for package in packages:
# get all addressants who gets packege
addressants = getAddressants(package.strip('\n'))
# add package to items of dictionary
if addressants:
for addressant in addressants:
dict[addressant].append(package)
return dict
def getAddressants(package):
"""
This function finds addressants whose has to get package.
Parameters
----------
package : str
One package
Returns
-------
list
List of addressants
None
if package is empty
"""
addressants = []
if not package:
return
# Checking package for Lesya
if package.split()[-1] == 'end':
addressants.append('L')
# Checking package for Ivasyk
if len(package) % 2 == 0:
addressants.append('I')
# Checking package for Dmytro
elif package[0].isupper():
addressants.append('D')
# Checking package for Ostap
elif not addressants:
addressants.append('O')
return addressants
def generateFile(pathFile, packages):
"""
This function generates file with packages.
Parameters
----------
pathFile : str
Name of new file
packages : list of str
Packages for one addressant
"""
# open file for write
with open(pathFile, 'w') as file:
file.writelines(packages)
if __name__ == "__main__":
main()
|
f1e8a40404f58f979a280cf0eedb200b12397e85 | evafengan/python06 | /07/0702.py | 3,273 | 3.59375 | 4 | # import logging
# from time import sleep, ctime
#
#
# """单线程启动"""
# #调用日志
# logging.basicConfig(level=logging.INFO)
#
# #设置2个线程
# def loop0():
# logging.info("start loop0 at " + ctime())
# sleep(4)
# logging.info("end loop0 at " + ctime())
#
# def loop1():
# logging.info("start loop1 at " + ctime())
# sleep(6)
# logging.info("end loop1 at " + ctime())
#
# def main():
# logging.info("start all at " + ctime())
# loop0()
# loop1()
# #顺序执行loop0,loop1
# sleep(6)
# logging.info("end all at " + ctime())
#
# if __name__ == '__main__':
# main()
#
# """多线程启动,_thread是将线程同时启动"""
# import logging
# from time import sleep, ctime
# import _thread
#
#
# logging.basicConfig(level = logging.INFO)
#
# def loop0():
# logging.info("start loop0 at " + ctime())
# sleep(4)
# logging.info("end loop0 at " + ctime())
#
# def loop1():
# logging.info("start loop1 at " + ctime())
# sleep(6)
# logging.info("end loop1 at " + ctime())
#
# def main():
# logging.info("start all at " + ctime())
# _thread.start_new_thread(loop0, ())
# _thread.start_new_thread(loop1, ())
# #主main要sleep,不然main主线程运行结束时,会把子进程loop0,loop1关闭
# sleep(6)
# logging.info("end all at " + ctime())
#
# if __name__ == '__main__':
# main()
#
# """多线程启动,threading是基于_thread的功能"""
# import logging
# import threading
# from time import ctime, sleep
#
# logging.basicConfig(level=logging.INFO)
#
# loops = [2, 4]
#
#
# def loop(nloop, nsec):
# logging.info("start loop " + str(nloop) + " at " + ctime())
# sleep(nsec)
# logging.info("end loop " + str(nloop) + " at " + ctime())
#
#
# def main():
# logging.info("start all at " + ctime())
# threads = []
# nloops = range(len(loops))
# for i in nloops:
# # 调用loop函数,args参数传给loop
# t = threading.Thread(target=loop, args=(i, loops[i]))
# threads.append(t)
# for i in nloops:
# threads[i].start()
# for i in nloops:
# threads[i].join()
# logging.info("end all at " + ctime())
#
#
# if __name__ == '__main__':
# main()
"""自定义多线程启动,把threading继承成mythread"""
import logging
import threading
from time import ctime, sleep
logging.basicConfig(level=logging.INFO)
loops = [2, 4]
#新建MyThread类,继承threading.Thread
class MyThread(threading.Thread):
def __init__(self, func, args, name=''):
threading.Thread.__init__(self)
self.func = func
self.args = args
self.name = name
def run(self):
self.func(*self.args)
def loop(nloop, nsec):
logging.info("start loop " + str(nloop) + " at " + ctime())
sleep(nsec)
logging.info("end loop " + str(nloop) + " at " + ctime())
def main():
logging.info("start all at " + ctime())
threads = []
nloops = range(len(loops))
for i in nloops:
t = MyThread(loop, (i,loops[i]), loop.__name__)
threads.append(t)
for i in nloops:
threads[i].start()
for i in nloops:
threads[i].join()
logging.info("end all at " + ctime())
if __name__ == '__main__':
main()
|
c53e0d7ba455cc35b370c421e011a775a33d5d00 | Vinayak7103/Text_Mining_Assignments | /Text_Mining_1.py | 4,399 | 3.734375 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Text Mining 1
# ### TASK: NATURAL LANGUAGE PROCESSING (TEXT MINING)
# Perform sentimental analysis on the Elon-musk tweets (Exlon-musk.csv)
#
# IMPORTING LIBRARIES
# In[1]:
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import string # special operations on strings
import spacy # language models
from matplotlib.pyplot import imread
from matplotlib import pyplot as plt
from wordcloud import WordCloud
get_ipython().run_line_magic('matplotlib', 'inline')
import warnings
import re
import string
import nltk
# IMPORTING DATA
# In[8]:
df=pd.read_csv("C:/Users/vinay/Downloads/Elon_musk.csv",encoding = "ISO-8859-1")
# In[9]:
pd.set_option('display.max_colwidth',200)
warnings.filterwarnings('ignore',category=DeprecationWarning)
# In[10]:
df.head()
# In[11]:
df=df.drop(['Unnamed: 0'],axis=1)
# In[12]:
df
# In[13]:
df = [Text.strip() for Text in df.Text] # remove both the leading and the trailing characters
df = [Text for Text in df if Text] # removes empty strings, because they are considered in Python as False
df[0:10]
# In[14]:
# Joining the list into one string/text
text = ' '.join(df)
text
# In[15]:
#Punctuation
no_punc_text = text.translate(str.maketrans('', '', string.punctuation)) #with arguments (x, y, z) where 'x' and 'y'
# must be equal-length strings and characters in 'x'
# are replaced by characters in 'y'. 'z'
# is a string (string.punctuation here)
no_punc_text
# In[16]:
#Tokenization
import nltk
from nltk.corpus import stopwords
nltk.download('punkt')
nltk.download('stopwords')
from nltk.tokenize import word_tokenize
text_tokens = word_tokenize(no_punc_text)
print(text_tokens[0:50])
# In[17]:
len(text_tokens)
# In[18]:
#Remove stopwords
import nltk
from nltk.corpus import stopwords
nltk.download('punkt')
nltk.download('stopwords')
my_stop_words = stopwords.words('english')
my_stop_words.append('the')
no_stop_tokens = [word for word in text_tokens if not word in my_stop_words]
print(no_stop_tokens[0:40])
# In[19]:
#Noramalize the data
lower_words = [Text.lower() for Text in no_stop_tokens]
print(lower_words[0:25])
# In[20]:
#Stemming
from nltk.stem import PorterStemmer
ps = PorterStemmer()
stemmed_tokens = [ps.stem(word) for word in lower_words]
print(stemmed_tokens[0:40])
# In[21]:
# NLP english language model of spacy library
nlp = spacy.load('en_core_web_sm')
# In[22]:
# lemmas being one of them, but mostly POS, which will follow later
doc = nlp(' '.join(no_stop_tokens))
print(doc[0:40])
# In[23]:
lemmas = [token.lemma_ for token in doc]
print(lemmas[0:25])
# PERFORMING FEATURE EXTRACTION
# In[25]:
from sklearn.feature_extraction.text import CountVectorizer
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(lemmas)
# In[26]:
print(vectorizer.vocabulary_)
# In[27]:
print(vectorizer.get_feature_names()[50:100])
print(X.toarray()[50:100])
# In[28]:
print(X.toarray().shape)
# PERFORMING BIGRAMS AND TRIGRAMS
# In[29]:
vectorizer_ngram_range = CountVectorizer(analyzer='word',ngram_range=(1,3),max_features = 100)
bow_matrix_ngram =vectorizer_ngram_range.fit_transform(df)
# In[30]:
print(vectorizer_ngram_range.get_feature_names())
print(bow_matrix_ngram.toarray())
# TF-IDF VECTORIZER
# In[31]:
from sklearn.feature_extraction.text import TfidfVectorizer
vectorizer_n_gram_max_features = TfidfVectorizer(norm="l2",analyzer='word', ngram_range=(1,3), max_features = 500)
tf_idf_matrix_n_gram_max_features =vectorizer_n_gram_max_features.fit_transform(df)
print(vectorizer_n_gram_max_features.get_feature_names())
print(tf_idf_matrix_n_gram_max_features.toarray())
# GENERATING WORD_CLOUD
# In[32]:
# Import packages
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')
from wordcloud import WordCloud, STOPWORDS
# Define a function to plot word cloud
def plot_cloud(wordcloud):
# Set figure size
plt.figure(figsize=(40, 30))
# Display image
plt.imshow(wordcloud)
# No axis details
plt.axis("off");
# In[33]:
# Generate wordcloud
stopwords = STOPWORDS
stopwords.add('will')
wordcloud = WordCloud(width = 3000, height = 2000, background_color='black', max_words=100,colormap='Set2',stopwords=stopwords).generate(text)
# Plot
plot_cloud(wordcloud)
# In[ ]:
|
7e6120ee8b5d7ea063b553d902279bbe6bcaeb19 | lkuehnl1/TextGame | /weapon.py | 1,109 | 3.984375 | 4 | #!/usr/bin/python
# ------------------ Base class Weapon --------------------------------
class Weapon:
def __init__(self, ammo = []):
"""
Baseclass Weapon
Ammo: could have multiple types of ammo for one weapon
"""
self.ammo = ammo
def desc(self):
"""
Description of this specific skill (debugging/logging purposes)
"""
raise NotImplementedError("Subclass must implement abstract method")
def add(self, ammo):
"""
Add weapon ammo
"""
raise NotImplementedError("Subclass must implement abstract method")
def sub(self, ammo):
"""
Subtract ammo
"""
raise NotImplementedError("Subclass must implement abstract method")
def Levels(self):
"""
Access the level of this weapon (?)
"""
raise NotImplementedError("Subclass must implement abstract method")
class Pistol(Weapon):
pass
class Rifle(Weapon):
pass
class Knife(Weapon):
pass
class Grenade(Weapon):
pass
class Laser(Weapon):
pass
|
96041da89b640b176e58ccc37309bd6dad18f76c | mostafa-asg/Algo | /geeksforgeeks/string/reverse-words-in-a-given-string/solution1.py | 348 | 3.59375 | 4 | def main():
test_case = int(input())
for t in range(test_case):
sentence = input().split(".")
for i in range(len(sentence)-1, -1, -1):
print(sentence[i], end="")
if i > 0:
print(".", end="")
else:
print("")
if __name__ == "__main__":
main() |
d30d99322e41d9b590a802d695bfa893dc5cea6d | highlylea/python_skku | /1st/c_to_f.py | 603 | 4.28125 | 4 | """
1차시도_두줄연습
temperature=float(input("This program converts Celsius to Fahrenheit. Celsius:"))
print("It is", temperature*9/5+32, "in fahrenheit.")
2차시도_한줄연습
print('It is {}°F.'.format(float(input('This program converts Celsius to Fahrenheit. Celsius:'))*9/5+32))
#3차시도_함수연습_
def ctof():
c = float(input("섭씨 온도를 입력하세요.:"))
return c*9/5+32
print("화씨", ctof(),"도 입니다.")
"""
#4차시도_함수 더 짧게
def ctof():
return float(input("섭씨 온도를 입력하세요:"))*9/5+32
print(ctof(),"도 입니다.") |
4b633fbac37b0fb7cd71133ea7a8d7cbb53a5abd | NewMountain/algo_practice | /chapter_10/10_2.py | 872 | 4.15625 | 4 | """Chapter 10: Sorting and Searching. Question 10.2"""
# Create a sorting function such that anagrams are next to each other
from collections import Counter
test_data = [
"tar",
"rat",
"redrum",
"study",
"murder",
"elbow",
"below",
"cider",
"dusty",
"cried",
"fizz",
"buzz",
"bar",
"baz",
]
def anagram_hash(word):
"""word hash."""
# Create word histogram
char_histogram = Counter(word)
# Coerce to list of tuples
zip_chars = list(char_histogram.values())
# Turn list into tuple (lists are not hashable in Python)
return tuple(zip_chars)
def sort_angrams(angrams):
"""Sort anagrams."""
# So we need to turn each word into a letter histogram
# Then hash them and sort by the hash
return sorted(angrams, key=lambda x: anagram_hash(x))
print(sort_angrams(test_data))
|
0f6e88bc71adb1d8c0311719a84751ef58fb02ae | phmartinsconsult/curso_python_3_luis_otavio | /Aula_32_Funções.py | 922 | 4.09375 | 4 |
print("FUNÇÃO 1")
print()
def calcula(a, b=10):
if a == 0:
divide = a / b
else:
divide = a / b
print(f'O resultado da sua soma é {divide}')
'''
if divide:
print(divide)
else:
print('Conta invalida')
'''
som = calcula(0)
print('FUNÇÃO 2')
print()
def funcao(var):
return var
var = funcao('Valor que eu quero')
print(var)
def divisao(n1,n2):
if n2 == 0:
return
return n1/n2
divide_1 = divisao(8,2)
if divide_1:
print(divide_1)
else:
print('Conta inválida')
print(type(divide_1))
print('FUNÇÃO 3')
print('#######################################')
print()
def f(var):
print(var)
def dumb():
return f
var = dumb()
print(f'O tipo dessa variável é: {type(var)}.') ## Classe Function
print(f'O id dessas variáveis é: a: {id(var)} e b: {id(f)}')
print('FUNÇÃO 4')
print()
def dumb():
return ("Luis","Otávio")
dum = dumb()
|
1757926fb9064d41f842f4adba60cc8c2b76779a | stonesteel1023/python_study | /test1/coding-ex5(list_compresive).py | 545 | 3.9375 | 4 | # List Comprehension(리스트를 만드는 쉬운 방법들)
# append 시킬 변수 선언 x
# []에 한 줄로 조건절 넣기
numbers = []
# 일반적인 방법
# for n in range(1 ,101) :
# numbers.append(n)
# print(numbers)
# 리스트 컴프리헨션
numbers2 = [x for x in range(1, 101)]
print(numbers2)
# 응용
# 다음 리스트 중에서 '정' 글자를 제외하고 출력하세요.
q3 = ["갑", "을", "병", "정"]
# q3.remove(q3[3])
# for i in q3 :
# print(i, end=' ')
# print()
print([x for x in q3 if x != "정"])
|
ffed35cfab793fc7391da5fef16dfdeb2286d885 | daniel-reich/turbo-robot | /Sdu9JRQtL45qXmJtr_7.py | 1,197 | 4.5 | 4 | """
**Mubashir** is getting old but he wants to celebrate his **20th or 21st
birthday only**. It is possible with some basic maths skills. He just needs to
select the correct number base with your help!
For example, if his current age is 22, that's exactly 20 - in base 11.
Similarly, 65 is exactly 21 - in base 32 and so on.
Create a function that takes his current `age` and returns the given age **20
(or 21) years, with number base** in the format specified in the below
examples.
### Examples
happy_birthday(22) ➞ "Mubashir is just 20, in base 11!"
happy_birthday(65) ➞ "Mubashir is just 21, in base 32!"
happy_birthday(83) ➞ "Mubashir is just 21, in base 41!"
### Notes
Given age will always be greater than 21.
"""
def decimal_to_base(n, base):
res = []
while n > base:
res.append(n % base)
n //= base
res = int(''.join(map(str, reversed(res + [n]))))
return res
def happy_birthday(n):
base = 0
age = 0
for i in range(11, 75):
if decimal_to_base(n, i) == 20:
base = i
age = 20
if decimal_to_base(n, i) == 21:
base = i
age = 21
return "Mubashir is just {}, in base {}!".format(age, base)
|
66222b02ece3c3ae2c8fec27d111e2efae973540 | EltonK888/Multiway-Search-Tree | /Contact.py | 751 | 4.03125 | 4 | class Contact():
''' This class constructs a structure to store people's contact information'''
def __init__(self, phone, name):
'''(Contact, str, str) -> NoneType
constructs a contact by the given phone number
and name.
REQ: phone follows xxx-xxx-xxxx format'''
self._phone = phone
self._name = name
def set_name(self, name):
'''(Contact, str) -> NoneType'''
self._name = name
def set_phone(self, phone):
'''(Contact, str) -> NoneType'''
self._phone = phone
def get_name(self):
'''(Contact) -> str'''
return self._name
def get_phone(self):
'''(Contact) -> str'''
return self._phone
|
fc82fe576e031e6e9f2ceac2661e20d7eebb1c3e | naumovda/python | /daria.py | 490 | 3.734375 | 4 | class base:
def get_name(self):
raise NotImplementedError
def get_cost(self):
raise NotImplementedError
class coffee(base):
def get_name(self):
return 'coffee'
def get_cost(self):
return 10
class tea(base):
def get_name(self):
return 'tea'
def add_milk_cost(obj):
return obj.get_cost() + 1.5
def add_milk_name(obj):
return f"{obj.get_name()}, milk"
m = coffee()
print(add_milk_cost(m))
print(add_milk_name(m))
|
9ee10569a065db6da694aa5c8f01e0fdd2715980 | SaintOops/my_python | /семестр - 2/ДЗ - 2/if_random_game.py | 166 | 3.78125 | 4 | import random
num = int(input('number?'))
x = random.randint(1,4)
if num == x:
print('won')
elif num > x:
print('lower, lose')
else:
print('upper, lose')
|
348fe3eb418e38034b7fb4ae64796945a7135520 | nuggy875/tensorflow-of-all | /39. deep cnn using tf.layer.py | 3,076 | 3.8125 | 4 | # 39. deep cnn using tf.layer
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
# Check out https://www.tensorflow.org/get_started/mnist/beginners for
# more information about the mnist dataset
# hyper parameters
learning_rate = 0.001
training_epoch = 15
batch_size = 100
class Model:
def __init__(self, sess, name):
self.sess = sess
self.name = name
self._build_net()
def _build_net(self):
with tf.variable_scope(self.name):
# dropout (keep_prob) rate 0.7~0.5 on training, but should be 1
# for testing
self.training = tf.placeholder(tf.bool)
# input placeholders
self.X = tf.placeholder(dtype=tf.float32, shape=[None, 784])
X_img = tf.reshape(tensor=self.X, shape=[-1, 28, 28, 1])
self.Y = tf.placeholder(dtype=tf.float32, self=[None, 10])
# layer1
conv1 = tf.layers.conv2d(inputs=X_img, filters=32, kernel_size=[3, 3],
padding="SAME", activation=tf.nn.relu)
# result shape : [28,28,1,32]
# Pooling Layer1
pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2, 2],
padding="SAME", strides=2)
# result shape : [14,14,1,32]
# 결과 layer는 반으로 줄어든다.
dropout1 = tf.layers.dropout(inputs=pool1, rate=0.3, training=self.training)
# conv2
conv2 = tf.layers.conv2d(inputs=dropout1, filters=64, kernel_size=[3, 3],
padding="SAME", activation=tf.nn.relu)
# result shape : [14,14,32,64]
pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2, 2],
padding="SAME", strides=2)
# result shape : [7,7,32,64]
dropout2 = tf.layers.dropout(inputs=pool2, rate=0.3, training=self.training)
# conv3
conv3 = tf.layers.conv2d(inputs=dropout2, filters=128, kernel_size=[3, 3],
padding="SAME", activation=tf.nn.relu)
# result shape : [7,7,64,128]
pool3 = tf.layers.max_pooling2d(inputs=conv3, pool_size=[2, 2],
padding="SAME", strides=2)
dropout3 = tf.layers.dropout(inputs=pool3, rate=0.3, training=self.training)
# dense cost/loss
flat = tf.reshape(dropout3, [-1, 128 * 4 * 4])
dense4 = tf.layers.dense(inputs=flat, units=625, activation=tf.nn.relu)
dropout4 = tf.layers.dropout(inputs=dense4, rate=0.5, training=self.training)
self.logits = tf.layers.dense(inputs=dropout4, units=10)
self.cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=self.logits, labels=self.Y))
self.optimizer = tf.train.AdamOptimizer()
# result shape : [7 ,7 ,64, 128]
|
c58e77d295295c10dd553f42b57b8b4744d635c6 | liamb315/CSE291 | /probset2/run_softmaxregression.py | 1,524 | 3.5625 | 4 | '''Logistic Regression for 0/1 in MNIST dataset'''
import numpy as np
import helper_functions as fn
import math_softmax as ms
from softmaxregression import SklearnSoftmaxRegression
from logisticregression import SklearnLogisticRegression
from sklearn import linear_model
import time
import matplotlib.pyplot as plt
#--------------------#
# Softmax Regression #
#--------------------#
# Load dataset from MNIST
full_trainarray = np.load('data/numpy/trainarray.npy')
full_trainlabel = np.load('data/numpy/trainlabel.npy')
full_testarray = np.load('data/numpy/testarray.npy' )
full_testlabel = np.load('data/numpy/testlabel.npy' )
X_train, Y_train = fn.preprocess_data(full_trainarray, full_trainlabel, False)
X_test, Y_test = fn.preprocess_data(full_testarray, full_testlabel, False)
'''
# 0. Sklearn softmax regression
print 'Softmax regression using sklearn'
t0 = time.time()
softmax = SklearnSoftmaxRegression(tolerance = 0.1)
W = softmax.train(X_train, Y_train)
t1 = time.time()
print ' Training time:', t1-t0
p = softmax.predict(X_test)
t2 = time.time()
print ' Testing time:', t2-t1
fn.print_performance(p, Y_test)
'''
# 0. Softmax regression using stochastic gradient descent
print 'Softmax regression using stochastic gradient descent'
t0 = time.time()
W = np.zeros([X_train.shape[1], 10])
W = ms.stochastic_gradient_descent(X_train, Y_train, W, 10, 256 )
t1 = time.time()
print ' Training time:', t1-t0
p = ms.predict(X_test, W)
t2 = time.time()
print ' Testing time:', t2-t1
fn.print_performance(p, Y_test) |
f606276318a2351fc6e94fa08af7095cc6f451bc | geometryolife/Python_Learning | /PythonCC/Chapter11/e10_test_survey.py | 1,576 | 3.671875 | 4 | import unittest
from e8_survey import AnonymousSurvey
print("----------测试AnonymousSurvey类----------")
# 验证:
# 如果用户面对调查问题时只提供了一个答案,这个答案也能被妥善地存储。
# 使用assertIn()方法核实其确实存储在答案列表中。
class TestAnonymousSurvey(unittest.TestCase):
"""针对AnonymousSurvey类的测试"""
def test_store_single_response(self):
"""测试单个答案会被妥善地存储"""
question = "What language did you first learn to speak?"
# 要测试类的行为,需要创建其实例
my_survey = AnonymousSurvey(question)
my_survey.store_response('English')
self.assertIn('English', my_survey.responses)
def test_store_three_responses(self):
"""测试三个答案会被妥善地存储"""
question = "What language did you first learn to speak?"
my_survey = AnonymousSurvey(question)
responses = ['English', 'Spanish', 'Mandarin']
for response in responses:
my_survey.store_response(response)
for response in responses:
self.assertIn(response, my_survey.responses)
unittest.main()
# ----------测试类----------
# ----------测试AnonymousSurvey类----------
# .
# ----------------------------------------------------------------------
# Ran 1 test in 0.012s
# OK
# ----------测试类----------
# ----------测试AnonymousSurvey类----------
# ..
# ----------------------------------------------------------------------
# Ran 2 tests in 0.000s
# OK
|
8b7d906f6bde17ad7fdfc1e503ab8394732dd0de | sanjkm/Coursera | /Cryptography-I/assignment1/decrypt.py | 4,194 | 4.03125 | 4 | # decrypt.py
# Program will take in encrypted messages as input, from file
# It will decrypt the final message in the input file and output the
# message.
hexVal = 16
# Ascii code values mapping letters to decimal numbers
upperCaseMin, upperCaseMax, lowerCaseMin, lowerCaseMax = 65,90,97,122
# Opens the input file, places the encrypted messages in a list,
# and returns the list
def getEncryptedMsgs (filename):
msgList = []
index = 1
with open(filename, 'r') as f:
for line in f:
if (index % 4) == 3:
msgList.append(line.rstrip('\n'))
if msgList[-1][-1] == ' ':
msgList[-1].rstrip(' ')
index+=1
return msgList
# Takes in two strings of hexadecimal values and outputs their XoR,
# also in the form of hexadecimal string
# First step is to cut the longer string such that each is of the same
# length
def HexStringXor (str1, str2):
strLen = min(len(str1), len(str2))
finalStr1 = str1[:strLen]
finalStr2 = str2[:strLen]
DecimalXoR = [int(x,hexVal)^int(y,hexVal)
for (x,y) in zip(finalStr1, finalStr2)]
return ''.join([hex(val)[2:] for val in DecimalXoR])
# Takes as input a list of indices, and two encrypted strings
# It will return a subset of that list corresponding to indices that
# may correspond to a space character in one of the strings
# This will be known because the XoR of a space character's ascii code
# with any letter's code will flip the case of that letter
def SpaceCharIndexTest (indexList, str1, str2):
# Each ascii code corresponds to two digits of hexadecimal
# So an index value of 'x' will correspond to the xth set of 2 characters
# i.e. character at indices 2*x and 2*x+1
strXor = HexStringXor (str1, str2)
if len(indexList) == 0:
indexList = range(len(strXor)/2)
spaceIndexList = []
for index in indexList:
if (2*index+2) > len(strXor):
break
hexStr = strXor[2*index:2*index+2]
testVal = int (hexStr, hexVal)
if (testVal >= upperCaseMin) and (testVal <= upperCaseMax):
spaceIndexList.append (index)
continue
if (testVal >= lowerCaseMin) and (testVal <= lowerCaseMax):
spaceIndexList.append (index)
if testVal == 0:
spaceIndexList.append(index)
# Assuming that any non-space, non-letter will be followed by space
if index in spaceIndexList:
if (index-1) in spaceIndexList:
spaceIndexList.remove(index-1)
return spaceIndexList
# For inputs, takes the list of indices of known spaces in message N
# Takes the XoR of the inputted encrypted string N and the encrypted
# target string. At indices where message N is known to contain spaces,
# target string will contain the flipped case of the above XoR
def decryptMsg (SpaceIndexList, encrStrN, encrStrTgt, decrMsg):
strXor = HexStringXor (encrStrN, encrStrTgt)
for index in SpaceIndexList:
if index > len(decrMsg):
break
hexStr = strXor[2*index:2*index+2]
testVal = int(hexStr, hexVal)
if testVal == 0:
decrMsg[index] = ' '
elif testVal <= upperCaseMax:
decrMsg[index] = chr(testVal + lowerCaseMin - upperCaseMin)
else:
decrMsg[index] = chr(testVal - (lowerCaseMin - upperCaseMin))
return decrMsg
def main():
filename = 'msgs.txt'
msgList = getEncryptedMsgs (filename)
decrMsg = ['-'] * (len(msgList[-1])/2) # the msg to decrypt
for i in range(len(msgList)):
indexList = []
for j in range(len(msgList)):
if i == j:
continue
indexList = SpaceCharIndexTest (indexList, msgList[i], msgList[j])
if i == 4:
print indexList
if i != len(msgList) - 1:
decrMsg = decryptMsg (indexList, msgList[i], msgList[-1], decrMsg)
else:
for index in indexList:
decrMsg[index] = ' '
print ''.join(decrMsg)
print HexStringXor (msgList[4], msgList[-1])[:16]
main()
|
ba69971f1eb1eb1454233bfbd6b83f03171e5a38 | Jaideep25-tech/AlgoBook | /python/string algorithms/Reversing a string using Recursion.py | 213 | 4.28125 | 4 | String = str(input("Enter a string: "))
def reverse(word):
size = len(word)
if size == 0 :
return
last_char = word[size-1]
print(last_char,end='')
return reverse(word[0:size-1])
reverse(String)
|
b8399941d845ea157a6c19d7a6e2a6bfac2f244a | Chansazm/Project_24_Competitions | /04-Data Structures/index3.py | 437 | 3.859375 | 4 | # Data Structures
# Arrays
arr = [1, 2, 3, 4, 5, 6]
arr.pop()
arr.pop()
print(arr)
arr.append(1)
print(arr)
# Set
s = {1, 2, 3, 4, 5, 2}
print(s)
s.remove(5)
print(s)
s.add(6)
print(s)
print(len(s))
# Map or Object
dictionary = {1: 2, 2: 3}
print(dictionary)
print(dictionary.keys())
print(dictionary.values())
print(dictionary.items())
for i,j in dictionary.items():
print(i,j)
print(2 in dictionary)
print(3 in dictionary)
|
20aab5ed03358ecb3a260510c31a6689bbe83e26 | dev9033/head-first-python- | /function.py | 310 | 4.34375 | 4 | # function in python
def search_for_vowels():
"""Display any vowels found in an asked-for word""" # doc string
vowels = set('aeiou')
word = input('give a word to check search for vowel')
found = vowels.intersection(set(word))
for vowel in found:
print(vowel)
search_for_vowels()
|
16133fb2391e55e8ba39eef4d70b665f035dd27a | dlimeb/kids-projects | /cool.py | 695 | 4 | 4 | import random
import re
# ask for an acronym
acronym = ""
while not acronym:
acronym = raw_input("Type in an acronym to use: ")
letters = list(acronym.lower())
# put the dictionary into a list
dict_file = open("/usr/share/dict/words", "r")
dictionary = []
for line in dict_file:
dictionary.append(line.rstrip("\n"))
insult = []
# for each letter, find all the dictionary words that start with that letter, and pick one at random
for l in letters:
choices = []
for word in dictionary:
if re.match("^%s" % l, word):
choices.append(word)
word = random.choice(choices)
insult.append(word)
print "Oh yeah? Well you are a " + " ".join(insult) + "!"
|
e8bcbd59bd3bf40d35aea409adc3f30810c1b894 | AaronDweck/all-Python-folders | /tests.py | 208 | 3.96875 | 4 | print ("welcome to my chat box")
live = input("where do live? ")
if live == "london":
truth = input("are you sure? ")
elif truth == "yes":
print("ok but i dont baliev you")
elif truth == "no":
|
8405d744c15f2cb722ed8e520844eaa065192eec | samuel-c/SlackBot-2020 | /venv/Lib/site-packages/pyowm/weatherapi25/location.py | 6,519 | 3.6875 | 4 | """
Module containing location-related classes and data structures.
"""
import json
import xml.etree.ElementTree as ET
from pyowm.weatherapi25.xsd.xmlnsconfig import (
LOCATION_XMLNS_URL, LOCATION_XMLNS_PREFIX)
from pyowm.utils import xmlutils, geo
class Location(object):
"""
A class representing a location in the world. A location is defined through
a toponym, a couple of geographic coordinates such as longitude and
latitude and a numeric identifier assigned by the OWM Weather API that uniquely
spots the location in the world. Optionally, the country specification may
be provided.
Further reference about OWM city IDs can be found at:
http://bugs.openweathermap.org/projects/api/wiki/Api_2_5_weather#3-By-city-ID
:param name: the location's toponym
:type name: Unicode
:param lon: the location's longitude, must be between -180.0 and 180.0
:type lon: int/float
:param lat: the location's latitude, must be between -90.0 and 90.0
:type lat: int/float
:param ID: the location's OWM city ID
:type ID: int
:param country: the location's country (``None`` by default)
:type country: Unicode
:returns: a *Location* instance
:raises: *ValueError* if lon or lat values are provided out of bounds
"""
def __init__(self, name, lon, lat, ID, country=None):
self._name = name
if lon is None or lat is None:
raise ValueError("Either 'lon' or 'lat' must be specified")
geo.assert_is_lon(lon)
geo.assert_is_lat(lat)
self._lon = float(lon)
self._lat = float(lat)
self._ID = ID
self._country = country
def get_name(self):
"""
Returns the toponym of the location
:returns: the Unicode toponym
"""
return self._name
def get_lon(self):
"""
Returns the longitude of the location
:returns: the float longitude
"""
return self._lon
def get_lat(self):
"""
Returns the latitude of the location
:returns: the float latitude
"""
return self._lat
def get_ID(self):
"""
Returns the OWM city ID of the location
:returns: the int OWM city ID
"""
return self._ID
def get_country(self):
"""
Returns the country of the location
:returns: the Unicode country
"""
return self._country
def to_geopoint(self):
"""
Returns the geoJSON compliant representation of this location
:returns: a ``pyowm.utils.geo.Point`` instance
"""
if self._lon is None or self._lat is None:
return None
return geo.Point(self._lon, self._lat)
def to_JSON(self):
"""Dumps object fields into a JSON formatted string
:returns: the JSON string
"""
return json.dumps({'name': self._name,
'coordinates': {'lon': self._lon,
'lat': self._lat
},
'ID': self._ID,
'country': self._country})
def to_XML(self, xml_declaration=True, xmlns=True):
"""
Dumps object fields to an XML-formatted string. The 'xml_declaration'
switch enables printing of a leading standard XML line containing XML
version and encoding. The 'xmlns' switch enables printing of qualified
XMLNS prefixes.
:param XML_declaration: if ``True`` (default) prints a leading XML
declaration line
:type XML_declaration: bool
:param xmlns: if ``True`` (default) prints full XMLNS prefixes
:type xmlns: bool
:returns: an XML-formatted string
"""
root_node = self._to_DOM()
if xmlns:
xmlutils.annotate_with_XMLNS(root_node,
LOCATION_XMLNS_PREFIX,
LOCATION_XMLNS_URL)
return xmlutils.DOM_node_to_XML(root_node, xml_declaration)
def _to_DOM(self):
"""
Dumps object data to a fully traversable DOM representation of the
object.
:returns: a ``xml.etree.Element`` object
"""
root_node = ET.Element("location")
name_node = ET.SubElement(root_node, "name")
name_node.text = self._name
coords_node = ET.SubElement(root_node, "coordinates")
lon_node = ET.SubElement(coords_node, "lon")
lon_node.text = str(self._lon)
lat_node = ET.SubElement(coords_node, "lat")
lat_node.text = str(self._lat)
id_node = ET.SubElement(root_node, "ID")
id_node.text = str(self._ID)
country_node = ET.SubElement(root_node, "country")
country_node.text = self._country
return root_node
def __repr__(self):
return "<%s.%s - id=%s, name=%s, lon=%s, lat=%s>" % (__name__, \
self.__class__.__name__, self._ID, self._name, str(self._lon), \
str(self._lat))
def location_from_dictionary(d):
"""
Builds a *Location* object out of a data dictionary. Only certain
properties of the dictionary are used: if these properties are not
found or cannot be read, an error is issued.
:param d: a data dictionary
:type d: dict
:returns: a *Location* instance
:raises: *KeyError* if it is impossible to find or read the data
needed to build the instance
"""
country = None
if 'sys' in d and 'country' in d['sys']:
country = d['sys']['country']
if 'city' in d:
data = d['city']
else:
data = d
if 'name' in data:
name = data['name']
else:
name = None
if 'id' in data:
ID = int(data['id'])
else:
ID = None
if 'coord' in data:
lon = data['coord'].get('lon', 0.0)
lat = data['coord'].get('lat', 0.0)
elif 'coord' in data['station']:
if 'lon' in data['station']['coord']:
lon = data['station']['coord'].get('lon', 0.0)
elif 'lng' in data['station']['coord']:
lon = data['station']['coord'].get('lng', 0.0)
else:
lon = 0.0
lat = data['station']['coord'].get('lat', 0.0)
else:
raise KeyError("Impossible to read geographical coordinates from JSON")
if 'country' in data:
country = data['country']
return Location(name, lon, lat, ID, country)
|
c648b8fcd831129b3d1e50f43f23d4fb2a7f0709 | AmitBaroi/Data-Visualization-Lessons | /DataCamp/4_Customization.py | 455 | 3.6875 | 4 | import matplotlib.pyplot as plt
year = [1950, 1951, 1952, 2100]
pop = [2.538, 2.57, 2.62, 10.85]
# Adding new data:
year = [1800, 1850, 1900] + year
pop = [1.0, 1.262, 1.650] + pop
plt.plot(year, pop)
plt.xlabel("Year")
plt.ylabel("Population")
plt.title("World Population Projections")
# Y ticks the numbers shown on the y axis
plt.yticks([0, 2, 4, 6, 8, 10],
["0", "2B", "4B", "6B", "8B", "10B"]) # Labels for the y ticks
plt.show()
|
78983dc4a61d0043d9dfbc188c45d586cebd4704 | DanielOjo/Functions | /Classroom starters/Starter-Functions Task 4.py | 272 | 4.0625 | 4 | #Daniel Ogunlana (40730)
#17-11-2014
#Starter-Functions Task 4
pay_rate = int(input("Please enter your pay rate: "))
hours_worked = int(input("Please enter the amount of hours that you work for in a week: "))
calculated_pay = pay_rate*hours_worked
print(calculated_pay)
|
8bdf3df61118205a8d808acfeeda94a31455e558 | tschart/python | /daily-programmer/revised-julian-calendar/src.py | 523 | 3.625 | 4 | #brute force emthod of calculating # of leap years
def divis_by_4(year):
return year % 4 == 0
def divis_by_100(year):
return year % 100 == 0
def remain_by_900(year):
return year % 900 == 200 or year % 900 == 600
def is_leap_year(year):
return (divis_by_4(year)) and not ((divis_by_100(year)) and (not remain_by_900(year)))
def leaps(start, end):
i = 0
while start < end:
if is_leap_year(start):
i += 1
start += 1
return(i)
print(leaps(123456, 7891011))
|
078405e18a59232315323308de1e67030ea029c0 | Vinamra2009/Algorithms | /Language/Python/calendar.py | 148 | 3.90625 | 4 | #Program for printing calander
import calendar
yy=int(input("enter the year"))
mm=int(input("enter the month"))
print(calendar.month(yy,mm))
|
55a9ba26f2d57089b871f47d207a9112498f25ef | novas-meng/EmtionClassify | /item_emotion.py | 540 | 3.75 | 4 |
def readWords():
f=open('train.csv',encoding='utf-8')
item_emotion_map={}
for line in f:
array=line.strip().split(',')
if len(array) == 3:
#print(len(array))
#print(line)
text=array[1]
label=array[2]
for item in text.split(' '):
if item not in item_emotion_map:
h={}
h[label]=1
item_emotion_map[item]=h
else:
h=item_emotion_map[item]
if label in h:
h[label]=h[label]+1
else:
h[label]=1
return item_emotion_map
if __name__=='__main__':
h=readWords()
print(len(h))
|
50351ebcc69b8ef94015008dac686bbb52f949bf | pythonbyte/Interview-solved | /Important/given_string.py | 492 | 3.875 | 4 | # Given a string find out whether there are the same number of letters inside of it.
def balanced(string):
dict_word = {}
for i in string:
if i in dict_word:
dict_word[i] += 1
else:
dict_word[i] = 1
len_dict = len(dict_word.values())
sum_dict = sum(dict_word.values())
values = list(dict_word.values())
for v in values:
if values[0] == v:
continue
else:
return False
return True
|
a16f6d80017b3a83eb9ad22cfd7c2eeaaac1dcbf | vishalnirmal/Data-Structures-and-Algorithms | /Data Structures/Doubly Linked List/DoublyLinkedList.py | 5,919 | 3.78125 | 4 | ##############################################
# Doubly Linked List #
# by Vishal Nirmal #
# #
# A Doubly Linked List ADT implementation. #
##############################################
class DLL:
class DLLNode:
def __init__(self, data=None):
self.data = data
self.next = None
self.prev = None
def __init__(self):
self.start = None
def traverseList(self):
if self.start == None:
print('The list is empty.')
return
else:
current = self.start
while current.next:
print(current.data, '<->', end=' ')
current = current.next
print(current.data)
def insertAtBeginning(self, data):
nnode = DLL.DLLNode(data)
if self.start == None:
self.start = nnode
else:
nnode.next = self.start
self.start.prev = nnode
self.start = nnode
def insertAtEnd(self, data):
nnode = DLL.DLLNode(data)
if self.start == None:
self.start = nnode
else:
current = self.start
while current.next:
current = current.next
current.next = nnode
nnode.prev = current
def insert(self, data, pos):
k=1
nnode = DLL.DLLNode(data)
if self.start == None and pos != 1:
print('Invalid position.')
return
if pos == 1:
if self.start == None:
self.start = nnode
else:
self.start.prev = nnode
nnode.next = self.start
self.start = nnode
return
p = self.start
while p and k < pos:
q = p
p = p.next
k+=1
if k!=pos:
print('Invalid position.')
return
nnode.prev = q
q.next = nnode
nnode.next = p
if p:
p.prev = nnode
def deleteAtBeginning(self):
if self.start == None:
print('The list is empty.')
return
else:
data = self.start.data
self.start = self.start.next
self.start.prev = None
return data
def deleteAtEnd(self):
if self.start == None:
print('The list is empty.')
return
else:
current = self.start
temp = None
while current.next:
temp = current
current = current.next
if temp:
temp.next = None
else:
self.start = None
def delete(self, pos):
if self.start == None:
print('The list is empty.')
return
if pos == 1:
self.start = self.start.next
return
current = self.start
temp = None
k=1
while current and k<pos:
temp = current
current = current.next
k+=1
if current == None:
print('Invalid position.')
return
if current.next:
current.next.prev = temp
temp.next = current.next
def get(self, pos):
if self.start == None:
print('The list is empty.')
return
current = self.start
k = 1
while current and k < pos:
current = current.next
k+=1
if current == None:
print('Invalid position.')
return
return current.data
def search(self, data):
if self.start == None:
print('The list is empty.')
return
current = self.start
k=1
while current and current.data != data:
current = current.next
k+=1
if current:
return k
print('{} not present in the list.'.format(data))
def addNodes(self, arr):
nnode = DLL.DLLNode(arr[0])
n1 = nnode
for i in arr[1:]:
node = DLL.DLLNode(i)
n1.next = node
node.prev = n1
n1 = node
if self.start != None:
print('Appending the data at the end of the list.')
current = self.start
while current.next:
current = current.next
current.next = nnode
nnode.prev = current
else:
self.start = nnode
def count(self):
current = self.start
c=0
while current:
current = current.next
c+=1
return c
def reverseList(self):
current = self.start
while current.next:
temp = current.next
current.next = current.prev
current.prev = temp
current = temp
temp = current.next
current.next = current.prev
current.prev = temp
self.start = current
# >>> l1 = DLL()
# >>> l1.insertAtBeginning(34)
# >>> l1.traverseList()
# 34
# >>> l1.insertAtEnd(12)
# >>> l1.traverseList()
# 34 <-> 12
# >>> l1.insert(8, 2)
# >>> l1.traverseList()
# 34 <-> 8 <-> 12
# >>> l1.addNodes([1, 4, 2, 7, 3])
# Appending the data at the end of the list.
# >>> l1.traverseList()
# 34 <-> 8 <-> 12 <-> 1 <-> 4 <-> 2 <-> 7 <-> 3
# >>> l1.deleteAtBeginning()
# 34
# >>> l1.traverseList()
# 8 <-> 12 <-> 1 <-> 4 <-> 2 <-> 7 <-> 3
# >>> l1.deleteAtEnd()
# >>> l1.traverseList()
# 8 <-> 12 <-> 1 <-> 4 <-> 2 <-> 7
# >>> l1.delete(3)
# >>> l1.traverseList()
# 8 <-> 12 <-> 4 <-> 2 <-> 7
# >>> l1.count()
# 5
# >>> l1.get(3)
# 4
# >>> l1.search(2)
# 4 |
407214dc1cf7fc4b2efa7281ee0506478de3bd0f | thirihsumyataung/Python_Tutorials | /formatted_string.py | 307 | 4.03125 | 4 | first = 'John'
last = 'Smith'
message = first + ' [' + last + ']' + ' is a coder. '
print(message)
#Formatted String
#Note : To define formatted string, prefix your string with an F
#and then use curly braces to dynamically insert values into your strings.
msg = f'{first} [{last}] is a coder.'
print(msg)
|
38911cb4f112fbf147a4188bb86fecda4ebcf422 | mavenickk/ML-project-snippets | /train_test.py | 739 | 3.5625 | 4 | import pandas as pd
from sklearn.model_selection import train_test_split
# Read the data
X_full = pd.read_csv('../input/train.csv', index_col='Id')
X_test_full = pd.read_csv('../input/test.csv', index_col='Id')
# Remove rows with missing target, separate target from predictors
X_full.dropna(axis=0, subset=['SalePrice'], inplace=True)
y = X_full.SalePrice
X_full.drop(['SalePrice'], axis=1, inplace=True)
# To keep things simple, we'll use only numerical predictors
X = X_full.select_dtypes(exclude=['object'])
X_test = X_test_full.select_dtypes(exclude=['object'])
# Break off validation set from training data
X_train, X_valid, y_train, y_valid = train_test_split(X, y, train_size=0.8, test_size=0.2,random_state=0) |
bccd404d9b75353dfc98b0d22624756183aa902f | DanLesman/euler | /p12.py | 335 | 3.65625 | 4 | def num_divisors(n):
i = 1
divisors_count = 0
while i * i <= n:
if n % i == 0:
if i == n/i:
divisors_count += 1
else:
divisors_count += 2
i += 1
return divisors_count
def first_with_n_divisors(n):
i = 0
num = 0
while num_divisors(num) < 500:
num += i
i += 1
return num
print(first_with_n_divisors(500))
|
249e23c333a2b98c6dc142c1ffea3619e0bd2296 | scan3ls/Markdown2HTML | /parser.py | 4,895 | 3.8125 | 4 | """
Parses Markdown text and returns html elements
"""
def get_tags(tag):
"""
"""
open_tag = "<{}>".format(tag)
close_tag = "</{}>".format(tag)
return open_tag, close_tag
def headings(line=""):
"""
headings - generate html headings from md headings
Arguments
text: markdown text to parse
"""
import re
if line == "":
return None
line.lstrip(' ')
h_tags = {
0: None,
1: "h1", 2: "h2", 3: "h3",
4: "h4", 5: "h5", 6: "h6"
}
result = re.match(r"(^#+) (.+$)", line)
if result is None:
return None
groups = result.groups()
h_level = len(groups[0])
text = groups[1]
open_tag, close_tag = get_tags(h_tags[h_level])
html = "{}{}{}".format(
open_tag, text, close_tag
)
return(html)
def ulist(lines):
"""
"""
import re
list_content = []
for line in lines:
line.lstrip()
result = re.match(r"(^- )(.*)", line)
if result is not None:
item = result.groups()[1]
list_content.append(item)
else:
list_content.append(None)
for index, item in enumerate(list_content):
if list_content[index] is not None:
list_content[index] = "\t<li>{}</li>".format(item)
else:
list_content[index] = lines[index]
index = [idx for idx, s in enumerate(list_content) if '<li>' in s][0]
list_content.insert(index, "<ul>")
list_content.append("</ul>")
html = list_content
return html
def olist(lines):
"""
"""
import re
list_content = []
for line in lines:
line.lstrip()
result = re.match(r"(^\* )(.*)", line)
if result is not None:
item = result.groups()[1]
list_content.append(item)
else:
list_content.append(None)
for index, item in enumerate(list_content):
if list_content[index] is not None:
list_content[index] = "\t<li>{}</li>".format(item)
else:
list_content[index] = lines[index]
index = [idx for idx, s in enumerate(list_content) if '<li>' in s][0]
list_content.insert(index, "<ol>")
list_content.append("</ol>")
html = list_content
return html
def parse(text=""):
"""
parse - main parse function
Arguments:
text: markdown text to parse
"""
import re
html_text = ""
lines = text.split('\n')
sections = []
html_list = []
while len(lines) != 0:
end = lines.index('')
sections.append(lines[0:end])
del lines[:end + 1]
for section in sections:
# Change Heading
for index, line in enumerate(section):
html = headings(line)
if html is not None:
section[index] = html
# Change unordered lists
is_ulist = False
for line in section:
line.lstrip()
pattern = r'(^\- )(.*)'
result = re.search(pattern, line)
if result is not None:
is_ulist = True
break
if is_ulist:
html = ulist(section)
section = html
# Change ordered lists
is_olist = False
for line in section:
line.lstrip()
pattern = r'(^\* )(.*)'
result = re.search(pattern, line)
if result is not None:
is_olist = True
break
if is_olist:
html = olist(section)
section = html
# Find normal text and add <br/>
for index, line in enumerate(section):
line.lstrip()
if line[0] not in ['<', '\t']:
html = '<p>\n\t{}\n</p>'.format(line)
section[index] = html
for index, line in enumerate(section):
try:
next_line = section[index + 1]
except IndexError:
continue
next_tag = next_line[1]
cur_tag = line[-2]
if next_tag == cur_tag:
section[index] = line[:-5]
section[index + 1] = section[index + 1][4:]
section.insert(index + 1, "\t\t<br />")
# bold and emphasis normal text
for index, line in enumerate(section):
match = re.search(r'\*\*.+\*\*', line)
if match is not None:
result = re.sub(r'(\*\*)(.+)(\*\*)', r'<b>\2</b>', line)
section[index] = result
for index, line in enumerate(section):
match = re.search('__.+__', line)
if match is not None:
result = re.sub(r'(__)(.+)(__)', r'<em>\2</em>', line)
section[index] = result
continue
html_list.append(section)
return html_list
|
6335e19f65f28cc813a368afdd96444c755fb3c1 | sandeepmanocha/myCheckIO | /roman_numerals.py | 2,422 | 3.6875 | 4 | def checkio(data):
roman = {1: 'I', 5: 'V', 10: 'X', 50: 'L', 100: 'C', 500: 'D', 1000: 'M', 0: ''}
converted = ''
remainder = 1
div = 1000
remainder = data % (div)
num = data - data % div
# print(data, num, remainder)
while remainder == data:
div = int(div / 10)
remainder = data % (div)
num = data - data % div
# print(data, num, remainder)
"""
if remainder == data:
#print('100s')
num = data - data % 100
remainder = data%100
if remainder == data:
#print('10s')
num = data - data % 10
remainder = data%10
if remainder == data:
# print('10s')
num = data
remainder = data % 10
"""
if remainder > 0 and remainder != data:
# print('Calling with ', remainder)
converted = checkio(remainder)
if num > 0 and num <= 9:
if num == 9:
converted = roman[1] + roman[10] + converted
elif num == 4:
converted = roman[1] + roman[5] + converted
else:
five = num - num % 5
ones = num - five
converted = roman[five] + roman[1] * ones + converted
elif num > 9 and num <= 99:
if num == 90:
converted = roman[10] + roman[100] + converted
elif num == 40:
converted = roman[10] + roman[50] + converted
else:
fiftys = num - num % 50
tens = int((num - fiftys) / 10)
converted = roman[fiftys] + roman[10] * tens + converted
elif num > 99 and num <= 999:
if num == 900:
converted = roman[100] + roman[1000] + converted
elif num == 400:
converted = roman[100] + roman[500] + converted
else:
five_hunds = num - num % 500
hunds = int((num - five_hunds) / 100)
converted = roman[five_hunds] + roman[100] * hunds + converted
elif num > 999:
count_of_thousnds = int((num) / 1000)
converted = roman[1000] * count_of_thousnds + converted
# print(str(data),converted)
# replace this for solution
return converted
print(checkio(3889)) # == 'MMMDCCCLXXXVIII', '3888'
print(checkio(3999)) # == 'MMMDCCCLXXXVIII', '3888'
print(checkio(1)) # == 'I', '1'
print("Output:", checkio(44)) # == 'MMMDCCCLXXXVIII', '3888'
print("Output:", checkio(4)) # == 'MMMDCCCLXXXVIII', '3888'
|
0c0d63552f75a42c0638e423a1e0f7511c686bef | ShubhangiDabral13/Text-Summarization-Through-NLP | /Extractive Text Summerization/src/split_text_to_sentences.py | 492 | 4.03125 | 4 |
#we will split the text into different sentence and then append it to the list.
def split_text(text):
"""
param text: it is the plain text
return a list which consist of sentence present in text.
"""
from nltk.tokenize import sent_tokenize
sentences = []
for s in text:
sentences.append(sent_tokenize(s))
# flatten list
sentences = [y for x in sentences for y in x]
# return the sentences after beind sentence tokenized
return sentences
|
b2f6bfbd7fe78b75c5684a0b00bf8ab27b8b6954 | arunkumaraqm/Mullers-Method | /MullersMethod.py | 5,696 | 3.5625 | 4 | """
Implementation of Muller's method
Approximates one of the roots for an equation of the form f(x) = 0
This implementation supports complex functions and complex guesses.
Contributors:
Archana (ENG18CS0044)
Arun (ENG18CS0047)
"""
from cmath import * # It provides access to mathematical functions for complex numbers like sinh() nad abs().
from itertools import count as counting_forever # This module provides access to iterators like count().
# Defining constraints
TOLERATED_PERCENTAGE_ERROR = 10 ** (-3) # accepted percentage error upto 0.001
MAX_ITERATIONS = 100
DEBUG = False
def find_next_guess(func, x0, x1, x2):
try: # The try block lets you test a block of code for errors.
# calculating the function values at x0, x1 and x2
e = func(x0)
f = func(x1)
g = func(x2)
except: #The except block lets you handle the error.
raise ValueError("The function does not meet input criteria.")
# This could be because the entered function does not conform to Python syntax.
# or because the function is not analytic at a point x.
try:
h0 = x1 - x0
h1 = x2 - x1
delta0 = (f - e) / h0
delta1 = (g - f) / h1
a = (delta1 - delta0) / (h1 + h0)
b = (a * h1) + delta1
c = g
d = sqrt((b * b) - (4 * a * c)) # discriminant
# The denominator should have a large magnitude so that x3 is closer to x2.
if abs(b - d) > abs(b + d):
x3 = x2 - ((2 * c) / (b - d))
else:
x3 = x2 - ((2 * c) / (b + d))
except ZeroDivisionError as err:
"""
During testing, we discovered that if the root of the function is 0,
x2 eventually reaches the value 0, then g = f(x2) = 0.
This ends up making h1 + h0 = 0 or b - d = 0 or b + d = 0 depending on the other values.
So, we require this except block.
"""
if isclose(func(0), 0): # Checking if 0 is a root.
x3 = 0
else:
# As per our calculations, control will never reach this block.
raise ZeroDivisionError(str(err) + "; we haven't thought this through.")
finally: # The finally block will be executed regardless if the try block raises an error or not.
return x3
def read_inputs(disable_prompts = False):
prompt = "Enter the function: " if not disable_prompts else ""
expr = input(prompt) # should not end with ' = 0' obviously.
# Converting the input string to a Python expression
expr = expr.replace("^", "**") # ** is used for pow in Python
func = lambda x: eval(expr) # Assuming "x" is the independent var
# Caution: Python uses j for sqrt(-1)
#TODO Support for natural mathematic notation
#TODO Input validation
# A nested function because we're calling it multiple times within read_inputs
def read_guess(guess_no):
# Reads one of the x values from the user
prompt = f"Initial guess {guess_no}: " if not disable_prompts else ""
x = input(prompt)
"""
The complex() function returns a complex number when real and imaginary parts are provided,
or it converts a string to a complex number; we're doing the latter here.
"""
x = complex(x)
return x
x0, x1, x2 = read_guess(0), read_guess(1), read_guess(2) # copying the return values to x0, x1, x2
"""
The isclose function checks whether two values are close or not.
It is a bad practice to compare floats for equality due to implicit roundoffs.
The real and imaginary parts are floats.
"""
if isclose(x0, x1) or isclose(x1, x2) or isclose(x2, x0):
raise ValueError("At least two of the three guesses are the same.")
return func, x0, x1, x2
def main():
func, x0, x1, x2 = read_inputs(disable_prompts = DEBUG)
for iteration_cnt in counting_forever(1): # counting_forever starts counting from 1
x3 = find_next_guess(func, x0, x1, x2)
# is all is required? Plus TODO ZeroDivisionError for x3
"""
isclose will compare the absolute values of the two complex numbers.
rel_tol is the relative tolerance. It is the maximum allowed difference between value x2 and x3.
In this case rel_tol = 0.001. This handles the work of calculating the relative percentage error.
abs_tol is the minimum absolute tolerance. rel_tol doesn't work satisfactorily if one of x2 or x3 is 0.
In this case abs_tol = 0.001
If x2 is almost equal to x3, no more iterations are required; x3 is the root.
Otherwise if the no. of iterations have exceeded the earlier specified maximum,
the loop must be halted.
"""
if isclose(x2, x3, rel_tol = TOLERATED_PERCENTAGE_ERROR, abs_tol = TOLERATED_PERCENTAGE_ERROR)\
or iteration_cnt >= MAX_ITERATIONS:
print(f"One of the roots is: {x3 : .4f}") # Setting precision
print(f"No. of iterations = {iteration_cnt}")
print(f"Verification: f({x3}) = {func(x3)}")
# The latter number might get printed in scientific notation because it is so small.
# Remember to look at the exponent following the number.
break
else:
x0, x1, x2 = x1, x2, x3 # Including the newly found x3 as a guess.
# This makes our module importable from another program while still being able to be run on its own.
if __name__ == "__main__": main()
|
35c7c5abc2a95ba5bea9a6e27357a15ecb8ac1bb | Abhijnan-Bajpai/Budget-Estimation | /data.py | 968 | 3.53125 | 4 | import pandas as pd
import random as ran
def generate_expense(year, lst):
if year >= 2001:
generate_expense(year - 1, lst)
base_num = ran.randint(10000,15000)
lst.append(base_num * (year % 2000))
return lst
else:
return
n = int(input("Data from 2001 upto which year: "))
Jan = generate_expense(n, [])
Feb = generate_expense(n, [])
Mar = generate_expense(n, [])
Apr = generate_expense(n, [])
May = generate_expense(n, [])
Jun = generate_expense(n, [])
Jul = generate_expense(n, [])
Aug = generate_expense(n, [])
Sep = generate_expense(n, [])
Oct = generate_expense(n, [])
Nov = generate_expense(n, [])
Dec = generate_expense(n, [])
csv_dict = {
"Year": [i for i in range(2001,n+1)], "Jan": Jan, "Feb": Feb, "Mar": Mar, "Apr": Apr, "May": May, "Jun": Jun, "Jul": Jul, "Aug": Aug,
"Sep": Sep, "Oct": Oct, "Nov": Nov, "Dec": Dec}
dfObj = pd.DataFrame(csv_dict)
print(dfObj)
|
330f115c43701357390d13f6d305efc662b1c4d7 | BobXGY/PythonStudy | /oj_py/CCF_CSP/201803-1.py | 504 | 3.640625 | 4 | if __name__ == '__main__':
game = str(input())
op_list = game.split(" ")
combo = False
base_score = 1
total_score = 0
for op in op_list[:-1:]:
if op == "0":
break
if op == "1":
combo = False
base_score = 1
elif op == "2":
combo = True
if base_score == 1:
base_score += 1
else:
base_score += 2
total_score += base_score
print(total_score)
|
6c7a058ff997b3211c80b69eb923c1bfb0acdb37 | m7jay/Algorithms-in-Python | /Linear&BinarySearch.py | 1,544 | 3.921875 | 4 | #impletation of linear search alogrithm
#only for illustration as sequence types like List, Tuple, Range
# all implements the __contains__() and
# allows to search simply by using 'in' operator
from enum import IntEnum
from typing import List, Tuple
Nucleotide: IntEnum = IntEnum ('Nucleotide', ('A', 'C', 'G', 'T')) #IntEnum gives us the comparsion operators
#codons are defined as triplets of nucleotides
Codon = Tuple[Nucleotide, Nucleotide, Nucleotide]
#genes are list of codons
Genes = List[Codon]
gene_str: str = "ACGTGGCTCTCTAACGTACGTACGTACGGGGTTTATATATACCCTAGGACTCCCTTTGTC"
def string_to_gene(s:str)->Genes:
genes: Genes = []
for i in range(0, len(s), 3):
if (i + 2) > len(s):
return genes
codon: Codon = (Nucleotide[s[i]], Nucleotide[s[i + 1]], Nucleotide[s[i + 2]])
genes.append(codon)
return genes
def linear_search(g:Genes, c:Codon)->bool:
for codon in g:
if codon == c:
return True
return False
def binary_search(g:Genes, key:Codon)->bool:
low = 0
high = len(g) - 1
while low <= high:
mid = (low + high) // 2
if g[mid] < key:
low = mid + 1
elif g[mid] > key:
high = mid - 1
else :
return True
return False
if __name__ == "__main__":
gene:Genes = string_to_gene(gene_str)
gtc:Codon = (Nucleotide.G, Nucleotide.T, Nucleotide.C)
print(linear_search(gene, gtc))
sorted_genes = sorted(gene)
print(binary_search(sorted_genes, gtc))
print()
|
193f4107eb47964999002a7a29a29b711d7598a3 | orenzaj/Python-Basics | /doubler.py | 207 | 3.828125 | 4 | # This class will double whatever it's given as parameter.
class Double(int):
def __new__(*args, **kwargs):
self = int.__new__(*args, **kwargs)
return self * 2
print(Double(3))
|
bd09a87523a8d91924bc82313cf6f54264cadbd0 | Chi-you/python_pratice | /staticmethod.py | 1,230 | 4.46875 | 4 | # static
# when a variable is delared as static which means it has already been writen into the memory when class initialize
# when to use static:
# 1. we hope that some members is independent of instance
# 2. because of using only one part of memory, so no matter how much instances there are, the space of the static member would not increase
# example:
class Shiba:
def __init__(self, height, weight):
self.height = height
self.weight = weight
@staticmethod # we use decorator '@staticmethod' to declare the method is static
def pee(length): # parameter has no 'self' and 'cls' so it cannot access the static member
print("pee" + "." * length)
Shiba.pee(3) # static method not only can be called by instance but also class
Shiba.pee(20)
black_shiba = Shiba(90, 40)
black_shiba.pee(10)
class Sh:
pee_length = 10
def __init__(self, height, weight):
self.height = height
self.weight = weight
@staticmethod
def pee():
print("pee" + "." * pee_length) # parameter has no 'self' and 'cls' so it cannot access the static member (pee_length)
Sh.pee()
Sh.pee()
black = Sh(90, 40)
black.pee()
# Error > NameError: name 'pee_length' is not defined
|
d8f849d1480f8aa65dde9df4d0b7437be9f889e2 | Yvette995/twitter_hot_topic_Clustering | /web.py | 2,749 | 3.5 | 4 | import streamlit as st
from function import *
st.sidebar.header('Twitter Hot Finder')
option = st.sidebar.selectbox('Choose',('input data','process data', 'show analyse'),index = 0)
uploaded_file = st.file_uploader('Please upload twitter data(.csv):')
if uploaded_file is not None:
filepath = 'data.csv'
eps_var = 0.6
min_samples_var = 10
@st.cache(allow_output_mutation=True)
def main():
df_non_outliers,rank_num,data_pca_tsne,label = process(filepath,eps_var,min_samples_var)
return df_non_outliers,rank_num,data_pca_tsne,label
df_non_outliers,rank_num,data_pca_tsne,label = main()
if option == 'input data':
st.write("Successfully Upload!")
st.write(pd.read_csv(filepath,index_col=0)[:5000])
if option == 'process data':
st.write('The text has been transformed into vectors,and after the clustering process,twitter is divided into different categories')
st.text('rank: The more popular the topic, the higher the ranking')
st.write(df_non_outliers[['text','label','rank','pca_tsne']])
st.write('The vectors of each hot topic are visualized as shown in the figure (different colors represent different categories)')
fig = plt.figure()
x = [i[0] for i in data_pca_tsne]
y = [i[1] for i in data_pca_tsne]
plt.scatter(x, y, c=label)
plt.title('Hot Topic Vector')
st.write(fig)
if option == 'show analyse':
st.write("Total",rank_num,"hot topics")
rank_num = get_num_of_value_no_repeat(df_non_outliers['rank'])
value = [df_non_outliers[df_non_outliers['rank'] == i].shape[0] for i in range(1, rank_num + 1)]
yticks = [str(get_most_common_words(df_non_outliers[df_non_outliers['rank'] == i]['content_cut'],
top_n=5)) + str(i) for i in range(1, rank_num + 1)]
fig = plt.figure(figsize=(13, 6), dpi=100)
plt.subplot(122)
ax = plt.gca()
ax.spines['left'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.invert_yaxis()
plt.barh(range(1, rank_num + 1), value, align='center', linewidth=0)
plt.yticks(range(1, rank_num + 1), yticks)
for a, b in zip(value, range(1, rank_num + 1)):
plt.text(a + 1, b, '%.0f' % a, ha='left', va='center')
plt.title('Bar')
st.write(fig)
fig = plt.figure(figsize=(13, 6), dpi=100)
plt.subplot(132)
plt.pie(value, explode=[0.2] * rank_num, labels=yticks, autopct='%1.2f%%', pctdistance=0.7)
plt.title('Pie')
st.write(fig)
|
641310e371de567a42734b4fb27e3f187a45bca5 | c3c-git/O-Python | /error.py | 657 | 3.53125 | 4 | # module error
"""Сообщения об ошибках"""
import loc
import text
def _error(pos, msg):
while text.ch() != text.chEOL and text.ch() != text.chEOT:
text.nextCh()
print(' ' * (pos - 1), '^', sep='')
print(msg)
exit(1)
def lexError(msg):
_error(loc.pos, msg)
def Expected(msg):
_error(loc.lexPos, "Ожидается " + str(msg))
def posExpected(msg, p):
_error(p, "Ожидается " + str(msg))
def posError(msg, p):
_error(p, str(msg))
def Error(msg):
print()
print(msg)
exit(1)
def cntError(msg):
_error(loc.lexPos, str(msg))
|
fa1b58f3b65cb4130eeee829fc8ad91cec51426a | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/hamming/0cd3f763788f4e6bbfa1c79a94287271.py | 125 | 3.546875 | 4 | def distance(s1, s2):
distance = 0
for i in range(0, len(s1)):
if s1[i] != s2[i]:
distance += 1
return distance
|
cf868b828169e39c6c0a7191916895225b58b4b7 | desve/netology | /tasks/3/3-2.py | 175 | 3.796875 | 4 | # Дробная чвсть
print("Ввведите положительгое число")
n = float( input())
m = int(n)
m1 = n - m
print("Дробная часть", m1) |
dc011782edf811c9378946b8911dbe29a32253d5 | rafaelblira/python-progressivo | /soma_media_colecao.py | 560 | 3.84375 | 4 | #Faça um programa que calcule o valor total investido por um colecionador em sua coleção de CDs e o valor médio gasto em cada um deles. O usuário deverá informar a quantidade de CDs e o valor para em cada um.
quant = int(input('Digite a quantidade de CDs: '))
cont = 0
soma = 0
media = 0
produto = 0
while cont < quant:
produto = float(input('Quanto custou o {}º CD? R$ '.format(cont + 1)))
cont += 1
soma += produto
media = soma / quant
print('O valor total investido é R$ {:.2f} e o valor médio gasto foi R$ {:.2f}'.format(soma, media))
|
fb0576dd2dd6b572a76a2a714fba3e081760ced0 | Nurzhan097/lern_py | /files.py | 712 | 3.703125 | 4 | import zipfile
import os
# with open("file_test.txt", 'w', encoding="UTF-8") as f:
# f.write("Hello page")
# def read_dir(folder):
# for root, dirs, files in os.walk(folder):
# print(f"{root.count(os.sep) * '----'} [{os.path.basename(root)}]")
# for file in files:
# print(f"{root.count(os.sep) * '----'} {file}")
# read_dir('folder')
# print(list(os.walk('folder')))
zip_file = zipfile.ZipFile("archive.zip", 'w', zipfile.ZIP_DEFLATED)
for folder in list(os.walk('folder')):
zip_file.write(folder[0])
for file in folder[2]:
print(folder[0], file)
zip_file.write(f"{folder[0]}{os.sep}{file}")
# zip_file.write('file_test.txt')
zip_file.close() |
f519d6eb68d46fd367c80087dda3184bd5f55152 | nla-group/slearn | /slearn/mkc.py | 2,704 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""This part is for string sequence generation"""
import numpy as np
class markovChain(object):
def __init__(self, transition_prob):
"""
Initialize the MarkovChain instance.
Parameters
----------
transition_prob: dict
A dict object representing the transition
probabilities in Markov Chain.
Should be of the form:
{'state1': {'state1': 0.1, 'state2': 0.4},
'state2': {...}}
"""
self.transition_prob = transition_prob
self.states = list(transition_prob.keys())
def next_state(self, current_state):
"""
Returns the state of the random variable at the next time
instance.
Parameters
----------
current_state: str
The current state of the system.
"""
next_ = np.random.choice(self.states, p = [
self.transition_prob[current_state][next_state]
for next_state in self.states]
)
return next_
def generate_states(self, current_state, no=10):
"""
Generates the next states of the system.
Parameters
----------
current_state: str
The state of the current random variable.
no: int
The number of future states to generate.
"""
future_states = []
for i in range(no):
next_state = self.next_state(current_state)
future_states.append(next_state)
current_state = next_state
return ''.join(future_states)
def markovMatrix(n = 26):
'''
Generates a Markov matrix for transition among n symbols
Parameters
----------
n: int
number of symbols
'''
np.random.seed(0) # for replicability
symbols = [chr(i+65) for i in range(n)] # list of available symbols
markov_matrix = {}
for i, s in enumerate(symbols):
dim = len(symbols)
# Probabilities of change of state (symbol)
# Random with a decreasing probability to jump to the farthest states
# It could be replaced by a negative logarithmic function to make it more
# likely to land in the same state and change the complexity of the sequence
probs = np.random.random(dim*3)
probs.sort()
probs = np.append(probs[dim%2::2], probs[::-2])
offset = -int(dim*1.5)
# to keep the highest value in the current state
probs = np.roll(probs, offset+i)[:dim]
probs /= probs.sum()
markov_matrix[s] = {s: p for s, p in zip(symbols, probs)}
return markov_matrix
|
3ec0030ddcd288e05199682b37179a2aff788701 | JayWelborn/Grocery | /Main2.py | 4,428 | 4.3125 | 4 | import os
class Grocery(object):
def __init__(self, name, position):
self.name = name
self.position = position
def __str__(self):
print self.name
# This Function gets a list of items from the user and puts them into a list
def get_items(list1):
item = raw_input("Add item to list or \ntype 'finished' if finished \n> ")
if item == '':
print "You didn't type anything"
get_items(list1)
elif 'finished' not in item:
list1.append(Grocery(item, 0))
get_items(list1)
elif 'finish' in item:
print "Today's list is: "
print [item.name for item in list1]
# This function will compare items from today's list to the master list,
# and sort them accordingly. It will place items not on the master list at the end.
def sort_todays_items(list1, list2, list3):
count = 0
for item in list1:
name = item.name
count += 1
if name in list3:
item.position = list3.index(name)
elif name not in list3:
item.position = count
else:
print "Unknown Error."
sorted_list = sorted(list1, key=lambda item: item.position)
print "Today's list sorted based on master: "
print [item.name for item in sorted_list]
for item in sorted_list:
name = item.name
list2.append(name)
# This function sorts todays items in the order the user checks them off,
# and makes a new list, including new items from today.
def check_items(list1, list2):
while list1:
item = raw_input("Item checked: ")
if item in list1:
list1.remove(item)
list2.append(item)
print item, "; check!"
elif item not in list1:
print "Item not on list"
if len(list1) == 0:
print "Items were checked in this order: ", list2
else:
print "check_items error"
# This function adds items checked today to the master list.
# If the items aren't already on the master list, it will add them
# immediately after the previously checked item.
# If first item isn't on master list, it will be added at the front of the master list.
# If an item from a pr
def fix_master_list(list1, list2):
for item in list1:
item_index = list1.index(item)
# The following tells how to tell where the first item on the list should go
if item_index == 0 and len(list1) > 1:
next_item = list1[item_index + 1]
if item not in list2: # If it's a new item it will get added at the front of the master
list2.insert(0, item)
elif item in list2 and next_item in list2: # If it's an old item, this corrects its position
master_item_index = list2.index(item)
next_item_index = list2.index(next_item)
list2.pop(master_item_index)
list2.insert(next_item_index - 1, item)
else:
previous_item = list1[item_index - 1]
if item in list2:
item_location = list2.index(item)
previous_item_location = list2.index(previous_item)
# This handles re-sorting items placed erroneously on previous trips based on incomplete data
if item_location < previous_item_location:
list2.pop(item_location)
list2.insert(previous_item_location + 1, item)
else:
x = list2.index(previous_item)
list2.insert(x + 1, item)
target = open("listsave.txt", 'w')
target.writelines("%s\n" % item for item in list2)
if __name__ == '__main__':
todays_list = []
todays_sorted_list = []
checked_list = []
if os.path.isfile('listsave.txt'):
read_list = open('listsave.txt', 'r')
master_list = [x.strip('\n') for x in read_list.readlines()]
else:
read_list = open('listsave.txt', 'w+')
master_list = [x.strip('\n') for x in read_list.readlines()]
print "master_list is: "
print master_list
get_items(todays_list)
sort_todays_items(todays_list, todays_sorted_list, master_list)
check_items(todays_sorted_list, checked_list)
fix_master_list(checked_list, master_list)
print "master list is"
print master_list
|
059c076210d921a896e6dc0c21aeacde1a3eaeb5 | ConorFlanagan/210CTCW | /Week1/Q1_shuffle.py | 345 | 3.65625 | 4 | import random
def shuf(List):
for a in range(len(List)-1,0,-1): #For each index of array
b=random.randint(0,a) #Selects random second index
if b == a:
continue
List[a],List[b] = List[b],List[a] #Swap selected indexes
return (List)
#Run-time bounds (Big O):
#O(n)
|
c7a3a2dc607b8dedafe93e564d333bdeb5c3dcca | LizinczykKarolina/Python | /Loops and conditions/ex1.py | 731 | 4.25 | 4 | #1. Write a Python program to find those numbers which are divisible by 7 and multiple of 5, between 1500 and 2700 (both included).
new_list = []
for i in range(1500, 1700):
if i % 7 == 0 and i % 5 == 0:
new_list.append(str(i))
print ",".join(new_list)
#2. Write a Python program to convert temperatures to and from celsius, fahrenheit.
x = raw_input("would you like to convert fahrenheit(f) or celsius(c)?")
if x == "c":
d = raw_input("how much would you like to convert?")
z = (int(d) * 1.8) + 32
print "{0} celsius is {1} farenheit".format(d, z)
else:
k = raw_input("how much would you like to convert?")
y = (int(k) - 32) / 1.8
print "{0} celsius is {1} farenheit".format(k, y)
|
6bfc31c0159c04fac546d02b28ef0f66dd2950b9 | andrewBatutin/p_nato_alp | /nato_alph.py | 1,434 | 3.796875 | 4 | #!/usr/bin/python
import sys
numbers = {
"1": "One",
"2": "Two",
"3": "Three",
"4": "Four",
"5": "Five",
"6": "Six",
"7": "Seven",
"8": "Eight",
"9": "Nine",
"0": "Zero"
}
letters = {
"A": "Alpha",
"B": "Bravo",
"C": "Charlie",
"D": "Delta",
"E": "Echo",
"F": "Foxtrot",
"G": "Golf",
"H": "Hotel",
"I": "India",
"J": "Juliett",
"K": "Kilo",
"L": "Lima",
"M": "Mike",
"N": "November",
"O": "Oscar",
"P": "Papa",
"Q": "Quebec",
"R": "Romeo",
"S": "Sierra",
"T": "Tango",
"U": "Uniform",
"V": "Victor",
"W": "Whiskey",
"X": "X-ray",
"Y": "Yankee",
"Z": "Zulu"
}
additional_letters = {
" ": "space",
"-": "dash",
".": "dot",
",": "comma",
":": "colon",
";": "semicolon",
"@": "at"
}
def convert_to_nato(phrase):
res = ""
for l in phrase:
res = res + " " + convert_nato_letter(l)
return res
def convert_nato_letter(letter):
if letter.upper() in letters:
return letters[letter.upper()].upper()
elif letter in additional_letters:
return additional_letters[letter]
elif letter in numbers:
return numbers[letter].upper()
else:
return letter
def main(argv):
data = argv
for phrase in data:
print convert_to_nato(phrase)
if __name__ == "__main__":
main(sys.argv[1:])
|
a3405cd836020b0b223484469d489e5e9b924e43 | BrianTurnwald/DS201-With-Chyld | /2018-01-08/stats.py | 2,430 | 3.90625 | 4 | """
Module/file docstring
Run:
python -m doctest -v stats.py
"""
def add(num1,num2):
return num1 + num2
def cubevol(length,width,height):
return length * width * height
def mean(numbers): #works
sm = 0
for x in numbers:
sm += x
#print(sm)
#print(len(numbers))
return sm / len(numbers)
def mean2(numbers): #better
return sum(numbers) / len(numbers)
def median(numbers): #works
#number.sort() will change the original variable
x = sorted(numbers)
if len(x) %2 == 0:
mid = int(len(x) / 2)-1
return (x[mid] + x[mid+1]) / 2
else:
mid = int(len(x)/2)
return x[mid]
def median2(numbers): #better
"""Computes the median of a list of numbers.
arguments: list of numbers
return: the median (int for odd len list, float for even len list)
The ">>>" below will actually run the test when runing the file
with doctest: python -m doctest -v stats.py
>>> median([2,1,6])
2
>>> median([3,7])
5.0
"""
#number.sort() will change the original variable
x = sorted(numbers)
mid = len(x)//2
if len(x) %2 == 0:
return sum(x[mid-1:mid+1]) / 2
else:
return x[mid]
def mode(numbers):
"""Find the most common value in the list
arguments: list of numbers
return: the mode
>>> mode([9,9,8,8,7,6])
8
"""
#defaultdict
from collections import defaultdict
d = defaultdict(int)
for k in numbers:
d[k] += 1
for x in d:
if d[x] > 1:
p = 'Not Unique, Not Bimodal'
max_mode = sorted(d, key=lambda key: d[key])[-1]
max_next = sorted(d, key=lambda key: d[key])[-2]
if max_mode == max_next:
p='Bimodal'
return min(max_mode,max_next)
else:
return max(d, key=lambda key: d[key])
else:
p = 'Unique'
return min(d)
#return max(d, key=lambda key: d[key])
#or sorted(d, key-lambda key: d[key], reverse=True)[0]
#or sorted(d, key-lambda key: d[key])[-1]
def mode2(numbers):
"""Find the most common value in the list
arguments: list of numbers
return: the mode
>>> mode([9,9,8,8,7,6])
8
"""
#defaultdict
from collections import defaultdict
d = defaultdict(int)
for k in numbers:
d[k] += 1
return max(d, key=lambda key: d[key])
|
ced6c079a775a22e750e2c418869acc78f5bd85d | sbenning42/42 | /PyMuse/TcpSocket.py | 3,149 | 3.671875 | 4 | import socket, struct
#TcpSocket class is a socket.socket inherit, that handle TCP communication message way
#All TcpSocket message are preffixed with the 4 bytes, big endian, unsigned size of that TcpSocket message
#That way if a server and a client both use the TcpSocket's mthods for message communication
#They can both ensure that the message will be send and receive entierly
#Here is the protocol picture:
# Have a variable length message: 'Msg...'
# Encode its size with struct.pack '>L' in front of it: "[4-bytes-bigEndian-unsigned-size]['Msg...']"
# Send all the packet
# Read 4 byte from the socket, unpack it with struct.unpack '>L'
# Then loop on the read socket until all that length has been read and return the message
#TcpSocket module include two other classes, TcpSocketClient and TcpSocketServer
#TcpSocketClient is a TcpSocket who try to connect when instanciate
#TcpSocketServer is a TcpSocket who bind and listen when instanciate
#TcpSocketServer also provide a wrapper for accept method in order to return a TcpSocket insteas of socket.socket
#All socket.error catched raise TcpSocketError
#Additionnaly a TcpSocketError is raise for a empty message on the socket
class TcpSocketError(Exception):
pass
class TcpSocket(socket.socket):
def __init__(self, fileno=None):
self._header_size = struct.calcsize('>L')
socket.socket.__init__(self, socket.AF_INET, socket.SOCK_STREAM, 0, fileno)
def msg_recv(self):
header = int(self._header_recv())
# print 'RECV : header', header
raw_chunk = ''
while len(raw_chunk) < header:
raw_chunk += self._raw_recv(header - len(raw_chunk))
# print 'RECV :', raw_chunk, len(raw_chunk)
return struct.unpack('%ds' % header, raw_chunk)[0]
def msg_send(self, msg):
self._raw_sendall(struct.pack('>L%ds' % len(msg), len(msg), msg))
# print 'SEND :', msg, len(msg)
def _header_recv(self):
return struct.unpack('>L', self._raw_recv(self._header_size))[0]
def _raw_recv(self, size):
try:
raw = self.recv(size)
except socket.error as error:
raise TcpSocketError(error)
if not raw or len(raw) == 0:
raise TcpSocketError('TcpSocket : Empty socket')
return raw
def _raw_sendall(self, raw):
try:
self.sendall(raw)
except socket.error as error:
raise TcpSocketError(error)
class TcpSocketClient(TcpSocket):
def __init__(self, addr='localhost', port=9999):
TcpSocket.__init__(self)
try:
self.connect((addr, port))
except socket.error as error:
raise TcpSocketError(error)
class TcpSocketServer(TcpSocket):
def __init__(self, addr='', port=9999):
TcpSocket.__init__(self)
self.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
self.bind((addr, port))
except socket.error as error:
raise TcpSocketError(error)
self.listen(5)
def accept(self):
sock, addr = socket.socket.accept(self)
return TcpSocket(sock), addr
|
896d02640ef7f7d66da3701dcf00bf743a0d7fec | RussellSB/mathematical-algorithms | /task1.py | 3,415 | 4 | 4 | #Name: Russell Sammut-Bonnici
#ID: 0426299(M)
#Task: 1
import random #used for choosing random pivot
#class for storing pair's details
class Pair:
#initialises product pair
def __init__(self,a,b):
self.a = a
self.b = b
self.product = a*b
#recursive method for sorting pairs by products
def sortByProduct(objList):
#base case for when segment's length is less than or equal to one
if(len(objList)<=1):
return objList
smaller=[] #initialized for storing the smaller segment of the list
equivalent=[] #initialized for storing the element at the pivot
greater=[] #initialized for storing the greater segment of the list
#randomly chosen pivot selected from list of pairs
pivot = objList[random.randint(0,len(objList)-1)]
#for loop to go through the list of pairs
for x in objList:
#when x is less, append to smaller segment
if(x.product < pivot.product):
smaller.append(x)
#when x is at the pivot, store element into equivalent
elif(x.product==pivot.product):
equivalent.append(x)
#when x is greater, append to greater segment
elif(x.product > pivot.product):
greater.append(x)
else:
print("An unknown error has occurred during sorting by Product")
#recursively calls method to work on the smaller and greater segment, then returns on backtracking
return sortByProduct(smaller) + equivalent + sortByProduct(greater)
#method for finding product matches
def findProductMatches(rangeList):
pairList = [] #initialized for storing products pairs and their components
# outer loop for a equivalent
for x in rangeList:
# inner loop for b equivalent
for y in rangeList:
if(y>x): #condition to avoid repeated a*b combinations
pairList.append(Pair(x,y))
pairList = sortByProduct(pairList) #sorts by product using quick sort
i = 0 #initialized index to 0
#goes through every index in the pairList array
while(i<len(pairList)):
#Accesses this during the last iteration when the last index has no matching products. Avoids OutOfIndex exception, iterates to exit loop
if(i==len(pairList)-1):
i+=1
#If pair at index has a unique product, skips cause no matches
elif(pairList[i].product != pairList[i+1].product):
i+=1
#If current pair is seen to have at least one match, access while loop
elif(pairList[i].product == pairList[i+1].product):
print("The pair [%d*%d = %d] matches with"%(pairList[i].a, pairList[i].b, pairList[i].product)),
#traverses through products, displaying the matches until there are no more (stops when at the end)
while(i!=len(pairList)-1 and pairList[i].product == pairList[i+1].product):
print("[%d*%d = %d] and"%(pairList[i+1].a, pairList[i+1].b, pairList[i+1].product)),
i+=1
print(",") #prints comma indicating end of line
#else statement used for unconsidered scenarios
else:
print("Error: something wrong has occurred during printing.")
return 0
print("Matching products from 1 to 1024 are;")
findProductMatches(range(1, 1025)) #or (range(1,26))
|
e855bcd3abdfaeb6b7275b8e097530544c625e47 | duducosmos/multiresolutionfit | /src/multiresolutionfit/countclass.py | 1,873 | 3.8125 | 4 | #!/usr/bin/env python3
# -*- Coding: UTF-8 -*
"""
Count Class function.
Return a dictionary where key represents the class and value the total number
of object in two scenes.
Example
-------
>>> from numpy.random import randint
>>> from multiresolutionfit import countclass
>>> scene1 = randint(256, size=(50, 50))
>>> scene2 = randint(256, size=(50, 50))
>>> cnt1, cnt2 = countclass(scene1, scene2)
License
-------
Developed by: E. S. Pereira.
e-mail: [email protected]
Copyright [2019] [E. S. Pereira]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from collections import OrderedDict
from numpy import unique
def countclass(scene1, scene2):
"""
Count Class function.
Return a dictionary where key represents the class and value the total number
of object in two scenes.
:parameter 2d_array scene1: numpy gray image array.
:parameter 2d_array scene2: numpy gray image array.
Example
-------
>>> from numpy.random import randint
>>> from multiresolutionfit import countclass
>>> scene1 = randint(256, size=(50, 50))
>>> scene2 = randint(256, size=(50, 50))
>>> cnt1, cnt2 = countclass(scene1, scene2)
"""
unq1, cnts1 = unique(scene1, return_counts=True)
unq2, cnts2 = unique(scene2, return_counts=True)
cnt1 = OrderedDict(zip(unq1, cnts1))
cnt2 = OrderedDict(zip(unq2, cnts2))
return cnt1, cnt2
|
ef7d1c696cafe3041b8afb397def3ec0ebdd31dc | varunmiranda/Algorithms-Python | /Longest common subsequence - CLRS/LCS.py | 1,442 | 3.828125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: varunmiranda
Citation:
Introduction to Algorithms 3rd Edition, CLRS - LCS implementation (Dynamic Programming)
"""
"Reading the Inputs"
X=['A','B','C','B','D','A','B']
Y=['B','D','C','A','B','A']
#X=[1, 0, 0, 1, 0, 1, 0, 1]
#Y=[0, 1, 0, 1, 1, 0, 1, 1, 0]
m=len(X)
n=len(Y)
"Initializing b and c that stores the directions and the values respectively"
b = [[' ' for i in range(n)] for j in range(m)]
c = [[0 for i in range(n+1)] for j in range(m+1)]
"Setting the first row and first column as 0 in array c"
for i in range(1,m+1):
c[i][0] = 0
for j in range(0,n+1):
c[0][j] = 0
"tl denotes top left, t denotes top, l denotes left"
for i in range(1,m+1):
for j in range(1,n+1):
if(X[i-1]==Y[j-1]):
c[i][j] = c[i-1][j-1]+1
b[i-1][j-1] = "tl"
elif(c[i-1][j] >= c[i][j-1]):
c[i][j] = c[i-1][j]
b[i-1][j-1] = "t"
else:
c[i][j] = c[i][j-1]
b[i-1][j-1] = "l"
"Storing the longest common subsequence in an array Z"
def print_lcs(b,X,i,j):
if i==-1 or j==-1:
return Z
if b[i][j] == "tl":
print_lcs(b,X,i-1,j-1)
Z.append(X[i])
elif b[i][j] == "t":
print_lcs(b,X,i-1,j)
else:
print_lcs(b,X,i,j-1)
"Providing the initial parameters for the print_lcs function and returning Z"
Z = []
print_lcs(b,X,m-1,n-1)
print(Z)
|
b26576613b62f6c3ab7379f6e7fcc55eb55b1e5a | Marta37937/EmployeeMerge | /database.py | 2,105 | 3.765625 | 4 | import sqlite3
class DatabaseContextManager(object):
def __init__(self, path):
self.path = path
def __enter__(self):
self.connection = sqlite3.connect(self.path)
self.cursor = self.connection.cursor()
return self.cursor
def __exit__(self, exc_type, exc_val, exc_tb):
self.connection.commit()
self.cursor.close()
self.connection.close()
def create_employee_table():
query = """CREATE TABLE IF NOT EXISTS Employees(
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
role TEXT,
annual_salary FLOAT,
feedback INTEGER,
years_employed INTEGER,
email TEXT)"""
with DatabaseContextManager("employees") as db:
db.execute(query)
#create_employee_table()
def create_employee(first_name: str, last_name: str, role: str, annual_salary: float, feedback: int,
years_employed: int, email: str):
query = f"""INSERT INTO Employees(first_name, last_name, role, annual_salary, feedback, years_employed, email)
VALUES('{first_name}','{last_name}','{role}',{annual_salary},'{feedback}','{years_employed}', '{email}')"""
with DatabaseContextManager("employees") as db:
db.execute(query)
def get_employees():
query = f"SELECT * FROM Employees"
with DatabaseContextManager("employees") as db:
data = db.execute(query)
for record in data:
print(record)
get_employees()
def check_if_employee_exists_in_database(email: str):
query = f"SELECT * FROM Employees WHERE email = '{email}'"
with DatabaseContextManager("employees") as db:
db.execute(query)
employee = db.fetchone()
if employee == None:
return False
return True
def delete_employee(email: str):
query = f"DELETE FROM Employees WHERE email = '{email}'"
with DatabaseContextManager("employees") as db:
db.execute(query) |
b4a1b796b4b64c11681bcebd8943c1df4edfa707 | rutujak993/Rutuja_Python_Practice | /Reverse_The_words_from_Sentence.py | 376 | 3.984375 | 4 | #WAP to accept a sentence from user and reverse every word from the sentence
def SentenceConversion(sentence):
l1 = sentence.split(' ')
for i in range(0,len(l1)):
l1[i] = l1[i][::-1]
return ' '.join(l1)
def main():
String1 = input("Enter a sentance : ")
print(SentenceConversion(String1))
if __name__=="__main__":
main()
|
ab5df4cf85b29ab9c3b63bd09d3de55d05d16109 | raytso0831/unit-4 | /functionDemo.py | 525 | 3.953125 | 4 | #Ray Tso
#3/9/18
#functionDemo.py
def hw():
print("hello, world")
def double(thingToDouble):
print(thingToDouble * 2)
def bigger(a,b):
if a>b:
print(a)
else:
print(b)
def slope(x1, y1, x2, y2):
print((y2 - y1)/(x2 - x1))
slope(1,1,2,2)
slope(True,True,False,False) #sketchy
#bigger(3,4)
#bigger(4,3)
#bigger("Smedinghoff","Sam")
#bigger(True,False)
#double(12) #test of double function
#double('w') #test of double with a string input
#double(False) #test of double with a boolean |
d3a8de72c6610a9132794982dc124a57dfd7673d | Silent-wqh/PycharmProjects | /PyProjects/buy_pencil.py | 1,090 | 3.59375 | 4 | pens=[[],[],[]]
total_money = []
total_num = int(input().strip())
pens[0] = list(input().strip().split())
pens[1] = list(input().strip().split())
pens[2] = list(input().strip().split())
def calcu(need_num, pens, current_money=0):
for pen in pens:
if need_num/int(pen[0]):
curr_need_num = need_num - (need_num/int(pen[0])*int(pen[0]))
current_money = need_num/int(pen[0]) * int(pen[1])
calcu(curr_need_num, pens, current_money)
else:
for pen in pens:
total_money.append(current_money+int(pen[1]))
calcu(total_num, pens)
total_money.sort(key=int)
print(total_money[0])
"""
for num1 in range(0, int(total_num/int(pens[0][1])+1)):
for num2 in range(0, int(total_num/int(pens[1][1])+1)):
for num3 in range(0, int(total_num/int(pens[2][1])+1)):
if num1*int(pens[0][1]) + num2*int(pens[1][0]) + num3*int(pens[2][0]) >= total_num:
total_money.append(num1*int(pens[0][1])+num2*int(pens[1][1])+num3*int(pens[2][1]))
total_money.sort(key=int)
print(total_money[0])
"""
|
43be91ba6bfa59462665e3afb16091ef33a6a631 | tommyyearginjr/PyCodingExercises | /delDel/delDel.py | 420 | 3.921875 | 4 | '''
Given a string, if the string "del" appears starting at index 1, return a string where that "del" has been deleted. Otherwise, return the string unchanged.
delDel("adelbc") --> "abc"
delDel("adelHello") --> "aHello"
delDel("adedbc") --> "adedbc"
'''
def delDELETED(string):
print('{} ---> {}'.format(string, string.replace('del', '')))
delDELETED('adelbc')
delDELETED('adelHello')
delDELETED('adedbc')
|
e5588a14c520de78a5553a3af9178caea7bf0271 | Coobie/DADSA-2-Tennis | /solution/factor.py | 812 | 3.59375 | 4 | __author__ = "JGC" # Author: JGC
if __name__ == "__main__": # File is opened directly
print("This file has been called incorrectly")
class Factor(object):
"""Class for a factor"""
def __init__(self,amount,difference):
"""
Constructor for factor
:param float amount: multiplier
:param int difference: different in points
"""
self.__amount = amount
self.__diff = difference
def get_amount(self):
"""
Get the amount (multiplier)
:return float amount: the multiplier for the points
"""
return self.__amount
def get_diff(self):
"""
Get the difference in points required for the factor
:return int diff: difference in points (w - l)
"""
return self.__diff |
1b95b893829705a8a8d24176beae9bc942fb8016 | DiksonSantos/GeekUniversity_Python | /137_Deltas_De_Data_E_Hora.py | 670 | 3.8125 | 4 | """
Delta é a diferença entre uma data inicial Menos a Data Final:
03-04-2020 á 04-05-2020 -> Delta = 31 Dias
"""
"""
import datetime
data_hoje = datetime.datetime.now()
Birthday = datetime.datetime(2021, 3, 24, 00)
Res = data_hoje - Birthday
print(Res*-1) # 365 days, 20:38:56.004360 -> Hoje é 23-03-2020 03:20H Matina.
print(Res.days*-1, " Dias Restantes")
print(type(Res)) # Tipo TimeDelta
"""
import datetime
Data_Compra = datetime.datetime.now()
Regra_Boleto = datetime.timedelta(days=3)
print(Regra_Boleto)
Vencimento = Data_Compra + Regra_Boleto
print("Data Do Vencimento: ", Vencimento.day, "/", Vencimento.month, "/", Vencimento.year)
|
d249030fd4dc952165f8ec5b8d48c11d5001db99 | andclima/algoritmo | /aula-09/exemplo.py | 354 | 3.859375 | 4 | # Alô, som!
nome = "Joao"
idade = 21
valor = 29.31
idade = int(input(f"Informe a idade de {nome}: "))
print(f"{nome} tem {idade} anos e possui R$ {valor} na carteira")
if idade < 21:
print(f"{nome} ainda nao possui idade suficiente para maioridade civil.")
else:
print(f"{nome} ja pode ser declarado civilmente capaz.")
print("Ate a proxima!") |
b8bc7711da99b6690b25d835294a79f4042226e9 | SmileShmily/LaunchCode-summerofcode-Unit1 | /ClassExercise & studio/chapter 14/Sameness.py | 2,411 | 4.28125 | 4 | '''For example, if you say, Chris and I have the same car, you mean that his car and yours are the same make and model,
but that they are two different cars. If you say, Chris and I have the same mother, you mean that his mother and yours are the same person.
When you talk about objects, there is a similar ambiguity. For example,
if two Fractions are the same, does that mean they contain the same data (same numerator and denominator) or that they are actually the same object?
We’ve already seen the is operator in the chapter on lists, where we talked about aliases.
It allows us to find out if two references refer to the same object.
'''
class Fraction:
def __init__(self, top, bottom):
self.num = top # the numerator is on top
self.den = bottom # the denominator is on the bottom
def __str__(self):
return str(self.num) + "/" + str(self.den)
myfraction = Fraction(3, 4)
yourfraction = Fraction(3, 4)
print(myfraction is yourfraction)
ourfraction = myfraction
print(myfraction is ourfraction)
'''This type of equality is called shallow equality because it compares only the references, not the contents of the objects.
Using the == operator to check equality between two user defined objects will return the shallow equality result.
In other words, the Fraction objects are equal (==) if they are the same object.
Of course, we could define equality to mean the fractions are the same in that they have the same numerator and the same denominator.
For example, here is a boolean function that performs this check.
def sameFraction(f1, f2):
return (f1.getNum() == f2.getNum()) and (f1.getDen() == f2.getDen())
This type of equality is known as deep equality since it compares the values “deep” in the object, not just the reference to the object.
'''
def sameFraction(f1, f2):
return (f1.getNum() == f2.getNum()) and (f1.getDen() == f2.getDen())
class Fraction:
def __init__(self, top, bottom):
self.num = top # the numerator is on top
self.den = bottom # the denominator is on the bottom
def __str__(self):
return str(self.num) + "/" + str(self.den)
def getNum(self):
return self.num
def getDen(self):
return self.den
myfraction = Fraction(3, 4)
yourfraction = Fraction(3, 4)
print(myfraction is yourfraction)
print(sameFraction(myfraction, yourfraction)) |
32b112a4e815d327d9fc69407cd1fc31f27d3c56 | jakehoare/leetcode | /python_1_to_1000/150_Evaluate_Reverse_Polish_Notation.py | 1,050 | 3.59375 | 4 | _author_ = 'jake'
_project_ = 'leetcode'
# https://leetcode.com/problems/evaluate-reverse-polish-notation/
# Evaluate the value of an arithmetic expression in Reverse Polish Notation.
# Valid operators are +, -, *, /. Each operand may be an integer or another expression.
# Push numbers onto stack. Apply operators to top 2 members of stack and push back result.
# Faster but less concise without using eval().
# Time - O(n)
# Space - O(n)
class Solution(object):
def evalRPN(self, tokens):
"""
:type tokens: List[str]
:rtype: int
"""
ops = {'+', '-', '/', '*'}
stack = []
for token in tokens:
if token in ops:
right = stack.pop()
left = stack.pop()
if token == '/':
stack.append(int(left / float(right))) # round down
else:
stack.append((eval(str(left) + token + str(right))))
else:
stack.append(int(token))
return stack[-1]
|
9fed9f09d8555aae4cf848cf99885164151f6cab | maximkha/peeks | /test3.py | 499 | 3.921875 | 4 | from Peeks import Peekstr
s = "I am a string" #"I am a string"
peeked = Peekstr(s)
for c in peeked:
if c == "": break #peeked does not throw a stop iterator!!!
if peeked.peek(4) == "am a":
print("I found the substring!")
print(f"{peeked.Position}")
break
peeked = Peekstr(s)
for c in peeked:
if c == "": break #peeked does not throw a stop iterator!!!
print(c)
if peeked.peek(1) == "a":
peeked.consume(1) #skip the next character if it's an 'a' |
f95936c56c6abda10b2ea4623d385ee0e886ac5d | xboard/AoC | /2020/Day_15/rambunctious_recitation.py | 2,651 | 3.84375 | 4 | #!/usr/bin/env python3
"""
Solves day 15 tasks of AoC 2020.
https://adventofcode.com/2020/day/15
"""
import argparse
from typing import Sequence, List
from collections import defaultdict
SEQUENCE = [14, 3, 1, 0, 9, 5]
def task(sequence: List[int], ith: int) -> int:
"""
Solve task 1 or 2.
Parameters
----------
sequence: List[int]
List with initial sequence.
ith: int
desired i-th number in sequence.
Return
------
int
i-th number in sequence.
"""
seen = defaultdict(list)
for pos, num in enumerate(sequence):
seen[num].append(pos)
prev = sequence[-1]
for pos in range(len(seen), ith):
# print(f"seen[{prev}] = {seen[prev]}")
if len(seen[prev]) < 2:
curr = 0
else:
curr = seen[prev][-1] - seen[prev][-2]
seen[curr].append(pos)
prev = curr
return prev
def get_input() -> List[int]:
"""
Parse arguments passed to script.
Return:
Path
path to gziped file for this problem.
"""
parser = argparse.ArgumentParser()
msg = "comma separated numbers, i.e '0,3,6'"
parser.add_argument("sequence", help=msg)
args = parser.parse_args()
return list(map(int, args.sequence.split(",")))
def main() -> None:
"""Run script."""
sequence = get_input()
answer = task(sequence, 2020)
print(f"Task 1: {answer}.")
answer = task(sequence, 30000000)
print(f"Task 2: {answer}.")
if __name__ == "__main__":
main()
#######################
# Tests section #
#######################
def sample_seqs() -> Sequence[Sequence[int]]:
"""Sample seq from statement."""
return ((1, 3, 2), (2, 1, 3), (1, 2, 3), (2, 3, 1), (3, 2, 1), (3, 1, 2))
def test_task1_with_example_input():
"""Test task1 with problem statement example."""
assert task((0, 3, 6), 4) == 0
assert task((0, 3, 6), 5) == 3
assert task((0, 3, 6), 6) == 3
assert task((0, 3, 6), 7) == 1
assert task((0, 3, 6), 8) == 0
assert task((0, 3, 6), 9) == 4
assert task((0, 3, 6), 10) == 0
seq = sample_seqs()
ith = 2020
assert task(seq[0], ith) == 1
assert task(seq[1], ith) == 10
assert task(seq[2], ith) == 27
assert task(seq[3], ith) == 78
assert task(seq[4], ith) == 438
assert task(seq[5], ith) == 1836
def test_task1_with_input_file():
"""Test task1 with given input file (gziped)."""
val = task(SEQUENCE, 2020)
assert val == 614
def test_task2_with_input_file():
"""Test task2 with given input file (gziped)."""
val = task(SEQUENCE, 30000000)
assert val == 1065
|
62d96faf2d20070a5403801a793c24117d5ad151 | goareum93/K-digital-training | /01_Python/18_OOP/05_클래스상속.py | 1,985 | 3.921875 | 4 | # 클래스 상속(inheritance)
class Car:
number = 0
def __init__(self, speed=0, color='white'):
self.speed = speed
self.color = color
Car.number += 1
def __str__(self):
return '이 자동차의 색상은 %s이고,\n속도는 %d입니다.' % (self.color, self.speed)
# color 필드 값을 반환메소드
def getColor(self):
return self.color
# color 필드값을 변경메소드
def setColor(self, color):
self.color = color
def showInfo(self):
print('속도는 %d입니다.' % self.speed)
def drive(self):
if self.speed != 0:
print('%d 로 주행중입니다' % self.speed)
else:
print('정차중입니다')
def upSpeed(self, up):
self.speed += up
def downSpeed(self, down):
self.speed -= down
if self.speed < 0 :
self.speed = 0
class Truck(Car):
def __init__(self, speed, color, load):
super().__init__(speed, color) # 부모 객체 사용
self.load = load # 필드 추가
# 메소드를 재정의 : 오버라이딩(overriding)
def showLoad(self):
print(self.load)
def upLoad(self, up):
self.load += up
def showInfo(self):
print('Truck : 속도는 %d이고, 적재량은 %d입니다.' % (self.speed,self.load))
class SportCar(Car):
def __init__(self, speed, color, seats):
super().__init__(speed, color)
self.seats = seats
def showInfo(self):
print('Sport Car : 색상은 %s, 좌석수는 %d' %(self.color, self.seats))
car1 = Car()
car2 = Truck(0,'Blue', 1000)
car3 = SportCar(0,'Red',2)
car1.showInfo()
car2.showInfo()
car3.showInfo()
# print(isinstance(car2, Car))
# print(issubclass(Truck, Car))
# print(issubclass(bool, int))
# 다형성(polymorphism) : 동일한 이름의 메소드이지만, 다른 기능을 수행
carL = [car1, car2, car3]
for car in carL:
car.showInfo() |
dea15e3736111d09317f0d31765d1da04b09d427 | iangraham20/cs108 | /projects/03/triangle.py | 1,608 | 4.21875 | 4 | '''
This program uses turtle graphics to create triangles with user input coordinates
Created September 27, 2016
Homework 03 Exercise 3.2
@author: Ian Christensen (igc2)
'''
# import necessary libraries
import turtle
import math
# assign variables
x1 = int(input('Please enter first x-coordinate'))
x2 = int(input('Please Enter second x-coordinate'))
x3 = int(input('Please Enter third x-coordinate'))
y1 = int(0)
y2 = int(0)
y3 = int(input('Please Enter third y-coordinate'))
# create data structures
tup1 = (x1, y1)
tup2 = (x2, y2)
tup3 = (x3, y3)
tup4 = (x3, y1)
list1 = [tup1, tup2, tup3]
# find the lengths of each side
side1 = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
side2 = math.sqrt((x3 - x2)**2 + (y3 - y2)**2)
side3 = math.sqrt((x1 - x3)**2 + (y1 - y3)**2)
side4 = math.sqrt((x3 - x3)**2 + (y1 - y3)**2)
# assign perimeter and area to variables
perimeter = (side1 + side2 + side3)
area = (side1 * side4) / 2
# create window and name turtle
window = turtle.Screen()
joe = turtle.Turtle()
# draw triangle and perpendicular line
joe.penup()
joe.goto(tup3)
joe.pendown()
joe.goto(tup1)
joe.goto(tup2)
joe.goto(tup3)
joe.goto(tup4)
joe.penup()
# move to top left of window and write points, perimeter, and area
joe.goto(-250, 250)
joe.write('Points: '+str(list1), font=('Arial', 12, 'normal'))
joe.goto(-250, 230)
joe.write('Perimeter: '+str(perimeter)+' pixels', font=('Arial', 12, 'normal'))
joe.goto(-250, 210)
joe.write('Area: '+str(area)+' pixels squared', font=('Arial', 12, 'normal'))
# close window when clicked on
window.exitonclick()
|
d6f00fac79bd16f714b7a9e0fc6b26b25fbd5584 | kimdahyun0402/dao | /파이썬/4주차/4주차 1번..py | 623 | 3.984375 | 4 | list=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] #정수의 list를 생성했고 리스트의 이름을 list로 했다
print(list)
a=int(input("변경할 위치(0~9):")) #변경할 위치를 변수a로 설정하고 숫자로 전환시켰다
b=int(input("새로운 값:")) #변경할 값을 b라는 변수로 설정하고 숫자로 전환시켰다
list[a]=b #리스트의 a위치에 있는 값을 b로 변경시킴
print(list)
c=int(input("추가할 값:")) #리스트에 추가할 값을 변수 c로 놓고 숫자로 전환
list.append(c) #리스트에 c 추가
print(list)
|
c5611c1c88d774cff605f146a1ef9ede52c37c16 | AkmatovEldi/Init_Python | /lesson5.py | 1,258 | 3.671875 | 4 | # from datetime import datetime
#
#
# def timeit(func):
# def wrapper():
# start = datetime.now()
# func
# print(datetime.now() - start)
#
# return wrapper
#
#
# @timeit
# def one():
# l = []
# for i in range(10000):
# l.append(i)
# return f'{len(l)}'
#
#
# @timeit
# def two():
# l = [i for i in range(10000)]
# return f'{len(l)}'
#
#
# print(len(one()))
# print(len(two()))
#
# one()
#
# two()
# def make_upper(func):
# def wrapper():
# return func().upper()
# return wrapper
#
# def make_lower(func):
# def wrapper():
# return func().lower()
# return wrapper()
#
#
#
# @make_upper
# def hello():
# return 'Hello Eldi'
#
# @make_lower
# def myfunc():
# return 'I like Python'
#
# print(hello())
#
# print(myfunc())
# def decorator_func(func):
# def wrapper():
# print('Функция обертка')
# print(f'Оборачиваемая функция {func}')
# print('Выполняем обернутую функцию')
# func()
# print('Выходим из обертки')
# return wrapper
#
# @decorator_func
# def hello():
# print('Hello Eldi')
#
# hello()
RedGreen
Black
White
Pink
Yellow
|
843bc43c66d7f4eb279269279e4edc3a4bfeacb3 | margaridav27/feup-fpro | /Plays/Play06/bagdiff.py | 314 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Nov 25 17:15:34 2019
@author: Margarida Viera
"""
def bagdiff(xs, ys):
output = []
for n in xs:
if n in ys:
ys.remove(n)
else:
output.append(n)
return output
print(bagdiff([5, 7, 11, 11, 11, 12, 13], [7, 8, 11]))
|
6134d5e3919c7eb859b696c4da75b6791090a48b | tuoccho/Ph-m-Minh-c_python_C4E27 | /BTVN_Techkid_B3/Bai2.py | 784 | 3.734375 | 4 | ls = [5,7,300,90,24,50,75]
print("Hello, my name is Hiep and these are my sheep size")
print(ls)
for i in range(3):
print("MONTH ",i+1)
ls = [x + 50 for x in ls]
print("One month has passed, now here is my flock")
print(ls)
print("Now my biggest sheep has size",max(ls),"let's shear it")
a = ls.index(max(ls))
ls[a] = 8
print("After Shearing, here is my flock")
print (ls)
print('My flock has size in total: ', sum(ls))
print('I would get', sum(ls), '* 2 = ', sum(ls) * 2)
# print("Now my biggest sheep has size",max(ls),"let's shear it")
# ls.remove(max(ls))
# print("After Shearing, here is my flock")
# print (ls)
# ls = [x + 50 for x in ls]
# print("One month has passed, now here is my flock")
# print(ls)
|
4c4551d47baa1fb50816a8bd0dc21e29fd0b6cee | Timid-sauce/My-SilverBuddy | /SilverBuddy.py | 8,153 | 3.703125 | 4 | '''
SilverBuddy Program
Technica 2017
'''
import os.path
Spending = []
endProgram = 0
print("Welcome to Your Personal SilverBuddy!")
print("To begin you have 3 options: \n")
option = input("Option 1: Take a Quiz to figure out your spending habits \nOption 2: Go to your personal SilverMonitor® \nOption 3: See your past spending days\
\nPress 1 , 2 , or 3 based on the option you select. ")
def SilverMoniter():
Spending = readFile()
for i in range(len(Spending)+1,32):
print("Day", i)
money = input("How much money did you spend today?(In US Dollars) Ex:$0.48 ")
print(money)
if money == 'q':
print("You have chosen to quit the program")
break
Spending.append(money)
writeFile()
def readFile():
if os.path.isfile('SpendingPast.txt'):
my_file = open('SpendingPast.txt','r')
line = my_file.readline()
if line == '':
return []
return line.split(",")
else:
return []
def writeFile():
f = open('SpendingPast.txt','w+')
line = f.write(','.join(Spending))
f.close()
import time
def countdown(n):
print(" \nLoading...")
while n > 0:
time.sleep(1)
n = n - 1
if option == '1':
quiz = str(input("\nAre you sure you want to take the quiz? \n(Enter Yes or No - Capitalization doesn't matter)"))
if quiz.upper() == 'NO':
print(" Ok!")
countdown(3)
print("Menu has loaded SUCCESSFULLY. \n")
print("To begin you have 3 options: \n")
option = input("Option 1: Take a Quiz to figure out your spending habits \
\nOption 2: Go to your personal MoneyMonitor® \nOption 3: See your past spending days\
\nPress 1 , 2 , or 3 based on the option you select. ")
if option == '1':
print("Ok your quiz will begin shortly.")
countdown(3)
print("Your quiz has loaded SUCCESSFULLY.")
school = input("\n What level of schooling are you in? \
\n\t a. High School \
\n\t b. Under Grad \
\n\t c. Post Grad")
form = input("\n What form of money qdo you use most often? \
\n\t a. Debit \
\n\t b. Credit \
\n\t c. Cash")
job = input("\n Do you have a job? (Paid internships included)\
\n\t a. Yes \
\n\t b. No ")
if job.upper() == 'A':
paid = input("\n How much are you paid monthly? \
\n\t a. < 3,000 \
\n\t b. 3,000 - 15,000\
\n\t c. 15,000 - 24,000 \
\n\t d. 24,000 - 36,000 \
\n\t e. > 36,000")
print("All ready to go! Let's begin Tracking!")
previousUse = input("Have you used MySilverBuddy® before? (Please enter Yes or No - Capitalizaton doesn't matter)")
if previousUse.upper() == 'YES':
print("Great! Let's jump right into it!")
SilverMoniter()
elif previousUse.upper() == 'NO':
countdown(3)
print("Your tutorial has loaded SUCCESSFULLY")
input("Your SliverMonitor® will ask you how much money you have spent. (Press ENTER to continue)")
input("Then it will show you how many days you have spent money so you ca manage your money.(Press enter to continue)")
tutorial = input(" Do you understand how to use SilverMonitor® ? (Answer YES or NO - Capitalization does NOT matter)")
if tutorial.upper() == 'YES':
print("Okay! Let's Begin!")
SilverMonitor()
if job.upper() == 'B':
print("All ready to go! Let's begin Tracking!")
previousUse = input("Have you used MySilverBuddy® before? (Please enter Yes or No - Capitalizaton doesn't matter)")
if previousUse.upper() == 'YES':
print("Great! Let's jump right into it!")
SilverMoniter()
elif previousUse.upper() == 'NO':
countdown(3)
print("Your tutorial has loaded SUCCESSFULLY")
input("Your SilverMonitor® will ask you how much money you have spent. (Press ENTER to continue)")
input("Then it will show you how many days you have spent money so you ca manage your money.(Press enter to continue)")
tutorial = input(" Do you understand how to use SilverMonitor® ? (Answer YES or NO - Capitalization does NOT matter)")
if tutorial.upper() == 'YES':
print("Okay! Let's Begin!")
SilverMonitor()
if option == '2':
print ("Silver Moniter")
SilverMoniter()
print (str(Spending))
if option == '3':
print (str(Spending))
elif quiz.upper() == 'YES':
print("Ok your quiz will begin shortly.")
countdown(3)
print("Your quiz has loaded SUCCESSFULLY.")
school = input("\n What level of schooling are you in? \
\n\t a. High School \
\n\t b. Under Grad \
\n\t c. Post Grad")
form = input("\n What form of money do you use most often? \
\n\t a. Debit \
\n\t b. Credit \
\n\t c. Cash")
job = input("\n Do you have a job? (Paid internships included)\
\n\t a. Yes \
\n\t b. No ")
if job.upper() == 'A':
paid = input("\n How much are you paid monthly? \
\n\t a. < 3,000 \
\n\t b. 3,000 - 15,000\
\n\t c. 15,000 - 24,000 \
\n\t d. 24,000 - 36,000 \
\n\t e. > 36,000 \ ")
print("All ready to go! Let's begin Tracking!")
previousUse = input("Have you used MySilverBuddy® before? (Please enter Yes or No - Capitalizaton doesn't matter)")
if previousUse.upper() == 'YES':
print("Great! Let's jump right into it!")
SilverMoniter()
elif previousUse.upper() == 'NO':
countdown(3)
print("Your tutorial has loaded SUCCESSFULLY")
input("Your SliverMonitor® will ask you how much money you have spent. (Press ENTER to continue)")
input("Then it will show you how many days you have spent money so you ca manage your money.(Press enter to continue)")
tutorial = input(" Do you understand how to use SilverMonitor® ? (Answer YES or NO - Capitalization does NOT matter)")
if tutorial.upper() == 'YES':
print("Okay! Let's Begin!")
SilverMoniter()
else:
print("Oh No! Maybe this isn't the right program for you!")
endProgram = 1
if job.upper() == 'B':
print("All ready to go! Let's begin Tracking!")
previousUse = input("Have you used MySilverBuddy® before? (Please enter Yes or No - Capitalizaton doesn't matter)")
if previousUse.upper() == 'YES':
print("Great! Let's jump right into it!")
SilverMoniter()
elif previousUse.upper() == 'NO':
countdown(3)
print("Your tutorial has loaded SUCCESSFULLY")
input("Your SliverMonitor® will ask you how much money you have spent. (Press ENTER to continue)")
input("Then it will show you how many days you have spent money so you ca manage your money.(Press enter to continue)")
tutorial = input(" Do you understand how to use SilverMonitor® ? (Answer YES or NO - Capitalization does NOT matter)")
if tutorial.upper() == 'YES':
print("Okay! Let's Begin!")
SilverMoniter()
else:
print("Oh No! Maybe this isn't the right program for you!")
endProgram = 1
elif option == '2':
print ("Silver Moniter")
SilverMoniter()
elif option == '3':
print (str(Spending))
else:
print("You have entered an invalid response.")
|
3eb8aabe87d5fffa9bf91e4bb22f6d0222c82aaa | rafaelperazzo/programacao-web | /moodledata/vpl_data/94/usersdata/188/55295/submittedfiles/mediaLista.py | 86 | 3.578125 | 4 | # -*- coding: utf-8 -*-
n=float(input('Digite a quantidade de elementos da lista'))
|
c79236734e2701fca41e5777bf1a3c1fb4857e21 | melody40/monorepo | /Pyhton/learnPythonTheHardWay/ZedAShaw/src/ex7.py | 166 | 3.59375 | 4 | print ("Mary had a little %s" % 'lamb')
end1 = 'T'
end2 = 'o'
end3 = 'r'
end4 = 's'
end5 = 'h'
end6 = 'o'
print ( end1 + end2 + end3 + end4 + end5 + end6 ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.