blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
6b4e1d7e026e8092f09ecbc6f8984ae4c8ef9807 | okipriyadi/NewSamplePython | /SamplePython/samplePython/Process_and_Thread/signal/_03_Alarm.py | 735 | 3.5625 | 4 | """
Alarms are a special sort of signal, where the program asks the OS to notify it after some
period of time has elapsed. As the standard module documentation for os points out, this
is useful for avoiding blocking indefinitely on an I/O operation or other system call.
In this example, the call to sleep() does not last the full four seconds.
"""
import signal
import time
def receive_alarm(signum, stack):
print 'Alarm :', time.ctime()
# Call receive_alarm in 2 seconds
signal.signal(signal.SIGALRM, receive_alarm)
signal.alarm(4)
print 'Before:', time.ctime()
time.sleep(7)
print 'After :', time.ctime()
"""
fungsi receive alarm akan dipanggil ketika waktu tunggunya dalam contoh ini 4 detik dan tidak melewati waktu sleep |
5d53da37eaeb7ab546a1a289e5c95c6641debe23 | okipriyadi/NewSamplePython | /SamplePython/samplePython/Process_and_Thread/Threading/_03_determining_current_thread.py | 824 | 4.09375 | 4 | """
Using arguments to identify or name the thread is cumbersome and unnecessary. Each
Thread instance has a name with a default value that can be changed as the thread
is created. Naming threads is useful in server processes made up of multiple service
threads handling different operations.
"""
import threading
import time
def worker():
print threading.currentThread().getName(), 'Starting'
time.sleep(2)
print threading.currentThread().getName(), 'Exiting'
def my_service():
print threading.currentThread().getName(), 'Starting'
time.sleep(3)
print threading.currentThread().getName(), 'Exiting'
t = threading.Thread(name='my_service', target=my_service)
w = threading.Thread(name='worker', target=worker)
w2 = threading.Thread(target=worker) # use default name
w.start()
w2.start()
t.start() |
54601bfc436361968a04d4d8dcc9715e1901a914 | okipriyadi/NewSamplePython | /SamplePython/samplePython/Process_and_Thread/signal/_01_a_receiving_signal.py | 1,210 | 3.78125 | 4 | """
As with other forms of event-based programming, signals are received by establishing
a callback function, called a signal handler, that is invoked when the signal occurs.
The arguments to the signal handler are the signal number and the stack frame from the
point in the program that was interrupted by the signal.
This example script loops indefinitely, pausing for a few seconds each time.
When a signal comes in, the sleep() call is interrupted and the signal handler
receive_signal() prints the signal number. After the signal handler returns, the
loop continues.
Send signals to the running program using os.kill() or the UNIX command line program kill.
$ kill -USR1 $pid
$ kill -USR2 $pid
$ kill -INT $pid contoh jika program ini berjalan di PID 5361 maka untuk mematikannya dengan cara
kill -INT 5361
"""
import signal
import os
import time
def receive_signal(signum, stack):
print 'Received:', signum
# Register signal handlers
signal.signal(signal.SIGUSR1, receive_signal)
signal.signal(signal.SIGUSR2, receive_signal)
# Print the process ID so it can be used with 'kill'
# to send this program signals.
print 'My PID is:', os.getpid()
while True:
print 'Waiting...'
time.sleep(3) |
36f470094e74fdf5bf80792de7a3b24a4b443b54 | okipriyadi/NewSamplePython | /SamplePython/samplePython/internet/urllib/_02_ENCODE_argument.py | 344 | 3.5 | 4 | """
Arguments can be passed to the server by encoding them and appending them to the
URL.
"""
import urllib
query_args = { 'q':'query string', 'foo':'bar' }
encoded_args = urllib.urlencode(query_args)
print 'Encoded:', encoded_args
url = 'http://localhost:8080/?' + encoded_args
print 'url =',url
print 'urlopen = ', urllib.urlopen(url).read() |
28d62ead494a5f35e18d87e05fb6b7b9f47d57ea | okipriyadi/NewSamplePython | /SamplePython/Framework/Django/_06_apllication_extending.py | 7,081 | 3.796875 | 4 | """
Extend your application
We've already completed all the different steps necessary for the creation of our website:
we know how to write a model, url, view and template. We also know how to make our
website pretty.
Time to practice!
The first thing we need in our blog is, obviously, a page to display one post, right?
We already have a Post model, so we don't need to add anything to models.py.
Create a template link to a post's detail
We will start with adding a link inside blog/templates/blog/post_list.html file.
So far it should look like:
{% extends 'blog/base.html' %}
{% block content %}
{% for post in posts %}
<div class="post">
<div class="date">
{{ post.published_date }}
</div>
<h1><a href="">{{ post.title }}</a></h1>
<p>{{ post.text|linebreaks }}</p>
</div>
{% endfor %}
{% endblock content %}
We want to have a link from a post's title in the post list to the post's detail page.
Let's change <h1><a href="">{{ post.title }}</a></h1> so that it links to the post's
detail page:
<h1><a href="{% url 'post_detail' pk=post.pk %}">{{ post.title }}</a></h1>
Time to explain the mysterious {% url 'post_detail' pk=post.pk %}. As you might suspect,
the {% %} notation means that we are using Django template tags. This time we will use one
that will create a URL for us!
blog.views.post_detail is a path to a post_detail view we want to create. Please note:
blog is the name of our application (the directory blog), views is from the name of the
views.py file and the last bit - post_detail - is the name of the view.
Now when we go to: http://127.0.0.1:8000/ we will have an error (as expected,
since we don't have a URL or a view for post_detail). It will look like this:
NoReverseMatch error
Create a URL to a post's detail
Let's create a URL in urls.py for our post_detail view!
We want our first post's detail to be displayed at this URL: http://127.0.0.1:8000/post/1/
Let's make a URL in the blog/urls.py file to point Django to a view named post_detail, that will show an entire blog post. Add the line url(r'^post/(?P<pk>[0-9]+)/$', views.post_detail, name='post_detail'), to the blog/urls.py file. The file should look like this:
from django.conf.urls import include, url
from . import views
urlpatterns = [
url(r'^$', views.post_list, name='post_list'),
url(r'^post/(?P<pk>[0-9]+)/$', views.post_detail, name='post_detail'),
]
This part ^post/(?P<pk>[0-9]+)/$ looks scary, but no worries - we will explain it for you:
it starts with ^ again -- "the beginning"
post/ only means that after the beginning, the URL should contain the word post and /.
So far so good.
(?P<pk>[0-9]+) - this part is trickier. It means that Django will take everything that
you place here and transfer it to a view as a variable called pk. [0-9]
also tells us that it can only be a number, not a letter (so everything between 0 and 9).
+ means that there needs to be one or more digits there. So something like
http://127.0.0.1:8000/post// is not valid,
but http://127.0.0.1:8000/post/1234567890/ is perfectly ok!
/ - then we need / again
$ - "the end"!
That means if you enter http://127.0.0.1:8000/post/5/ into your browser,
Django will understand that you are looking for a view called post_detail and
transfer the information that pk equals 5 to that view.
pk is shortcut for primary key. This name is often used in Django projects.
But you can name your variable as you like (remember: lowercase and _ instead of
whitespaces!). For example instead of (?P<pk>[0-9]+) we could have variable post_id,
so this bit would look like: (?P<post_id>[0-9]+).
Ok, we've added a new URL pattern to blog/urls.py! Let's refresh the page:
http://127.0.0.1:8000/ Boom! Yet another error! As expected!
AttributeError
Do you remember what the next step is? Of course: adding a view!
Add a post's detail view
This time our view is given an extra parameter pk.
Our view needs to catch it, right? So we will define our function as
def post_detail(request, pk):. Note that we need to use exactly the same name as
the one we specified in urls (pk). Omitting this variable is incorrect and
will result in an error!
Now, we want to get one and only one blog post. To do this we can use querysets
like this:
Post.objects.get(pk=pk)
But this code has a problem. If there is no Post with given primary key (pk) we will
have a super ugly error!
DoesNotExist error
We don't want that! But, of course, Django comes with something that will handle that
for us: get_object_or_404. In case there is no Post with the given pk it will display
much nicer page (called Page Not Found 404 page).
Page not found
The good news is that you can actually create your own Page not found page
and make it as pretty as you want. But it's not super important right now, so we will skip it.
Ok, time to add a view to our views.py file!
We should open blog/views.py and add the following code:
from django.shortcuts import render, get_object_or_404
Near other from lines. And at the end of the file we will add our view:
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
return render(request, 'blog/post_detail.html', {'post': post})
Yes. It is time to refresh the page: http://127.0.0.1:8000/
Post list view
It worked! But what happens when you click a link in blog post title?
TemplateDoesNotExist error
Oh no! Another error! But we already know how to deal with it, right?
We need to add a template!
Create a template for post detail
We will create a file in blog/templates/blog called post_detail.html.
It will look like this:
{% extends 'blog/base.html' %}
{% block content %}
<div class="post">
{% if post.published_date %}
<div class="date">
{{ post.published_date }}
</div>
{% endif %}
<h1>{{ post.title }}</h1>
<p>{{ post.text|linebreaks }}</p>
</div>
{% endblock %}
Once again we are extending base.html. In the content block we want to display a post's published_date
(if it exists), title and text. But we should discuss some important things, right?
{% if ... %} ... {% endif %} is a template tag we can use when we want to check
something (remember if ... else .. from Introduction to Python chapter?). In this
scenario we want to check if a post's published_date is not empty.
Ok, we can refresh our page and see if TemplateDoesNotExist is gone now.
Post detail page
Yay! It works!
One more thing: deploy time!
It'd be good to see if your website will still be working on PythonAnywhere, right? Let's try deploying again.
$ git status
$ git add -A .
$ git status
$ git commit -m "Added view and template for detailed blog post as well as CSS for the site."
$ git push
Then, in a PythonAnywhere Bash console:
$ cd my-first-blog
$ source myvenv/bin/activate
(myvenv)$ git pull
[...]
(myvenv)$ python manage.py collectstatic
[...]
Finally, hop on over to the Web tab and hit Reload.
And that should be it! Congrats :)
""" |
8d0e4e75cfb540e40ea4b72134aa35ae51743daa | okipriyadi/NewSamplePython | /SamplePython/dari_buku_network_programming/Bab1_socket_and_simple_server_client.py/_13_echo_server.py | 1,508 | 4.0625 | 4 | """
First, we create the server. We start by creating a TCP socket object. Then, we set the reuse
address so that we can run the server as many times as we need. We bind the socket to the
given port on our local machine. In the listening stage, we make sure we listen to multiple
clients in a queue using the backlog argument to the listen() method. Finally, we wait for
the client to be connected and send some data to the server. When the data is received, the
server echoes back the data to the client
"""
import socket
PORT = 10001
HOST = 'localhost'
backlog = 5
data_payload = 2048
def echo_server():
# Create a TCP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Enable reuse address/port
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
#bind the socket to the port
print "Starting up echo server on %s port %s" % (HOST, PORT)
sock.bind((HOST, PORT))
# Listen to clients, backlog argument specifies the max no. of queued connections
sock.listen(backlog)
while True:
print "Waiting to receive message from client"
client, address = sock.accept()
print "mendapat koneksi dari client = %s, address=%s"%(client, address)
data = client.recv(data_payload)
if data:
print "Data: %s" %data
client.send(data)
print "sent %s bytes back to %s" % (data, address)
# end connection
client.close()
if __name__ == "__main__":
echo_server() |
757f1fe7ac984a14ad45198c98c5413485a390e2 | okipriyadi/NewSamplePython | /SamplePython/samplePython/Assignment5PM/Sudah Beres/bukuTeleponDatabase/engine/model/PhonebookModel.py | 1,956 | 3.78125 | 4 | import sqlite3
class PhonebookModel:
def __init__(self):
self.con = sqlite3.connect('files/test.db')
self.cur = self.con.cursor()
def createTable(self):
self.cur.execute('''CREATE TABLE person
(id_person INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT , address TEXT)''')
self.cur.execute('''CREATE TABLE phonebook
(id_phonebook INTEGER PRIMARY KEY AUTOINCREMENT, id_person INTEGER , no_telp TEXT, FOREIGN KEY (id_person) REFERENCES person(id_person))''')
self.cur.execute('''CREATE TABLE relation
(id_relation INTEGER PRIMARY KEY ,id_person1 INTEGER, id_person2 INTEGER, relation TEXT)''')
self.con.commit()
def addPhonebook(self, name, address, listNumber):
#self.createTable()
self.cur.execute('''INSERT INTO person(name, address)
VALUES(?,?)''',(name, address))
self.con.commit()
query = "select id_person from person where name ='" +name+"' AND address='"+address+"'"
self.cur.execute(query)
id_person = self.cur
id_person2 = 0
for i in id_person:
for j in i:
id_person2 = j
for noTelp in listNumber:
self.cur.execute('''INSERT INTO phonebook(id_person, no_telp)
VALUES(?,?)''',(id_person2, noTelp))
self.con.commit()
def addRelationship(self, id1, id2, relation):
self.cur.execute('''INSERT INTO relation(id_person1, idperson2, relation)
VALUES(?,?,?)''',(id1, id2, relation))
self.con.commit()
def search(self, keyword):
self.cur.execute(keyword)
return self.cur
#createTable()
#addPhonebook('OKi', 'cipedes',["085220902022"])
#cur.execute('SELECT * FROM phonebook')
#for i in cur:
#print "\n"
#for j in i:
#print j
#data = cur.fetchone()
#print "SQLite version: %s" % data |
36360988ad89205311f6f8ff806f345bbf5bf5ba | okipriyadi/NewSamplePython | /SamplePython/dari_buku_network_programming/Bab1_socket_and_simple_server_client.py/_06_socket_timeout.py | 809 | 3.828125 | 4 | """
Sometimes, you need to manipulate the default values of certain properties of a socket
library, for example, the socket timeout.
You can make an instance of a socket object and call a gettimeout() method to get the
default timeout value and the settimeout() method to set a specific timeout value. This is
very useful in developing custom server applications.
We first create a socket object inside a test_socket_timeout() function. Then, we can
use the getter/setter instance methods to manipulate timeout values.
"""
import socket
def test_socket_timeout():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print "Default socket timeout: %s" %s.gettimeout()
s.settimeout(10)
print "Current socket timeout: %s" %s.gettimeout()
if __name__ == '__main__':
test_socket_timeout() |
f08bd170328ec6dc4ca3c8da2f3d8e2af7af5891 | okipriyadi/NewSamplePython | /SamplePython/build_in_modul/_01_zip.py | 358 | 4.125 | 4 | """
built-in zip berfungsi untuk iterasi yang menghasilkan satu-ke satu. return nya berupa tuple.
contoh zip([1, 2, 3, 4], ['a', 'b', 'c', 'f']) menghasikan
"""
a = zip([1, 2, 3, 4], ['a', 'b', 'c', 'f'])
for i in a :
print i
print "a = " , a
b = zip([1, 2], ['a', 'b', 'c', 'f'])
print "b =",b
c = zip([1, 2, 3, 4], ['a', 'b', 'c'])
print "c =", c |
d34b149c0cb8bf87bd81b880f35f507d3b20fbd4 | okipriyadi/NewSamplePython | /SamplePython/samplePython/internet/CGI/01_test_web_server_works_or_not_with_CGI.py | 2,560 | 3.53125 | 4 | """
The Python standard library includes some modules that are helpful for creating plain
CGI programs:
1. cgi : Handling of user input in CGI scripts
2. cgitb : Displays nice tracebacks when errors happen in CGI applications,
instead of presenting a "500 Internal Server Error" message
The Python wiki features a page on CGI scripts with some additional information about
CGI in Python.
Depending on your web server configuration, you may need to save this code with
a .py or .cgi extension. Additionally, this file may also need to be in a cgi-bin folder,
for security reasons.
You might wonder what the cgitb line is about. This line makes it possible to display
a nice traceback instead of just crashing and displaying an "Internal Server Error"
in the user's browser. This is useful for debugging, but it might risk exposing some
confidential data to the user. You should not use cgitb in production code for this reason.
You should always catch exceptions, and display proper error pages
end-users don't like to see nondescript "Internal Server Errors" in their browsers.
"""
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# enable debugging
import cgitb
cgitb.enable()
print "Content-Type: text/plain;charset=utf-8"
print "Hello World!"
"""
If you don't have your own web server, this does not apply to you.
You can check whether it works as-is, and if not you will need to talk to the
administrator of your web server. If it is a big host, you can try filing a ticket
asking for Python support.
If you are your own administrator or want to set up CGI for testing purposes on your
own computers, you have to configure it by yourself. There is no single way to configure CGI,
as there are many web servers with different configuration options. Currently the most
widely used free web server is Apache HTTPd, or Apache for short. Apache can be easily
installed on nearly every system using the system's package management tool.
lighttpd is another alternative and is said to have better performance.
On many systems this server can also be installed using the package management tool,
so manually compiling the web server may not be needed.
On Apache you can take a look at the Dynamic Content with CGI tutorial,
where everything is described. Most of the time it is enough just to set +ExecCGI.
The tutorial also describes the most common gotchas that might arise.
On lighttpd you need to use the CGI module, which can be configured in a
straightforward way. It boils down to setting cgi.assign properly.
"""
|
a3330d6f9075ac7c7524bcb8d859092454967559 | okipriyadi/NewSamplePython | /SamplePython/Basic Source /Dasar/struct/01_awal_pack_and_unpack.py | 1,173 | 3.890625 | 4 | """
The struct module includes functions for converting between strings of bytes and native Python data types
such as numbers and strings.
Structs support packing data into strings, and unpacking data from strings using format specifiers
made up of characters representing the type of the data and optional count and endian-ness indicators.
For complete details, refer to the standard library documentation.
In this example, the format specifier calls for an integer or long value, a two character string,
and a floating point number. The spaces between the format specifiers are included here for clarity,
and are ignored when the format is compiled.
"""
import struct
import binascii
#PACKING
values = (1, 'ab', 2.7)
s = struct.Struct('I 2s f')
packed_data = s.pack(*values)
print 'Original values:', values
print 'Format string :', s.format
print 'Uses :', s.size, 'bytes'
print 'Packed Value :', binascii.hexlify(packed_data)
print 'Packed Data :', packed_data
#kebalikan hexlify
print 'Packed Value :', binascii.unhexlify('0100000061620000cdcc2c40')
#UNPACKING
unpacked_data = s.unpack(packed_data)
print 'Unpacked Values:', unpacked_data |
583f24e601964798dc24de7ae7bc1845d991f6e1 | kishen19/HSS-Course-Allotment | /generate_codes/code_generation.py | 1,720 | 3.875 | 4 | '''
Generating Unique Codes for students. These codes are used for authentication when collecting student preferences.
Codes are sent to students by email. Students are required to enter this unique code when submitting the form.
Each unique code contains 8 characters, alphanumeric. 'Case Sensitive'.
'''
from random import sample
import pandas as pd
import yaml
###################################################################################################
# reading config file for fetching paths
paths = open("../config.yaml", 'r')
paths_dictionary = yaml.load(paths)
# path to the file containing the unique codes shared to the students for authentication
# Input and Output Path
# CHANGE THESE AS PER REQUIREMENT #
STUDENT_LIST = paths_dictionary["STUDENT_LIST"] #Input file path (Excel file containing students information)
STUDENT_UNIQUE_CODES = paths_dictionary["STUDENT_UNIQUE_CODES"]
CODE_LENGTH = 8 #Length of unique codes
# Note: You can change the output format if you like
# Allowed characters - Lower and Upper case letters [a-z,A-Z] and Numbers [0-9]
small_alphs = [chr(ord('a')+i) for i in range(26)]
big_alphs = [chr(ord('A')+i) for i in range(26)]
nums = [str(i) for i in range(10)]
options = small_alphs+big_alphs+nums
# Reading Input
df = pd.read_excel(STUDENT_LIST)
num_studs = df.shape[0] # Num of students
# Generating codes
codes = set()
for i in range(num_studs):
code = ""
while True:
for j in range(CODE_LENGTH):
w = sample(options,1)[0]
code+=w
if code not in codes:
codes.add(code)
break
code = ""
codes = list(codes)
# Writing Output
df["Unique Code"] = codes
df.to_excel(STUDENT_UNIQUE_CODES) |
a6ac166cbc0c8ee75d09c906e4376c05f5a40169 | jeffsmohan/words | /scripts/wordcounts_clean.py | 1,361 | 4.03125 | 4 | """Tool to clean wordcounts files by removing the count."""
import argparse
def clean_word_counts(args):
"""Remove count from wordcounts file."""
with open(args.valid_words) as f:
valid_words = set(word.strip() for word in f)
with open(args.word_counts) as i, open(args.output, "w") as o:
o.writelines(
line.split()[1] + "\n" for line in i if line.split()[0] in valid_words
)
if __name__ == "__main__":
# Pull arguments from the command line
parser = argparse.ArgumentParser(description="Intersect two datasets of words.")
parser.add_argument(
"--word-counts", "-w", required=True, help="Input word counts",
)
parser.add_argument(
"--valid-words", "-v", required=True, help="Valid word list",
)
parser.add_argument(
"--output",
"-o",
default="intersection.txt",
help="Output file to write intersected word list to",
)
args = parser.parse_args()
# Process the input word lists, and write the intersected output
print("Processing input datasets...")
clean_word_counts(args)
# word_lists = read_word_lists(args.input, args.ignore)
# intersection = intersect_word_lists(word_lists)
# write_intersection(intersection, args.output)
print(f"Success! Your intersected word list is at `{args.output}`.")
|
cbe557cecd80fbd899d131c5fdd126550afaf88a | paulwuertz/CodeEval | /Easy/AgeDistribution.py | 830 | 3.796875 | 4 | import math
import sys
test_cases = open(sys.argv[1], 'r')
for test in test_cases:
if(int(test)<0):
print("This program is for humans")
elif(int(test)<3 and int(test)>-1):
print("Still in Mama's arms")
elif(int(test)<5 and int(test)>2):
print("Preschool Maniac")
elif(int(test)<12 and int(test)>4):
print("Elementary school")
elif(int(test)<15 and int(test)>11):
print("Middle school")
elif(int(test)<19 and int(test)>14):
print("High school")
elif(int(test)<23 and int(test)>18):
print("College")
elif(int(test)<66 and int(test)>22):
print("Working for the man")
elif(int(test)<101 and int(test)>65):
print("The Golden Years")
elif(int(test)>100):
print("This program is for humans")
test_cases.close()
|
57864bba5ca80ebbc1d1035b28a22a9b56cec39a | paulwuertz/CodeEval | /Easy/SumOfPrimes.py | 271 | 3.546875 | 4 | import math
def isPrim(zahl):
for i in range(3,(int)(zahl/2),2):
if(zahl%i==0):
return 0
return 1
primAnz=1
primSum=2
zahl=3
while primAnz<1000:
if(isPrim(zahl)==1):
primAnz+=1
primSum+=zahl
zahl+=2
print(primSum)
|
1edcf09a11ad03b85559e095fe1dcae4dfce6d3c | akshayjain3450/HackerRank30DaysChallenge | /loopreview.py | 302 | 3.5625 | 4 | T = int(input())
if T < 1 and T > 10:
exit()
else:
for i in range(T):
S = input()
odd = ''
even = ''
for j in range(len(S)):
if j % 2 == 0:
odd = odd + S[j]
else:
even = even + S[j]
print(odd,even)
|
78b23e0df36a221a1bf75c1947cabca32551a428 | rnlclngpilar/CBIRusingBarcode | /Feb28_GoogleDrive_Update/RBC_all.py | 1,638 | 3.625 | 4 | from mnist import MNIST
mndata = MNIST('.')
images, label = mndata.load_training()
# images, labels = mndata.load_testing()
print("Read all Images")
# index = random.randrange(0,len(images)) # choose a random index
#https://stackoverflow.com/questions/11926620/declaring-a-python-function-with-an-array-parameters-and-passing-an-array-argume
def makeBarcodes(images,label):
import matlab.engine
eng = matlab.engine.start_matlab()
import numpy as np
# Input for extractRBC
# IMG - passed through images array
nrows = 28
ncols = nrows
numRays = 8
showRBC = 0 #false
for index in range(len(label)):
# https://stackoverflow.com/questions/40481623/if-statement-with-modulo-operator
if not index%1000: # i.e. to show progress - when remainder divided by 1000 is 0
print(index,'->',label[index])
image = images[index]
IMG = matlab.double(image) # casting image
IMG.reshape((nrows,ncols)) # create 2D array from 1D array
bar = eng.extractRBC(IMG,nrows,ncols,numRays,showRBC) #sending input to the function
#https://stackoverflow.com/questions/30013853/convert-matlab-double-array-to-python-array
barcodes.append(bar._data.tolist())
eng.quit() #Stop the matlab engine
return barcodes
barcodes = [] # Create an empty python list
barcodes = makeBarcodes(images,label)
print("Output Barcodes")
import numpy as np
#https://thispointer.com/how-to-save-numpy-array-to-a-csv-file-using-numpy-savetxt-in-python/
np.savetxt('barcode_array.csv', barcodes, delimiter=',', fmt='%d')
np.savetxt('barcode_label.csv', label , delimiter=',', fmt='%d')
|
7cce2411a94de777d3a73993399cb9fadb574369 | anmolparida/selenium_python | /CorePython/DataTypes/Numbers/BitwiseOperators.py | 304 | 3.578125 | 4 | """
Bitwise operators act on operands as if they were strings of binary digits. They operate bit by bit, hence the name.
For example, 2 is 10 in binary and 7 is 111.
"""
x = 10 # 0000 1010
y = 4 # 0000 0100
print(x & y) # 0000 0010 - 0
print(x | y) # 0000 1010 - 14
print(-x) # 1111 0101 -
|
cf4bf216fd03c9acaff05038fe3f204902ddd216 | anmolparida/selenium_python | /CorePython/FlowControl/Pattern_Stars.py | 758 | 4.125 | 4 | """
Write a Python program to construct the following pattern, using a nested for loop.
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
"""
def pattern_star_right_arrow_method1(n):
print('pattern_star_right_arrow_method1')
for i in range(n + 1):
print("* " * i)
for j in range(n - 1, 0, -1):
print("* " * j)
pattern_star_right_arrow_method1(5)
def pattern_star_right_arrow_method2(n):
print('pattern_star_right_arrow_method2')
for i in range(n):
for j in range(i):
print('* ', end=' ')
print('')
for i in range(n, 0, -1):
for j in range(i):
print('* ', end=' ')
print('')
pattern_star_right_arrow_method2(5)
|
5512e04c4832ad7b74e6a0ae7d3151643747dd8c | anmolparida/selenium_python | /CorePython/DataTypes/Dictionary/DictionaryMethods.py | 1,181 | 4.28125 | 4 | d = {'A': 1, 'B' : 2}
print(d)
print(d.items())
print(d.keys())
print(d.values())
print(d.get('A'))
print(d['A'])
# empty dictionary
my_dict = {}
# dictionary with integer keys
my_dict = {1: 'apple', 2: 'ball'}
print(my_dict)
# dictionary with mixed keys
my_dict = {'name': 'John', 1: [2, 4, 3]}
print(my_dict)
# using dict()
my_dict = dict({1:'apple', 2:'ball'})
print(my_dict)
# from sequence having each item as a pair
my_dict = dict([(1,'apple'), (2,'ball')])
print(my_dict)
"""
Removing elements from Dictionary
"""
print('\nRemoving elements from Dictionary')
# create a dictionary
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# remove a particular item, returns its value
# Output: 16
print(squares.pop(4))
# Output: {1: 1, 2: 4, 3: 9, 5: 25}
print(squares)
squares[4] = 16
print(squares)
# removes last item, return (key,value)
# Output: (5, 25)
print(squares.popitem())
print(squares)
# remove all items
squares.clear()
# Output: {}
print(squares)
# delete the dictionary itself
del squares
# print(squares) # Throws Error
"""
setdefault
"""
person = {'name': 'Phill', 'age': 22}
age = person.setdefault('age')
print('person = ',person)
print('Age = ',age) |
39d0acbcb42f0e6e26264e867d4bbdea341be8a4 | anmolparida/selenium_python | /CorePython/DataTypes/List/Set.py | 3,256 | 4.65625 | 5 | """
Strings are immutable.
Forzensets are immutable version of the set
This means that elements of a string cannot be changed once they have been assigned.
We can simply reassign different strings to the same name.
"""
my_string = 'programiz'
# my_string[5] = 'a' # TypeError: 'str' object does not support item assignment - not mutable
# del my_string[1] # TypeError: 'str' object doesn't support item deletion
"""
enumerate
The enumerate() function returns an enumerate object.
It contains the index and value of all the items in the string as pairs. This can be useful for iteration.
"""
s = 'PYTHON'
list_enumerate = list(enumerate(s))
print('list_enumerate', list_enumerate)
print(list_enumerate[0][1])
# set cannot have duplicates
# Output: {1, 2, 3, 4}
my_set = {1, 2, 3, 4, 3, 2}
print(my_set)
# we can make set from a list
# Output: {1, 2, 3}
my_set = set([1, 2, 3, 2])
print(my_set)
# set cannot have mutable items
# here [3, 4] is a mutable list
# this will cause an error.
# my_set = {1, 2, [3, 4]}
"""
Set can have any number of items and they may be of different types (integer, float, tuple, string etc.).
But a set cannot have mutable elements like lists, sets or dictionaries as its elements.
"""
# Distinguish set and dictionary while creating empty set
# initialize a with {}
a = {}
# check data type of a
print(type(a))
# initialize a with set()
a = set()
# check data type of a
print(type(a))
# initialize my_set
my_set = {1, 3}
print(my_set)
# my_set[0] # TypeError: 'set' object does not support indexing
# add an element
# Output: {1, 2, 3}
my_set.add(2)
print(my_set)
# add multiple elements
# Output: {1, 2, 3, 4}
my_set.update([2, 3, 4])
print(my_set)
# add list and set
# Output: {1, 2, 3, 4, 5, 6, 8}
my_set.update([4, 5], {1, 6, 8})
print(my_set)
"""
Difference between discard() and remove()
my_set.remove(2) - remove throws key error if element is not present in set
my_set.discard(2) - discard does not throw error if element is not present in th set
"""
print('\n Difference between discard() and remove()')
# initialize my_set
my_set = {1, 3, 4, 5, 6}
print(my_set)
# discard an element
# Output: {1, 3, 5, 6}
my_set.discard(4)
print(my_set)
# remove an element
# Output: {1, 3, 5}
my_set.remove(6)
print(my_set)
# discard an element
# not present in my_set
# Output: {1, 3, 5}
my_set.discard(2)
print(my_set)
# remove an element
# not present in my_set
# you will get an error.
# Output: KeyError
# my_set.remove(2)
# initialize my_set - Output: set of unique elements
my_set = set("HelloWorld")
print(my_set)
# pop an element - Output: random element unlike last element in list
print(my_set.pop())
# pop another element
print(my_set.pop())
# clear my_set - Output: set()
my_set.clear()
print(my_set)
"""
SET Properties
"""
print('\nSET Properties')
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print(A.union(B))
print(A.intersection(B))
print(A & B)
# Values only present in A
print(A.difference(B))
print(A-B)
# Values only present in B
print(B.difference(A))
print(B-A)
# All elements in A.union(B) excluding A.intersection(B)
print(A.symmetric_difference(B))
print(B.symmetric_difference(A))
# symmetric_difference simplified
print(A.union(B) - A.intersection(B))
|
0ac431eb794358e899b968ff554df3060e54075d | anmolparida/selenium_python | /CorePython/FlowControl/DataTypes.py | 555 | 4.09375 | 4 | singleLine = "Single line string"
multiLine = """ Multi line
string"""
print(singleLine)
print(multiLine)
print(float(5))
print(int(5.0))
print(float(0))
print(int(0.0))
print(float(-5))
print(int(-5.0))
print("#"*50)
print(1, 2, 3, 4)
print(1, 2, 3, 4, sep='*')
print(1, 2, 3, 4, sep='#', end='\n')
# print(input('Enter Name: '))
# evaluates the string inside eval()
print(int(eval('111*11')))
import math
print(math.pi)
print('*#' * 10)
x = True
y = False
print('x and y is',x and y)
print('x or y is',x or y)
print('not x is',not x) |
8b97530008656847d3e8218d6e7d292aed34ede1 | anmolparida/selenium_python | /CorePython/DataTypes/Numbers/Decimal.py | 731 | 3.859375 | 4 | """
Adding float in python PROBLEM
It turns out that the decimal fraction 0.1 will result in long binary fraction 0.1000000000000000055511151231257827021181583404541015625
and our computer only stores a finite number of it.
******* When to use Decimal instead of float? *******
# When we are making financial applications that need exact decimal representation.
# When we want to implement the notion of significant decimal places.
# When we want to control the level of precision required.
"""
print(1.1 + 2.2 == 3.3) # False
print(1.1 + 2.2) # 3.3000000000000003
from decimal import Decimal as D
print(D(0.1)) # 0.1000000000000000055511151231257827021181583404541015625
print(D('1.1') + D('2.2'))
print(D('1.2') * D('2.5'))
|
6e5ea5a76c0af38d4fefd42eaff48f9d13512ec1 | anmolparida/selenium_python | /Tutorials/Udemy/FindElement_Xpath_CSS.py.py | 3,096 | 3.578125 | 4 | # driver.find_element_by_id()
# driver.find_element_by_name()
# driver.find_element_by_xpath()
# driver.find_element_by_link_text()
# driver.find_element_by_partial_link_text()
# driver.find_element_by_tag_name()
# driver.find_element_by_class_name()
# driver.find_element_by_css_selector()
# drive.find_element(By.XPATH. "xpath expression")
import os
import time
from selenium import webdriver
class FindElementBy:
def testFindElement(self):
driverLocation_windows = "C:\\Users\\aparida\\OneDrive\\Code\\Selenium\\chromedriver.exe"
driverLocation_mac = "anmolparida\OneDrive\Code\Selenium_Python\chromedriver.exe"
# Update based on the System you are using
driverLocation = driverLocation_windows
# Important Steps
os.environ["webdriver.chrome.driver"] = driverLocation
driver = webdriver.Chrome(driverLocation);
baseURL = "https://letskodeit.teachable.com/p/practice"
driver.get(baseURL)
driver.maximize_window()
elementByXpath = driver.find_element_by_xpath("//input[@id='name']")
if elementByXpath is not None:
print('elementByXpath - We have a match')
else:
print('elementByXpath - We Dont have a match')
elementByCSS = driver.find_element_by_css_selector(".btn-style.class1.class2")
if elementByXpath is not None:
print('elementByCSS - We have a match')
else:
print('elementByCSS - We Dont have a match')
# using contains
# //tag[contains(attribute,'value')]
# //tag[starts-with(attribute,'value')]
# //tag[ends-with(attribute,'value')]
elementByXpath = driver.find_element_by_xpath("//div[@class='homepage-hero']//a[text()='Enroll now']")
elementByXpath = driver.find_element_by_xpath("//div[@id='navbar']//a[contains(text(),'Login')]")
elementByXpath = driver.find_element_by_xpath("//div[@id='navbar']//a[contains(@class,'navbar-link fedora') and contains(@href,'sign_in')]")
# Syntax: xpath - to - some - element // parent:: < tag >
# Syntax: xpath - to - some - element // preceding - sibling:: < tag >
# Syntax: xpath - to - some - element // following - sibling:: < tag >
elementByXpath = driver.find_element_by_xpath("//a[@href='/sign_in']//parent::li")
elementByXpath = driver.find_element_by_xpath("//a[@href='/sign_in']//parent::li//following-sibling::li")
elementByXpath = driver.find_element_by_xpath("//a[@href='/sign_in']//parent::li//preceding-sibling::li")
elementByXpath = driver.find_element_by_xpath("//a[@href='/sign_in']//parent::li//preceding-sibling::li//following-sibling::li[2]")
if elementByXpath is not None:
print('elementByXpath - We have a match')
else:
print('elementByXpath - We Dont have a match')
time.sleep(2);
driver.quit();
oFindElement = FindElementBy()
oFindElement.testFindElement()
|
6a655da9e2fefbfaa7a77ce652b6af6755ae1e95 | surenthiran123/sp.py | /number.py | 330 | 4.21875 | 4 | n1=input();
n2=input();
n3=input();
Largest = n1
if Largest < n2:
if n2 > n3:
print(n2,"is Largest")
else:
print(n3,"is Largest")
elif Largest < n3:
if n3 > n2:
print(n3,"is Largest")
else:
print(n2,"is Largest")
else:
print(n1,"is Largest")
|
e29e3741598e0c459a2bd22292f9349f7cfe4fb4 | jonbinney/python-planning | /python_task_planning/src/python_task_planning/common.py | 7,885 | 3.609375 | 4 | class Symbol:
def __init__(self, val=None):
self.val = val
def __hash__(self):
return hash(id(self))
def __eq__(self, other):
return (self is other)
def __repr__(self):
return 'symbol%d' % id(self)
class Variable:
def __init__(self, name):
self.name = name
def __hash__(self):
return hash(id(self))
def __eq__(self, other):
return (self is other)
def __repr__(self):
return str(self.name)
class Fluent:
def __init__(self, pred, args):
self.pred = pred
self.args = tuple(args)
def __hash__(self):
'''Hash depends only on the fluent class and args.
'''
return hash((self.pred, self.args))
def __eq__(self, other):
'''Equality depends only on fluent class and args.
'''
return (self.pred, self.args) == (other.pred, other.args)
def __repr__(self):
return '%s(%s)' % (self.pred.name, ', '.join([str(a) for a in self.args]))
def match(self, other):
'''Returns a dictionary of bindings which map variables in this fluent
to variables/values in another fluent.
'''
if not other.pred == self.pred:
return None
bindings = {}
for arg_self, arg_other in zip(self.args, other.args):
# (strings starting with upper case are assumed to be variables)
if (not isinstance(arg_other, Variable)):
if isinstance(arg_self, Variable):
print 'binding:', arg_self, arg_other
bindings[arg_self] = arg_other
else:
print 'not binding:', arg_self, arg_other
if not arg_self == arg_other:
return None
else:
# for now assuming we always bind every variable. should
# relax this in the future.
raise ValueError('All variables must get bound!')
return bindings
def bind(self, bindings):
'''Returns a copy of itself with the given bindings applied.
'''
return Fluent(self.pred, [bindings.get(arg, arg) for arg in self.args])
def entails(self, other):
return self == other
def contradicts(self, other):
return False
class Predicate:
def __init__(self, name, argnames):
self.name = name
self.argnames = argnames
def __call__(self, args):
return Fluent(self, args)
def __hash__(self):
return hash(self.name)
def __eq__(self, other):
return self.name == other.name
class ConjunctionOfFluents:
def __init__(self, fluents):
'''State represented as a conjunction of fluents.
'''
self.fluents = tuple(fluents)
def __hash__(self):
'''Using sum because hash should be the same regardless of the
order of the fluents.
'''
return hash(sum([hash(f) for f in self.fluents]))
def __repr__(self):
if len(self.fluents) > 0:
return ' ^ '.join([str(f) for f in self.fluents])
else:
return '---'
def _entails_fluent(self, f):
return any([fs.entails(f) for fs in self.fluents])
def _contradicts_fluent(self, f):
return any([fs.contradicts(f) for fs in self.fluents])
def bind(self, bindings):
'''Return a copy of itself with the given bindings applied.
'''
return ConjunctionOfFluents([f.bind(bindings) for f in self.fluents])
def entails(self, other):
if isinstance(other, Fluent):
return self._entails_fluent(other)
elif isinstance(other, ConjunctionOfFluents):
return all([self._entails_fluent(f) for f in other.fluents])
else:
TypeError('Cannot operate on %s' % str(other))
def contradicts(self, other):
if isinstance(other, Fluent):
return self._contradicts_fluent(other)
elif isinstance(other, ConjunctionOfFluents):
return any([self._contradicts_fluent(f) for f in other.fluents])
else:
TypeError('Cannot operate on %s' % str(other))
class AbstractionInfo:
def __init__(self, fluent_counts={}):
self.fluent_counts = fluent_counts
def __repr__(self):
return 'AbstractionInfo(%s)' % repr(self.fluent_counts)
def inc_abs_level(self, f):
if not f in self.fluent_counts:
self.fluent_counts[f] = 0
self.fluent_counts[f] += 1
def get_abs_level(self, f):
if not f in self.fluent_counts:
return 0
else:
return self.fluent_counts[f]
def copy(self):
return AbstractionInfo(self.fluent_counts.copy())
class Operator:
def __init__(self, name, target, suggesters, preconditions, side_effects, primitive):
self.name = name
self.target = target
self.suggesters = suggesters
self.preconditions = preconditions
self.side_effects = side_effects
self.primitive = primitive
def __repr__(self):
return '%s()' % self.name
def gen_instances(self, world, current_state, goal, abs_info):
for goal_fluent in goal.fluents:
bindings = self.target.match(goal_fluent)
if bindings == None:
continue
# bind target and calculate current abstraction level
target = self.target.bind(bindings)
abs_level = abs_info.get_abs_level(target)
for other_bindings in suggest_values(self.suggesters, world, current_state, goal):
bindings.update(other_bindings)
pc_fluents = []
for abs_n, f in self.preconditions:
if abs_n <= abs_level:
pc_fluents.append(f.bind(bindings))
preconditions = ConjunctionOfFluents(pc_fluents)
side_effects = self.side_effects.bind(bindings)
concrete = (len(preconditions.fluents) == len(self.preconditions))
yield OperatorInstance(self.name, abs_level,
target, preconditions, side_effects, self.primitive, concrete)
class OperatorInstance:
def __init__(self, operator_name, abs_level, target, preconditions, side_effects, primitive, concrete):
self.operator_name = operator_name
self.abs_level = abs_level
self.target = target
self.preconditions = preconditions
self.side_effects = side_effects
self.primitive = primitive
self.concrete = concrete
def __repr__(self):
return 'A%d: %s(%s)' % (self.abs_level, self.operator_name, ', '.join([str(a) for a in self.target.args]))
class HPlanTree:
def __init__(self, goal=None, plan=None):
self.goal = goal
self.plan = plan
def __str__(self):
if self.plan == None:
return str(self.goal)
else:
return '%s( %s )' % (self.goal, ' '.join([str(st) for (op, st) in self.plan]))
def suggest_values(vars, world, current_state, goal):
'''Suggest values for all variables in the given dictionary.
Args:
vars (dict): Dictionary in which the keys are variables, and the values are
suggesters for that variable.
current_state (State): Current world state.
goal (ConjunctionOfFluents): Goal conjunction.
'''
if len(vars) == 0:
yield {}
return
remaining_vars = vars.copy()
varname, suggester = remaining_vars.popitem()
for val in suggester(world, current_state, goal):
if len(remaining_vars) == 0:
yield {varname: val}
else:
for values in suggest_values(remaining_vars, world, current_state, goal):
values[varname] = val
yield values
|
6473a46ccb7d1e761875c1e0bad2e231228a2d2a | amulyaparam/girlswhocoderepo | /gloop.py | 89 | 3.84375 | 4 | g_list = ["bread", "cheese", "milk", "juice"]
for g_list in range(3):
print(g_list)
|
5d728361f053726e324ee0e39d6e7743f50ef9f3 | auvy/big_data_2021 | /lab4/main.py | 1,973 | 3.765625 | 4 | import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import os
#PART1
#step1
#step2
salesDist = pd.read_csv('./stores-dist.csv')
# print(salesDist.head())
salesDist = salesDist.rename(columns={'annual net sales':'sales','number of stores in district':'stores'})
# print(salesDist.head())
#PART 2
#step 1
sales = salesDist.drop(columns={'district'})
# print(sales.head())
#step2
y = sales['sales']
x = sales.stores
plt.figure(figsize=(20,10))
plt.plot(x,y, 'o', markersize = 15)
plt.ylabel('Annual Net Sales', fontsize = 30)
plt.xlabel('Number of Stores in the District', fontsize = 30)
plt.xticks(fontsize = 20)
plt.yticks(fontsize = 20)
# plt.show()
# #PART 3
# #step1
m, b = np.polyfit(x,y,1)
# print ('The slope of line is {:.2f}.'.format(m))
# print ('The y-intercept is {:.2f}.'.format(b))
# print ('The best fit simple linear regression line is {:2f}x + {:.2f}.'.format(m, b))
#step2
y_mean = y.mean()
x_mean = x.mean()
# print ('The centroid for this dataset is x = {:.2f} and y = {:.2f}.'.format(x_mean, y_mean))
#step3
plt.figure(figsize=(20,10))
plt.plot(x,y, 'o', markersize = 14, label = "Annual Net Sales")
plt.plot(x_mean,y_mean, '*', markersize = 30, color = "r")
plt.plot(x, m*x + b, '-', label = 'Simple Linear Regression Line', linewidth = 4)
plt.ylabel('Annual Net Sales', fontsize = 30)
plt.xlabel('Number of Stores in District', fontsize = 30)
plt.xticks(fontsize = 20)
plt.yticks(fontsize = 20)
plt.annotate('Centroid', xy=(x_mean-0.1, y_mean-5), xytext=(x_mean-3, y_mean-20),arrowprops=dict(facecolor='black', shrink=0.05), fontsize = 30)
plt.legend(loc = 'upper right', fontsize = 20)
# plt.show()
#step4
def predict(query):
if query >= 1:
predict = m * query + b
return predict
else:
print ("You must have >= 1 store in the district to predict the annual net sales.")
print(predict(4)) |
cbf7a121424cb1217533d40d5c0a492197035194 | HuuHoangNguyen/Python_learning | /Modules.py | 5,574 | 4.25 | 4 | #!/usr/bin/python
"""
A module allows you to logically organize yout Pyhon code. Grouping related code
into a module makes the code easier to understand and use. A module is a Python
object with arbitrarily named attributes thay you can bind and reference.
Simply, a module is a file consisting of Python code. A module can define functions,
classes and variable. A module can also include runnable code.
"""
"""
----------------------------------------------------------------------------------
The import Statement
You can use any Python source file as a module by execuing an import
statement in some other Python source file. The import has the following syntax:
'import module1[, module2[,...moduleN]]'
When the interpreter encounters an import statement, it imports the module if the
module is present in the search path. A search path is a list of directories that
the interpreter searches before importing a module.
"""
print "\n-----------------------------------------"
import Support
Support.print_func("Zara")
"""
The 'from ... import' Statement
Python's 'from' statement lets you import specific atributes from a module into
Syntax:
from module_name import name1 [,name2 ,..., nameN]
For examble, to import the function fibonacci frm the module fib,
use the following
"""
# from fib import fibonacci
"""
This statement dees not import the entire module fib into the current
namespace; it just introduces the item fibonacci from the module fib into
the global symboy table of the importing module.
"""
"""
----------------------------------------------------------------------------------
The 'from... import *' Statement:
It is also posible to import all names from a module into the current
namespace by using the following import statement.
from module_name import *
"""
"""
----------------------------------------------------------------------------------
When you import a module, the Python interpreter searches for the module in the following sequences:
- The current directory
If the module isn't fount, Python then searches each directory in the shell variable $PYTHONPATH.
- If all else fails, Python checks the default path. On Unix, this default path is normally
/usr/local/lib/python
The module search path is stored in the system module sys as the sys.path variable.
The sys,path variable contains the current directory, PYTHONPATH, and the installation-dependent default.
"""
"""
----------------------------------------------------------------------------------
Variables are names (identifiers) that map to objects. A namespace is a dictionary of variable names(keys)
and their corresponding objects(values).
A Python statement can access variables in a local namespace and in the global namespace. If a local and a
global variable have the same name. the local variable shadows the global variable.
Each function has sits own local namespace. Class methods follow the same scoping rule as ordinary functions.
Python makes educated guesses on whether variables are local or global. It assumes that any variable assigned
a value in a function is local.
Therefore, in order to assign a value to a global variable within a function, you must first use the 'global' statement
The statement 'global VarNam' tell Python that VarName is a global variable. Python stops searching the local namespace for
the variable.
"""
Money = 2000
def AddMoney():
#Uncomment the following line to fix the code.
global Money
Money = Money + 1
import math
<<<<<<< HEAD
=======
import sys
>>>>>>> 74c2b30bb69bfa6ce89513e2b8ea4849d82c1ae0
def main():
print "\n-----------------------------------------"
print Money
AddMoney()
print Money
print """
----------------------------------------------------------------------------------
The 'dir()' Function
The dir() build-in function returns a sorted list of strings containing the names defined
by a module.
The listt contains the names of all the modules, variables and functions that are defined
in a module.
"""
content = dir (math)
print content
print "==========="
print dir(Support)
<<<<<<< HEAD
=======
print """
The global() and local() Functions
The glocal() and local() functions can be used to return the names in the global and local
namespcaes depending on the localtion from where they are called.
Is locals() is called from within a function, it will return all the names that can be accessed
locally from that function.
The return type of both these functions is dicrionary. Therefore, name can be extracted using the
key() function.
--------------------------------
The reload() Functions.
When the module is imported into a script, the code is the tip-level portion of a module is execute
only once.
Therefore, if you want to reexecute the top-leval coded in a module, you can use the reload() function.
The reload() functions imports a previously imported module again. The syntax of the reload() function is
'reload(module_name)'
--------------------------------
Packages in Python
A package is a hierachical file directory structure that defines a single Python applycation environment
that consists of modules and subpackages and sub-subpackages, and so on.
Consider a file Pots.py available in Phone directory. This file has following line of source code.
"""
>>>>>>> 74c2b30bb69bfa6ce89513e2b8ea4849d82c1ae0
if __name__ == "__main__":
main()
|
243fa09f33b873b827c1a69345df1da1f850bdf4 | HuuHoangNguyen/Python_learning | /membership_operators.py | 458 | 4.03125 | 4 | #!/usr/bin/python
a = 10
b = 20
list = [1, 2, 3, 4,5]
if a in list:
print "Line 1: a is available in the given list"
else:
print "Line 1: a is not available in the given list"
if b not in list:
print "Line 2: b is not availabale in the given list"
else:
print "Line 2: b is available in the given list"
a = 2
if a in list:
print "Line 3: a is available in the given list"
else:
print "Line 3: a is not availeble in the given list"
|
057e4637e754f4dbb0bd6e71078e730864603eef | ChengYuHua/PI-God-and-their-100-project | /計分系統.py | 12,926 | 3.5 | 4 | # import csv
#
# filename = "______.csv "
# with open filename as f
# reader csv reader f
# header_row=next(reader)
# print(header_row)
class Restaurant:
service = [0, 0, 0]
food = [0, 0, 0]
cp = [0, 0, 0]
environment = [0, 0, 0]
reachable = [0, 0, 0]
speed = [0, 0, 0]
total = [0, 0] # 中立就跳過不要計
articles = 0
def total_service(self):
# 名詞
if ["服務", "態度", "老闆", "員工", "笑容" ] in string :
# 正向模糊詞
if ["不賴", "完美", "好", "讚", "佳", "高級", "滿意", "優良", "優秀", "棒","不錯", "厲害",
"專業", "有", "用心", "享受", "精湛", "精緻", "實在", "特別", "可愛", "豐富", "喜歡",
"幸福", "推薦", "首選", "美", "用心", "優質", "高", "爆表", "多", "足", "夠", "驚豔",
"愉快", "愛", "推"] in 名詞的後3位內的詞:
# 否定詞判斷
if ["不", "沒有"] in 模糊詞的前面:
self.service[2] += 1
else:
self.service[0] += 1
# 負向模糊詞
elif ["差", "糟", "爛", "失望", "待加強", "錯", "噁心"] in 名詞的後3位內的詞:
# 否定詞判斷
if ["不", "沒有"] in 模糊詞的前面:
self.service[0] += 1
else:
self.service[2] += 1
# 正向精準詞
elif ["周詳", "細心", "周到", "親切", "貼心", "友善", "熱情", "禮貌", "認真", "健談",
"和氣", "有禮", "熱心", "溫柔", "客氣", "和善", "親民", "熱忱", "體貼"] in string:
# 否定詞判斷
if ["不", "沒有"] in 模糊詞的前面:
self.service[2] += 1
else:
self.service[0] += 1
# 負向精準詞
elif ["不耐煩", "自以為是", "不屑", "馬虎"] in string:
# 否定詞判斷
if ["不", "沒有"] in 模糊詞的前面:
self.service[0] += 1
else:
self.service[2] += 1
# 找不到任何詞
else:
self.service[1] += 1
return (self.service[0] / self.articles), (self.service[1] / self.articles), (self.service[2] / self.articles)
def total_food(self):
# 名詞
if ["餐點", "口感", "口味", "食材", "料理", "菜色", "食物",
"品項", "品質", "風味", "手藝", "廚藝", "滋味", "味道", "水準", "創意"] in string:
# 正向模糊詞
if ["不賴", "完美", "好", "讚", "佳", "高級", "滿意", "優良", "優秀", "棒","不錯", "厲害",
"專業", "有", "用心", "享受", "精湛", "精緻", "實在", "特別", "可愛", "豐富", "喜歡",
"幸福", "推薦", "首選", "美", "用心", "優質", "高", "爆表", "多", "足", "夠", "驚豔",
"愉快", "愛", "推"] in 名詞的後3位內的詞:
# 否定詞判斷
if ["不", "沒有"] in 模糊詞的前面:
self.food[2] += 1
else:
self.food[0] += 1
# 負向模糊詞
elif ["差", "糟", "爛", "失望", "待加強", "錯", "噁心"] in 名詞的後3位內的詞:
# 否定詞判斷
if ["不", "沒有"] in 模糊詞的前面:
self.food[0] += 1
else:
self.food[2] += 1
# 正向精準詞
elif ["好吃", "新鮮", "鮮美", "好滋味", "美味", "好喝", "水準高", "有特色", "回味無窮", "讓人回味", "可口", "驚艷",
"爽口", "正宗", "正統", "色香味俱全", "香氣四溢", "道地", "健康", "營養", "清爽", "多樣", "多元",
"經典", "真材實料", "順口"] in string:
# 否定詞判斷
if ["不", "沒有"] in 模糊詞的前面:
self.food[2] += 1
else:
self.food[0] += 1
# 負向精準詞
elif ["膩口", "難吃", "難喝", "奇怪", "沒熟", "油膩"] in string:
# 否定詞判斷
if ["不", "沒有"] in 模糊詞的前面:
self.food[0] += 1
else:
self.food[2] += 1
# 找不到任何詞
else:
self.food[1] += 1
return (self.food[0] / self.articles), (self.food[1] / self.articles), (self.food[2] / self.articles)
def total_cp(self):
# 名詞
if ["速度", "出菜", "上菜", "等", "排隊"] in string:
# 正向模糊詞
if ["不賴", "完美", "好", "讚", "佳", "高級", "滿意", "優良", "優秀", "棒", "不錯", "厲害",
"專業", "有", "用心", "享受", "精湛", "精緻", "實在", "特別", "可愛", "豐富", "喜歡",
"幸福", "推薦", "首選", "美", "用心", "優質", "高", "爆表", "多", "足", "夠", "驚豔",
"愉快", "愛", "推"] in 名詞的後3位內的詞:
# 否定詞判斷
if ["不", "沒有"] in 模糊詞的前面:
self.cp[2] += 1
else:
self.cp[0] += 1
# 負向模糊詞
elif ["差", "糟", "爛", "失望", "待加強", "錯", "噁心"] in 名詞的後3位內的詞:
# 否定詞判斷
if ["不", "沒有"] in 模糊詞的前面:
self.cp[0] += 1
else:
self.cp[2] += 1
# 正向精準詞
elif ["迅速", "快速", "快"] in string:
# 否定詞判斷
if ["不", "沒有"] in 模糊詞的前面:
self.cp[2] += 1
else:
self.cp[0] += 1
# 負向精準詞
elif ["久", "慢"] in string:
# 否定詞判斷
if ["不", "沒有"] in 模糊詞的前面:
self.cp[0] += 1
else:
self.cp[2] += 1
# 找不到任何詞
else:
self.cp[1] += 1
return (self.cp[0] / self.articles), (self.cp[1] / self.articles), (self.cp[2] / self.articles)
def total_environment(self):
# 名詞
if ["裝潢", "氣氛", "環境", "空間", "氛圍", "採光", "格調", "衛生", "場地", "空間", "樓梯"] in string:
# 正向模糊詞
if ["不賴", "完美", "好", "讚", "佳", "高級", "滿意", "優良", "優秀", "棒", "不錯", "厲害",
"專業", "有", "用心", "享受", "精湛", "精緻", "實在", "特別", "可愛", "豐富", "喜歡",
"幸福", "推薦", "首選", "美", "用心", "優質", "高", "爆表", "多", "足", "夠", "驚豔",
"愉快", "愛", "推"] in 名詞的後3位內的詞:
# 否定詞判斷
if ["不", "沒有"] in 模糊詞的前面:
self.environment[2] += 1
else:
self.environment[0] += 1
# 負向模糊詞
elif ["差", "糟", "爛", "失望", "待加強", "錯", "噁心"] in 名詞的後3位內的詞:
# 否定詞判斷
if ["不", "沒有"] in 模糊詞的前面:
self.environment[0] += 1
else:
self.environment[2] += 1
# 正向精準詞
elif ["划算", "物有所值", "物超所值", "平價", "佛心", "實惠", "超值", "公道", "料多", "豐盛", "澎湃"] in string:
# 否定詞判斷
if ["不", "沒有"] in 模糊詞的前面:
self.environment[2] += 1
else:
self.environment[0] += 1
# 負向精準詞
elif ["乾淨", "舒適", "明亮", "涼爽", "燈光美", "輕鬆", "簡潔", "自在", "舒服", "悠閒", "寬敞",
"衛生", "寧靜", "溫馨", "光亮", "整潔", "整齊"] in string:
# 否定詞判斷
if ["不", "沒有"] in 模糊詞的前面:
self.environment[0] += 1
else:
self.environment[2] += 1
# 找不到任何詞
else:
self.environment[1] += 1
return (self.environment[0] / self.articles), (self.environment[1] / self.articles), (self.environment[2] / self.articles)
def total_reachable(self):
# 名詞
if ["裝潢", "氣氛", "環境", "空間", "氛圍", "採光", "格調", "衛生", "場地", "空間", "樓梯"] in string:
# 正向模糊詞
if ["不賴", "完美", "好", "讚", "佳", "高級", "滿意", "優良", "優秀", "棒", "不錯", "厲害",
"專業", "有", "用心", "享受", "精湛", "精緻", "實在", "特別", "可愛", "豐富", "喜歡",
"幸福", "推薦", "首選", "美", "用心", "優質", "高", "爆表", "多", "足", "夠", "驚豔",
"愉快", "愛", "推"] in 名詞的後3位內的詞:
# 否定詞判斷
if ["不", "沒有"] in 模糊詞的前面:
self.reachable[2] += 1
else:
self.reachable[0] += 1
# 負向模糊詞
elif ["差", "糟", "爛", "失望", "待加強", "錯", "噁心"] in 名詞的後3位內的詞:
# 否定詞判斷
if ["不", "沒有"] in 模糊詞的前面:
self.reachable[0] += 1
else:
self.reachable[2] += 1
# 正向精準詞
elif ["乾淨", "舒適", "明亮", "涼爽", "燈光美", "輕鬆", "簡潔", "自在", "舒服", "悠閒", "寬敞",
"衛生", "寧靜", "溫馨", "光亮", "整潔", "整齊"] in string:
# 否定詞判斷
if ["不", "沒有"] in 模糊詞的前面:
self.reachable[2] += 1
else:
self.reachable[0] += 1
# 負向精準詞
elif ["狹小", "窄", "擁擠", "擠", "簡陋"] in string:
# 否定詞判斷
if ["不", "沒有"] in 模糊詞的前面:
self.reachable[0] += 1
else:
self.reachable[2] += 1
# 找不到任何詞
else:
self.reachable[1] += 1
return (self.reachable[0] / self.articles), (self.reachable[1] / self.articles), (self.reachable[2] / self.articles)
def total_speed(self):
# 名詞
if ["裝潢", "氣氛", "環境", "空間", "氛圍", "採光", "格調", "衛生", "場地", "空間", "樓梯"] in string:
# 正向模糊詞
if ["不賴", "完美", "好", "讚", "佳", "高級", "滿意", "優良", "優秀", "棒", "不錯", "厲害",
"專業", "有", "用心", "享受", "精湛", "精緻", "實在", "特別", "可愛", "豐富", "喜歡",
"幸福", "推薦", "首選", "美", "用心", "優質", "高", "爆表", "多", "足", "夠", "驚豔",
"愉快", "愛", "推"] in 名詞的後3位內的詞:
# 否定詞判斷
if ["不", "沒有"] in 模糊詞的前面:
self.speed[2] += 1
else:
self.speed[0] += 1
# 負向模糊詞
elif ["差", "糟", "爛", "失望", "待加強", "錯", "噁心"] in 名詞的後3位內的詞:
# 否定詞判斷
if ["不", "沒有"] in 模糊詞的前面:
self.speed[0] += 1
else:
self.speed[2] += 1
# 正向精準詞
elif ["乾淨", "舒適", "明亮", "涼爽", "燈光美", "輕鬆", "簡潔", "自在", "舒服", "悠閒", "寬敞",
"衛生", "寧靜", "溫馨", "光亮", "整潔", "整齊"] in string:
# 否定詞判斷
if ["不", "沒有"] in 模糊詞的前面:
self.speed[2] += 1
else:
self.speed[0] += 1
# 負向精準詞
elif ["狹小", "窄", "擁擠", "擠", "簡陋"] in string:
# 否定詞判斷
if ["不", "沒有"] in 模糊詞的前面:
self.speed[0] += 1
else:
self.speed[2] += 1
# 找不到任何詞
else:
self.speed[1] += 1
return (self.speed[0] / self.articles), (self.speed[1] / self.articles), (self.speed[2] / self.articles)
string = input()
string = Restaurant()
print(string.service)
string.service[0] += 1
string.articles += 1
print(string.service, string.articles)
print(string.total_service())
|
ab44b0bc2c1dda3e9f6af2267146e0357005fa13 | Guo-Alex/genetic-steganography-algorithm | /RankSelection.py | 1,836 | 3.890625 | 4 | import random as random
import hashlib
class RankSelection:
def __init__(self,population):
self.population = population
self.rankedList = list()
def setup(self,population,SP):
print "Preparing for RankSelection\nSoring List...",
self.rankedList = sorted(population, key=lambda x: x.fitness, reverse=True)
for x in range(0,len(self.rankedList)):
print self.rankedList[x].fitness
N = len(self.rankedList)
self.sum = len(population)
sums = 0
for x in range (0,len(population)):
pos = N - x
self.rankedList[x].fitness = 2 - SP + 2 * (SP - 1) * (pos - 1) / (N - 1)
sums = sums + self.rankedList[x].fitness
print(self.rankedList[x].fitness)
print(sums)
print "[done]"
################################################################
def select_individual(self,population):
R = 0
N = len(self.rankedList)-1
R = R + random.uniform(0,N)
print("Threshold : " + str(R))
weight = 0
while weight < len(population):
random_index = random.randint(0,N)
weight = weight + self.rankedList[random_index].fitness
return self.rankedList[random_index]
def select_mate(self,population,partner):
R = 0
N = len(self.rankedList)-1
R = R + random.uniform(0,N)
print("Threshold : " + str(R))
weight = 0
while weight < len(population):
random_index = random.randint(0,N)
weight = weight + self.rankedList[random_index].fitness
if(weight >= len(population) and self.rankedList[random_index] == partner):
weight = 0
return self.rankedList[random_index]
#################################################################
def get_parents(self,population):
print "Selecting parent one :\n"
parent_one = self.select_individual(population)
print "\nSelecting parent two: \n"
parent_two = self.select_mate(population,parent_one)
return parent_one,parent_two |
946d183421857c5896636eac5dcaa797091cb87a | aboyington/cs50x2021 | /week6/pset6/mario/more/mario.py | 480 | 4.15625 | 4 | from cs50 import get_int
def get_height(min=1, max=8):
"""Prompt user for height value."""
while True:
height = get_int("Height: ")
if height >= min and height <= max:
return height
def print_pyramid(n):
"""Print n height of half-pyramid to console."""
for i in range(1, n+1):
print(" "*(n-i) + "#"*i + " "*2 + "#"*i)
def main():
height = get_height()
print_pyramid(height)
if __name__ == "__main__":
main()
|
0db86d8ae6589de68b76677ad7ea6d8149332e71 | kmangutov/cs467Sankey | /csv_parser.py | 2,707 | 3.5625 | 4 | import csv
f = open("data.csv", "r")
data = csv.reader(f)
schema = []
for row in data:
schema = row + []
break
print schema
univ = set()
univ_bs = set()
univ_ms = set()
univ_phd = set()
univ_idx = schema.index('University')
univ_bs_idx = schema.index('Bachelors')
#univ_ms_idx = schema.index('Masters')
univ_phd_idx = schema.index('Doctorate')
fd_idx = schema.index('Subfield')
"""
for row in data:
univ.add(row[univ_idx])
univ_bs.add(row[univ_bs_idx])
univ_ms.add(row[univ_ms_idx])
univ_phd.add(row[univ_phd_idx])
print len(univ)
print len(univ_bs)
print len(univ_ms)
print len(univ_phd)
"""
top_univ = set(['University of Illinois at Urbana-Champaign',
'Stanford University',
'University of California - Berkeley',
'Cornell University',
'Massachusetts Institute of Technology',
'University of Texas - Austin',
'Georgia Institute of Technology',
'University of Washington',
'Carnegie Mellon University',
'Princeton University',
])
bs_prof = {}
ms_prof = {}
phd_prof = {}
bs_phd = {}
bs_program = set()
phd_program = set()
for row in data:
if row[univ_idx] in top_univ:
bs_key = (row[univ_bs_idx], row[univ_idx], row[fd_idx])
#ms_key = (row[univ_ms_idx], row[univ_idx], row[fd_idx])
phd_key = (row[univ_phd_idx], row[univ_idx], row[fd_idx])
bs_phd_key = (row[univ_bs_idx], row[univ_phd_idx], row[fd_idx])
if bs_key in bs_prof:
bs_prof[bs_key] += 1
else:
bs_prof[bs_key] = 1
if phd_key in phd_prof:
phd_prof[phd_key] += 1
else:
phd_prof[phd_key] = 1
#if ms_key in ms_prof:
# ms_prof[ms_key] += 1
#else:
# ms_prof[ms_key] = 1
if bs_phd_key in bs_phd:
bs_phd[bs_phd_key] += 1
else:
bs_phd[bs_phd_key] = 1
print len(bs_prof)
print len(ms_prof)
print len(phd_prof)
prof_data = []
for key in phd_prof:
col0 = '1_' + key[2] + '_' + key[0]
col1 = '2_'+ key[2] + '_' + key[1]
prof_data.append([col0, col1, phd_prof[key]])
for key in bs_phd:
col0 = '0_' + key[2] + '_' + key[0]
col1 = '1_'+ key[2] + '_' + key[1]
prof_data.append([col0, col1, bs_phd[key]])
def writeCsvFile(fname, data, *args, **kwargs):
"""
@param fname: string, name of file to write
@param data: list of list of items
Write data to file
"""
mycsv = csv.writer(open(fname, 'wb'), *args, **kwargs)
for row in data:
mycsv.writerow(row)
writeCsvFile("prof_data.csv", prof_data)
f.close()
|
138db170991e2efbeabe8efac9210b5885fd49c7 | edwight-delgado/python-profesional | /codes/palindrome.py | 409 | 3.953125 | 4 | def is_palindrome(string:str)->bool:
"""Returns if the string is palindrome (True or False)"""
string= string.replace(" ","").lower()
return string == string[::-1]
def suma(a:int,b:int)->int:
return a+b
def main():
print(suma('2','3'))
#lista =[ (value ,is_palindrome(value)) for value in ['Ana','Maria','oro','ala',1000]]
#print(lista)
print(is_palindrome(1000))
if __name__ == '__main__':
main() |
ff977846f338448778072c134dbf1ff0e0cfa998 | drexpp/Personal-projects | /Codefights/Interview questions/Dynamic programming/cimbingStairs.py | 124 | 3.53125 | 4 | def climbingStairs(n):
a = [0, 1, 2]
for i in range(3,n+1):
a.append(a[i - 1] + a[i - 2])
return a[n]
|
2b233d93ef2101f8833bbff948682add348fde63 | djanibekov/algorithms_py | /inversion_counting.py | 2,025 | 4.21875 | 4 | inversion_count = 0
def inversion_counter_conquer(first, second):
"""[This function counts #inversions while merging two lists/arrays ]
Args:
first ([list]): [left unsorted half]
second ([list]): [right unsorted half]
Returns:
[tuple]: [(first: merged list of left and right halves, second: #inversions)]
"""
i = 0
j = 0
length_of_first = len(first)
length_of_second = len(second)
inversion_count = 0
merged = []
#? looking for number of particular inversion
while (i < length_of_first) and (j < length_of_second):
if (first[i] > second[j]):
inversion_count += length_of_first - i
merged.append(second[j])
j = j + 1
else:
merged.append(first[i])
i = i + 1
#! extra check whether element is left
while i < len(first):
merged.append(first[i])
i = i + 1
while j < len(second):
merged.append(second[j])
j = j + 1
return merged, inversion_count
def list_divider_divide(array):
"""[This function divides the input list/array in to two parts recursively
by divide and conquer method till the base case.]
Args:
array ([list]): [given input]
Returns:
[int]: [final answer of the question "How many inversions did list hold?"]
[list]: [the sorted array/list of two derived lists "left" and "right"]
"""
length = len(array)
if(length == 1):
return array, 0
mid = length // 2
left = list_divider_divide(array[:mid])
right = list_divider_divide(array[mid:])
#? inversion_count holds the sum of all particular #inversion
merged, particular_inversions = inversion_counter_conquer(left[0], right[0])
inversion_count = particular_inversions + left[1] + right[1]
return merged, inversion_count
f_name = open("IntegerArray.txt")
integers = []
for integer in f_name:
integers.append(int(integer))
print(list_divider_divide(integers)[1])
|
609b60ed9ad43ca1b3053d86daf92bf440fcd65a | LeongWaiLimn/Coursera-test | /Python_stuff/Assignment/9/assignment_9.4.py | 647 | 3.703125 | 4 | name = input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
email_data = dict()
for readfile in handle:
if not readfile.startswith ("From "):
continue
email_list = readfile.split()
email_only = email_list[1]
#print("Email list:",email_only)
email_data[email_only]=email_data.get(email_only,0)+1
email_count = None
common_email = None
for key,value in email_data.items():
if email_count is None or value > email_count:
common_email = key
email_count = value
#print(email_data)
#print(email_data.items())
print(common_email,email_count)
|
59b8795ae291f06a1b9f56a4e9e0eac3e15d3a34 | SyaoranR/ADS_Pycharm | /Idade COMPLETO.py | 4,847 | 3.875 | 4 | # idade, nasc, ano, niver_mes, mes, niver_dia, dia,
# i, j, dias, d, idade_dias, resto_ano, meses, days
# bis: logico
print("Idade, COMPLETO")
# s em anos
idade = int(input("Informe a idade do indivduo: "))
# verificao
nasc = int(input("Informe o ano de nascimento: "))
atual = int(input("Informe o ano atual: "))
niver_mes = int(input("Informe o ms de aniversrio: "))
mes = int(input("Informe o ms atual: "))
niver_dia = int(input("Informe o dia de aniversrio: "))
dia = int(input("Informe o dia atual: "))
bis = bool(input("Informe se ano bissexto: "))
# idade a cada 4 anos idade_dias < - + 1 dia(anos bissextos)
# o indivduo nasceu
if ano < nasc:
nasc = int(input("Informe novamente o ano de nascimento: "))
atual = int(input("Informe novamente o ano atual: "))
# validade do ms
if niver_mes < 1 or niver_mes > 12:
niver_mes = int(input("Informe novamente o ms de aniversrio: "))
if mes < 1 or mes > 12:
mes = int(input("Informe novamente o ms atual: "))
# Incio do bloco para o ms de aniversrio
i = niver_mes
print("Mes de aniversrio: ")
# fevereiro
if i == 2:
print ("Fevereiro")
if bis == False:
print("Ano no bissexto")
dias = 28
else: # True
print("Ano bissexto")
dias = 29
# abril, junho, setembro, novembro
if i == 4 or i == 6 or i == 9 or i == 11:
dias = 30
else: # janeiro, maro, maio, julho, outubro, dezembro
dias = 31
# meses impressos exceto fevereiro
if i == 1:
print("Janeiro")
if i == 3:
print("Maro")
if i == 4:
print("Abril")
if i == 5:
print("Maio")
if i == 6:
print("Junho")
if i == 7:
print("Julho")
if i == 8:
print("Agosto")
if i == 9:
print("Setembro")
if i == 10:
print("Outubro")
if i == 11:
print("Novembro")
if i == 12:
print("Dezembro")
# Fim do bloco para o ms de aniversrio
# Incio do bloco para o ms atual
j = mes
print("Mes atual: ")
# fevereiro
if j == 2:
print ("Fevereiro")
if bis == False:
print("Ano no bissexto")
d = 28
else: # True
print("Ano bissexto")
d = 29
# abril, junho, setembro, novembro
if j == 4 or j == 6 or j == 9 or j == 11:
d = 30
else: # janeiro, maro, maio, julho, outubro, dezembro
d = 31
# meses impressos exceto fevereiro
if j == 1:
print("Janeiro")
if j == 3:
print("Maro")
if j == 4:
print("Abril")
if j == 5:
print("Maio")
if j == 6:
print("Junho")
if j == 7:
print("Julho")
if j == 8:
print("Agosto")
if j == 9:
print("Setembro")
if j == 10:
print("Outubro")
if j == 11:
print("Novembro")
if j == 12:
print("Dezembro")
# Fim do bloco para o ms atual
# Validade de dias ms aniversrio
if niver_mes == i or mes == j:
if niver_dia < 1 or niver_dia > dias:
niver_dia = int(input("Informe novamente o dia de aniversrio: "))
if dia < 1 or dia > d:
dia = int(input("Informe novamente o dia atual: "))
# idade a cada 4 anos idade_dias < - + 1 dia(anos bissextos)
if niver_mes == mes:
if niver_dia == dia:
idade_dias < - idade * 365 + int(idade / 4)
print(idade_dias, " idade em dia(s).")
elif niver_dia < dia:
idade_dias < - idade * 365 + int(idade / 4) + (dia - niver_dia)
print(idade_dias, " idade em dia(s).")
else: # niver_dia > dia:
idade_dias < - idade * 365 + int(idade / 4) + (12 - 1) * 30 + (d - (niver_dia - dia))
print(idade_dias, " idade em dia(s).")
elif niver_mes < mes:
if niver_dia == dia:
idade_dias < - idade * 365 + int(idade / 4) + (mes - niver_mes) * 30
print(idade_dias, " idade em dia(s).")
elif niver_dia < dia:
idade_dias < - idade * 365 + int(idade / 4) + (mes - niver_mes) * 30 + (dia - niver_dia)
print(idade_dias, " idade em dia(s).")
else: # niver_dia > dia:
idade_dias < - idade * 365 + int(idade / 4) + (mes - niver_mes - 1) * 30 + (dias - (niver_dia - dia))
print(idade_dias, " idade em dia(s).")
else: # niver_mes > mes:
if niver_dia == dia:
idade_dias < - idade * 365 + int(idade / 4) + 12 - (niver_mes - mes) * 30
print(idade_dias, " idade em dia(s).")
elif niver_dia < dia:
idade_dias < - idade * 365 + int(idade / 4) + 12 - (niver_mes - mes) * 30 + (dia - niver_dia)
print(idade_dias, " idade em dia(s).")
else: # niver_dia > dia:
idade_dias < - idade * 365 + int(idade / 4) + 12 - (niver_mes - mes - 1) * 30 + (d - (niver_dia - dia))
print(idade_dias, " idade em dia(s).")
ano = int(idade_dias / 365)
print('anos = ', ano)
resto_ano = idade_dias % 365
print('o que restou em dias = ', resto_ano)
meses = int(resto_ano / 30)
print('meses = ', meses)
days = resto_ano % 30
print('dias = ', days)
print(ano, " ano(s), ", meses, " mes(es) e ", days, " dia(s)")
|
ca2c9198e41e1fa53fb33eedca15a40e47e68d51 | pjc0618/ImageModifier | /imager/a6test.py | 12,909 | 3.8125 | 4 | """
Test cases for Tasks 1 and 2
You cannot even start to process images until the base classes are done. These classes
provide you with some test cases to get you started.
Author: Walker M. White (wmw2)
Date: October 20, 2017
"""
import cornell
import pixels
def test_assert(func,args,message):
"""
Tests that the given function raises an assert on those arguments.
This uses some advanced Python. Do not worry about how it works.
Parameter func: The function/method being tested
Precondition: func is callable
Parameter args: The function arguments
Precondition: args is a list of arguments for func
Parameter message: The message to display on failure
Precondition: message is a string
"""
try:
func(*args)
except AssertionError:
return True
except:
pass
print(message+' for '+func.__name__)
return False
def test_image_init():
"""
Tests the __init__ method and getters for class Image
"""
print('Testing image initializer')
import a6image
p = pixels.Pixels(6)
image = a6image.Image(p,3)
cornell.assert_equals(id(p),id(image.getPixels()))
cornell.assert_equals(6,image.getLength())
cornell.assert_equals(3,image.getWidth())
cornell.assert_equals(2,image.getHeight())
image = a6image.Image(p,2)
cornell.assert_equals(id(p),id(image.getPixels()))
cornell.assert_equals(6,image.getLength())
cornell.assert_equals(2,image.getWidth())
cornell.assert_equals(3,image.getHeight())
image = a6image.Image(p,1)
cornell.assert_equals(id(p),id(image.getPixels()))
cornell.assert_equals(6,image.getLength())
cornell.assert_equals(1,image.getWidth())
cornell.assert_equals(6,image.getHeight())
# Test enforcement
good = test_assert(a6image.Image,['aaa',3],'You are not enforcing the precondition on data')
good = good and test_assert(a6image.Image,[p,'a'],'You are not enforcing the precondition on width type')
good = good and test_assert(a6image.Image,[p, 5],'You are not enforcing the precondition on width validity')
if not good:
exit()
def test_image_setters():
"""
Tests the setters for class Image
"""
print('Testing image setters')
import a6image
p = pixels.Pixels(6)
image = a6image.Image(p,3)
cornell.assert_equals(3,image.getWidth())
cornell.assert_equals(2,image.getHeight())
image.setWidth(2)
cornell.assert_equals(2,image.getWidth())
cornell.assert_equals(3,image.getHeight())
image.setHeight(1)
cornell.assert_equals(6,image.getWidth())
cornell.assert_equals(1,image.getHeight())
image.setWidth(1)
cornell.assert_equals(1,image.getWidth())
cornell.assert_equals(6,image.getHeight())
# Test enforcement
good = test_assert(image.setWidth, ['a'], 'You are not enforcing the precondition on width type')
good = good and test_assert(image.setWidth, [5], 'You are not enforcing the precondition on width validity')
good = good and test_assert(image.setHeight, ['a'], 'You are not enforcing the precondition on height type')
good = good and test_assert(image.setHeight, [5], 'You are not enforcing the precondition on height validity')
if not good:
exit()
def test_image_access():
"""
Tests the methods get/setPixel and get/setFlatPixel in class Image
"""
print('Testing image pixel access')
import a6image
p = pixels.Pixels(6)
p[0] = (255,0,0)
p[1] = (0,255,0)
p[2] = (0,0,255)
p[3] = (0,255,255)
p[4] = (255,0,255)
p[5] = (255,255,0)
rgb1 = (255,255,255)
rgb2 = (64,128,192)
image = a6image.Image(p,2)
for n in range(6):
cornell.assert_equals(p[n],image.getFlatPixel(n))
cornell.assert_equals(id(p[n]),id(image.getFlatPixel(n)))
image.setFlatPixel(4,rgb1)
cornell.assert_equals(rgb1,image.getFlatPixel(4))
image.setFlatPixel(4,rgb2)
cornell.assert_equals(rgb2,image.getFlatPixel(4))
for n in range(6):
cornell.assert_equals(p[n],image.getPixel(n // 2, n % 2))
cornell.assert_equals(id(p[n]),id(image.getPixel(n // 2, n % 2)))
image.setPixel(2,1,rgb1)
cornell.assert_equals(rgb1,image.getPixel(2,1))
image.setPixel(2,1,rgb2)
cornell.assert_equals(rgb2,image.getPixel(2,1))
# Test enforcement
good = test_assert(image.getPixel, ['a', 1], 'You are not enforcing the precondition on row type')
good = good and test_assert(image.getPixel, [8, 1], 'You are not enforcing the precondition on row value')
good = good and test_assert(image.getPixel, [2, 'a'], 'You are not enforcing the precondition on col value')
good = good and test_assert(image.getPixel, [2, 8], 'You are not enforcing the precondition on col value')
good = good and test_assert(image.setPixel, ['a', 1, p], 'You are not enforcing the precondition on row type')
good = good and test_assert(image.setPixel, [8, 1, p], 'You are not enforcing the precondition on row value')
good = good and test_assert(image.setPixel, [2, 'a', p], 'You are not enforcing the precondition on col value')
good = good and test_assert(image.setPixel, [2, 8, p], 'You are not enforcing the precondition on col value')
if not good:
exit()
def test_image_str():
"""
Tests the __str__ method in class Image
"""
print('Testing image __str__ method')
import a6image
p = pixels.Pixels(6)
p[0] = (255, 64, 0)
p[1] = ( 0, 255, 64)
p[2] = ( 64, 0, 255)
p[3] = ( 64, 255, 128)
p[4] = (128, 64, 255)
p[5] = (255, 128, 64)
str0 = '[['+str(p[0])+', '+str(p[1])+'], ['+str(p[2])+', '+str(p[3])+']]'
str1 = '[['+str(p[0])+', '+str(p[1])+'], ['+str(p[2])+', '+str(p[3])+'], ['+str(p[4])+', '+str(p[5])+']]'
str2 = '[['+str(p[0])+', '+str(p[1])+', '+str(p[2])+'], ['+str(p[3])+', '+str(p[4])+', '+str(p[5])+']]'
str3 = '[['+str(p[0])+', '+str(p[1])+', '+str(p[2])+', '+str(p[3])+', '+str(p[4])+', '+str(p[5])+']]'
str4 = '[['+str(p[0])+'], ['+str(p[1])+'], ['+str(p[2])+'], ['+str(p[3])+'], ['+str(p[4])+'], ['+str(p[5])+']]'
image = a6image.Image(p[:4],2)
cornell.assert_equals(str0,str(image))
image = a6image.Image(p,2)
cornell.assert_equals(str1,str(image))
image.setWidth(3)
cornell.assert_equals(str2,str(image))
image.setWidth(6)
cornell.assert_equals(str3,str(image))
image.setWidth(1)
cornell.assert_equals(str4,str(image))
def test_image_other():
"""
Tests the copy and swapPixel methods in class Image
"""
print('Testing image extras')
import a6image
p = pixels.Pixels(6)
p[0] = (255, 64, 0)
p[1] = ( 0, 255, 64)
p[2] = ( 64, 0, 255)
p[3] = ( 64, 255, 128)
p[4] = (128, 64, 255)
p[5] = (255, 128, 64)
q = p[:] # Need to copy this
# Test the copy
image = a6image.Image(p,2)
copy = image.copy()
cornell.assert_equals(image.getLength(),copy.getLength())
cornell.assert_equals(image.getWidth(),copy.getWidth())
cornell.assert_not_equals(id(image), id(copy))
cornell.assert_not_equals(id(image.getPixels()), id(copy.getPixels()))
for pos in range(copy.getLength()):
cornell.assert_equals(image.getPixels()[pos],copy.getPixels()[pos])
# Test swap pixels
image.swapPixels(0,0,2,1)
cornell.assert_equals(q[5],image.getPixel(0,0))
cornell.assert_equals(q[0],image.getPixel(2,1))
image.swapPixels(0,0,2,1)
cornell.assert_equals(q[0],image.getPixel(0,0))
cornell.assert_equals(q[5],image.getPixel(2,1))
image.swapPixels(0,1,2,0)
cornell.assert_equals(q[4],image.getPixel(0,1))
cornell.assert_equals(q[1],image.getPixel(2,0))
image.swapPixels(0,1,2,0)
cornell.assert_equals(q[1],image.getPixel(0,1))
cornell.assert_equals(q[4],image.getPixel(2,0))
image.swapPixels(0,0,0,0)
cornell.assert_equals(q[0],image.getPixel(0,0))
# Test enforcement
good = test_assert(image.swapPixels, ['a', 1, 0, 0], 'You are not enforcing the precondition on row type')
good = good and test_assert(image.swapPixels, [8, 1, 0, 0], 'You are not enforcing the precondition on row value')
good = good and test_assert(image.swapPixels, [0, 1, 'a', 0], 'You are not enforcing the precondition on row type')
good = good and test_assert(image.swapPixels, [0, 1, 8, 0], 'You are not enforcing the precondition on row value')
good = good and test_assert(image.swapPixels, [0, 'a', 0, 0], 'You are not enforcing the precondition on column type')
good = good and test_assert(image.swapPixels, [0, 8, 0, 0], 'You are not enforcing the precondition on column value')
good = good and test_assert(image.swapPixels, [0, 1, 0, 'a'], 'You are not enforcing the precondition on column type')
good = good and test_assert(image.swapPixels, [0, 1, 0, 8], 'You are not enforcing the precondition on column value')
if not good:
exit()
def test_hist_init():
"""
Tests the __init__ method and getters in ImageHistory
"""
print('Testing history initializer')
import a6image
import a6history
p = pixels.Pixels(6)
p[0] = (255,0,0)
p[1] = (0,255,0)
p[2] = (0,0,255)
p[3] = (0,255,255)
p[4] = (255,0,255)
p[5] = (255,255,0)
image = a6image.Image(p,2)
hist = a6history.ImageHistory(image)
cornell.assert_equals(id(image),id(hist.getOriginal()))
cornell.assert_equals(type(image),type(hist.getCurrent()))
cornell.assert_not_equals(id(image),id(hist.getCurrent()))
current = hist.getCurrent()
cornell.assert_not_equals(id(p), id(current.getPixels()))
for pos in range(current.getLength()):
cornell.assert_equals(p[pos],current.getPixels()[pos])
cornell.assert_true(hasattr(hist, '_history'))
cornell.assert_equals(list,type(hist._history))
cornell.assert_equals(1,len(hist._history))
def test_hist_edit():
"""
Tests the edit (increment/undo/clear) methods in ImageHistory
"""
print('Testing history edit methods')
import a6image
import a6history
p = pixels.Pixels(6)
p[0] = (255,0,0)
p[1] = (0,255,0)
p[2] = (0,0,255)
p[3] = (0,255,255)
p[4] = (255,0,255)
p[5] = (255,255,0)
image = a6image.Image(p,2)
hist = a6history.ImageHistory(image)
bottom = hist.getCurrent()
bottom.setPixel(0,0,(64,128,192))
hist.increment()
current = hist.getCurrent()
cornell.assert_equals(bottom.getLength(),current.getLength())
cornell.assert_equals(bottom.getWidth(),current.getWidth())
cornell.assert_not_equals(id(bottom), id(current))
cornell.assert_not_equals(id(bottom.getPixels()), id(current.getPixels()))
for pos in range(current.getLength()):
cornell.assert_equals(bottom.getPixels()[pos],current.getPixels()[pos])
hist.undo()
cornell.assert_equals(id(bottom),id(hist.getCurrent()))
hist.increment()
hist.increment()
hist.increment()
cornell.assert_equals(4,len(hist._history))
current = hist.getCurrent()
cornell.assert_equals(bottom.getLength(),current.getLength())
cornell.assert_equals(bottom.getWidth(),current.getWidth())
cornell.assert_not_equals(id(bottom), id(current))
cornell.assert_not_equals(id(bottom.getPixels()), id(current.getPixels()))
for pos in range(current.getLength()):
cornell.assert_equals(bottom.getPixels()[pos],current.getPixels()[pos])
hist.clear()
cornell.assert_not_equals(id(bottom),id(hist.getCurrent()))
cornell.assert_equals(1,len(hist._history))
original = hist.getOriginal()
current = hist.getCurrent()
cornell.assert_equals(original.getLength(),current.getLength())
cornell.assert_equals(original.getWidth(),current.getWidth())
cornell.assert_not_equals(id(original), id(current))
cornell.assert_not_equals(id(original.getPixels()), id(current.getPixels()))
for pos in range(current.getLength()):
cornell.assert_equals(original.getPixels()[pos],current.getPixels()[pos])
bottom = hist.getCurrent()
bottom.setPixel(0,0,(64,128,192))
for step in range(hist.MAX_HISTORY+1):
hist.increment()
cornell.assert_equals(hist.MAX_HISTORY,len(hist._history))
cornell.assert_not_equals(id(bottom), id(hist._history[0]))
def test_all():
"""
Execute all of the test cases.
This function is called by __main__.py
"""
test_image_init()
test_image_setters()
test_image_access()
test_image_str()
test_image_other()
print('Class Image appears to be working correctly')
print()
test_hist_init()
test_hist_edit()
print('Class ImageHistory appears to be working correctly')
|
d872888d0820e600a2324ff64beb376384011c28 | ShuklaG1608/Python-for-Everybody-Specialization---Coursera | /2. Python Data Structures/Week 6/Py4EDataStructureWeek6Ex1.py | 849 | 3.9375 | 4 | '''Write a program to read through the mbox-short.txt and figure out the distribution by hour of the day for each of the messages.
You can pull the hour out from the 'From ' line by finding the time and then splitting the string a second time using a colon.
From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
Once you have accumulated the counts for each hour, print out the counts, sorted by hour as shown below.'''
name = input("Enter file:")
handle = open(name)
mydiction = dict()
myList = []
hoursList = []
for lines in handle:
if lines.startswith("From "):
words = lines.split()
myList.append(words[5])
for hours in myList:
h = hours.split(':')
hoursList.append(h[0])
for word in hoursList:
mydiction[word] = mydiction.get(word,0)+1
temp = sorted(mydiction.items())
temp.sort()
for hrs,ct in temp:
print(hrs,ct)
|
a2676ba8f5951f65248b4503b8df8e989c2422e9 | nurulsucisawaliah/python-project-chapter-6 | /latihan 2[praktikum 4]/latihan 2[ starFormation ].py | 1,166 | 3.515625 | 4 | #starFormation1
def starFormation1(n):
Kolom=0
Baris=n
i=0
while(i<=n):
j=0
while(j<Kolom):
print('*',end='')
j+=1
print('')
i+=1
Kolom+=1
#contohsF1
starFormation1(4)
print()
#starFormation2
def starFormation2(n):
Kolom=n
Baris=n
i=0
while(i<=n):
j=0
while(j<Kolom):
print('*',end='')
j+=1
print('')
i+=1
Kolom-=1
#contohsF2
starFormation2(4)
print()
#starFormation3
def starFormation3(n):
Kolom=0
Baris=n
Puncak=(n+1)/2
i=0
while(i<=n):
j=0
while(j<Kolom):
print('*',end='')
j+=1
print()
i+=1
Kolom+=1
if(Kolom == Puncak):
Kolom=Puncak
Baris=Puncak
i=0
while(i<=n):
j=1
while(j<=Kolom):
print('*',end='')
j+=1
print()
i+=1
Kolom-=1
#contohsF3
starFormation3(7)
print()
|
c415d93b04059c595aea33f054d032c075cfa83c | pran-p/port-mapper | /script.py | 3,211 | 4.21875 | 4 | """This is a simple port scanner built using the concept of sockets in python"""
import socket
import sys
import argparse
import pyfiglet
import os
"""This function is used to scan a given ip for a given open port"""
def portScanSingle(port,ip):
s=socket.socket()
try:
print ("[+] 4tt3mpting t0 c0nn3ct t0 "+ str(ip)+":"+str(port))
s.connect((ip,int(port)))
print (" [.] Port open: "+str(port))
s.close()
return 1
except:
s.close()
return 0
"""This function is used to scan for all the given ports of a specific ip"""
def portScanSingleIp(port,ip):
a=[]
for i in port:
try:
test=portScanSingle(i,ip)
if test==1:
a.append((i,ip))
except:
pass
return a
"""This function is used to scan for all the ports from a lower ip range to higher range of all the hosts(a python list)"""
def portScanner(lowerRange, higherRange,hosts):
a=[]
for ip in hosts:
for i in range(lowerRange,higherRange+1):
try:
# pass
test=portScanSingle(i,ip)
if test==1:
a.append((i,ip))
except :
pass
return a
"""This function is used to scan specific port of a list of IPs"""
def portScanPortIp(port,ip):
b=[]
for i in ip:
try:
a=portScanSingleIp(i,ip)
if len(a):
b.append(a)
except:
pass
return b
"""This is the driver code"""
def main():
os.system('tput clear')
f=pyfiglet.Figlet(font='cybermedium')
print(f.renderText('Port Mapper'))
print ('\033[1m')
print("P0rt M4pp3r: 4 simpl3 p0rt sc4nn3r t00l...")
print("F1nds 0p3n p0rts")
print ('\033[0m')
parser=argparse.ArgumentParser(description="P0rt M4pp3r: 4 simpl3 p0rt sc4nn3r t00l...")
parser.add_argument('-s','--simple', nargs=2, metavar=('port','ip'), help="enter the port number followed by the ip of the system for port scan")
parser.add_argument('-m','--multiple', nargs=2, metavar=('port1,port2,...','ip'),help='enter the list of port number separated by comma and the ip of the system for port scan')
parser.add_argument('-r','--range', nargs=3, metavar=('start-port', 'end-port', 'ip1,ip2,...'), help='enter the start port and the end port range and the ip of the system for port scan')
args=parser.parse_args()
if args.simple:
ans=portScanSingle(args.simple[0],args.simple[1])
if ans==0:
print("Th3 p0rt is cl0s3d...")
elif args.multiple:
p=args.multiple[0].split(',')
ans=portScanSingleIp(p,args.multiple[1])
print ('\033[1m')
print("The open ports are:",ans)
print ('\033[0m')
elif args.range:
address=args.range[2].split(',')
if int(args.range[1])>65535:
print("Port out of range")
else:
ans=portScanner(int(args.range[0]),int(args.range[1]), address)
print ('\033[1m')
print("The open ports are:",ans)
print ('\033[0m')
else:
print("set -h flag to see options")
if __name__ == '__main__':
main()
|
bf67625fe7b4925716e91c5dea79a23c91aeb248 | bomjic/StudyPython | /Problem016/Power_digit_sum.py | 244 | 3.671875 | 4 | def power_digit_sum(base, exponent):
result = 1
exp_res = str(base ** exponent)
print exp_res
for i in exp_res:
result += int(i)
return result
if __name__ == "__main__":
print power_digit_sum(2, 1000) |
1188524f18c0098b94fecfe5a38f4556886adfd0 | ForritunarkeppniFramhaldsskolanna/epsilon | /example_contests/fk_2014_beta/problems/tonlist/submissions/accepted/solution.py | 308 | 3.671875 | 4 |
pat = raw_input()
n = int(raw_input())
for _ in range(n):
s = raw_input()
if '*' in pat:
a, b = pat.split('*')
ok = len(a+b) <= len(s) and s.startswith(a) and s.endswith(b)
else:
ok = s == pat
if ok:
print('Passar')
else:
print('Passar ekki')
|
4f246a420a74ea3db6aa8541995ff046a99719ca | ForritunarkeppniFramhaldsskolanna/epsilon | /example_contests/fk_2014_beta/problems/bencoding/data/secret/check.py | 5,270 | 3.5 | 4 | import sys
# def parse(s):
# at = 0
# def next():
# if at == len(s):
# return None
# if s[at] == 'i':
# at += 1
# no = 0
# while at < len(s) and ord('0') <= ord(s[at]) <= ord('9'):
# no = no * 10 + (ord(s[at]) - ord('0'))
# at += 1
# if at == len(s) or s[at] != 'e':
# return None
# at += 1
# return no
# elif s[at] == 'l':
# at += 1
# l = []
# while at < len(s) and s[at] != 'e':
# it = next()
# if it is None:
# return None
# l.append(it)
# if at == len(s) or s[at] != 'e':
# return None
# at += 1
# elif s[at] == 'd':
# at += 1
# d = {}
# while at < len(s) and s[at] != 'e':
# k = next()
# if k is None:
# return None
# v = next()
# if v is None:
# return None
# if type(k) is not str:
# return None
# if k in d:
# return None
# d[k] = v
# if at == len(s) or s[at] != 'e':
# return None
# at += 1
# elif ord('0') <= ord(s[at]) <= ord('9'):
# l = 0
# while at < len(s) and ord('0') <= ord(s[at]) <= ord('9'):
# l = l * 10 + (ord(s[at]) - ord('0'))
# at += 1
# if at == len(s) or s[at] != ':':
# return None
# at += 1
# res = ''
# for _ in range(l):
# if at == len(s):
# return None
# res += s[at]
# at += 1
# return res
# else:
# return None
# res = next()
# if at != len(s):
# return None
# return res
# OOPS. Parsed the wrong type of string. Well, gotta start over..
def parse(s):
global at
at = 0
def next():
global at
if at == len(s):
return None
if s[at] == '"':
at += 1
res = ''
while at < len(s) and s[at] != '"':
res += s[at]
at += 1
if at == len(s) or s[at] != '"':
return None
at += 1
return res
elif ord('0') <= ord(s[at]) <= ord('9'):
res = 0
while at < len(s) and ord('0') <= ord(s[at]) <= ord('9'):
res = res * 10 + (ord(s[at]) - ord('0'))
at += 1
return res
elif s[at] == '[':
at += 1
res = []
while at < len(s) and s[at] != ']':
n = next()
if n is None:
return None
res.append(n)
if at == len(s):
return None
if s[at] == ']':
break
elif s[at] == ',':
at += 1
continue
else:
return None
if at == len(s) or s[at] != ']':
return None
at += 1
return res
elif s[at] == '{':
at += 1
res = {}
while at < len(s) and s[at] != '}':
k = next()
if k is None or type(k) is not str:
return None
if at == len(s) or s[at] != ':':
return None
at += 1
v = next()
if v is None:
return None
if k in res:
return None
res[k] = v
if at == len(s):
return None
if s[at] == '}':
break
elif s[at] == ',':
at += 1
continue
else:
return None
if at == len(s) or s[at] != '}':
return None
at += 1
return res
else:
return None
res = next()
if at != len(s):
return None
return res
def check(obtained, expected):
o = parse(obtained.strip())
e = parse(expected.strip())
assert e is not None
return o == e
def main():
obtained = sys.argv[1]
expected = sys.argv[2]
if obtained == '-':
obtained = sys.stdin.read()
else:
with open(obtained, 'r') as f:
obtained = f.read()
if expected == '-':
expected = sys.stdin.read()
else:
with open(expected, 'r') as f:
expected = f.read()
expected = expected.strip()
obtained = obtained.strip()
# print(expected)
# print(parse(expected))
# print(obtained)
# print(parse(obtained))
if check(expected=expected, obtained=obtained):
return 0
else:
sys.stdout.write('Wrong Answer\n')
return 1
if __name__ == '__main__':
sys.exit(main())
|
fa06ca0e9bd83aefd2ec1fce4b35b5e89b387c2b | sonu-python/Web-Scrabing-Using-scrapy | /webscrabing.py | 3,532 | 3.78125 | 4 | import urllib3
from bs4 import BeautifulSoup
# Create instance of urllib to get the data form browser
http = urllib3.PoolManager()
# Get the data using urls
request_data = http.request('GET', 'https://in.hotels.com/search.do?resolved-location=CITY%3A1506246%3AUNKNOWN%3AUNKNOWN&destination-id=1506246&q-destination=New%20York,%20New%20York,%20United%20States%20Of%20America&q-rooms=1&q-room-0-adults=2&q-room-0-children=0')
# check the status is ok or not
print(request_data.status)
# store the data
paga_data = request_data.data
# To deal with html content and formate the code use the BeautifulSoup
soup = BeautifulSoup(paga_data, features="html.parser")
# nested structure
html_page = soup.prettify()
print("\t \t Titel of the page \n\n")
print(soup.title.string)
print("\t \t Name of the hotels \n\n")
hotel_names = soup.find_all("h3", class_='p-name')
for hotel_name in hotel_names:
print(hotel_name.string)
print("\t \t Address of the hotels \n\n")
hotel_address = soup.find_all("address", class_="contact")
for hotel_addres in hotel_address:
print(hotel_addres.string)
print("\t \t Rating of the hotels \n\n")
hotel_ratings = soup.find_all("div" ,class_="reviews-box resp-module")
for hotel_ratins in hotel_ratings:
print(hotel_ratins.find('strong').string)
print("\t \t price of the hotels \n\n")
hotel_prices = soup.find_all("div", class_="price")
for hotel_price in hotel_prices:
if hotel_price.find('strong') is None:
print("Delete price:\t", hotel_price.find('del').string)
print("New price:\t", hotel_price.find('ins').string)
else:
print("Originale price:\t", hotel_price.find('strong').string)
# testing with scrapy
# def parse1(self, response):
# try:
# location = response.xpath("//div[@class='summary']/h1//text()").get()
# location = location.split(',')
# country = location[-1]
# for node in response.xpath("//div[@id='listings']/ol/li/article/section").getall():
# node = Selector(text=node)
# price = node.xpath("//aside/div[@class='price']/strong//text()").get()
# if price is not None:
# price
# else:
# price = node.xpath("//aside/div/ins//text()").get()
# yield {
# 'name': node.xpath("//div/h3/a//text()").get(),
# 'address': node.xpath("//div/address/span//text()").get(),
# 'rating': node.xpath("//div/div/div/strong//text()").get(),
# 'price' : price,
# 'country' : country,
# 'city' : city
# }
# except Exception as e:
# print(e)
# save it into database start code
# def parse(self, response):
# product = WebscrabingItem()
# for hole_page in response.xpath("//div[@id='listings']/ol/li/article/section").getall():
# div = Selector(text=hole_page)
# product['name'] = div.xpath("//div/h3/a//text()").get()
# product['address'] = div.xpath("//div/address/span//text()").get()
# product['rating'] = div.xpath("//div/div/div/strong//text()").get()
# product['price'] = div.xpath("//aside/div/strong//text()").get()
# yield product
# end code
# yield {
# 'name': div.xpath("//div/h3/a//text()").get(),
# 'address': div.xpath("//div/address/span//text()").get(),
# 'rating': div.xpath("//div/div/div/strong//text()").get(),
# 'price' : div.xpath("//aside/div/strong//text()").get()
# }
|
607cbe367b21dc77e4fcc52ba2311a5954afe50f | NCR7777/PythonLearning | /practice/practiceWeek2.py | 1,156 | 3.625 | 4 | # # 练习1
# from turtle import *
#
# penup()
# forward(-250)
# pendown()
# setheading(-40)
# width(25)
# pencolor("pink")
# for i in range(4):
# circle(40, 80)
# circle(-40, 80)
# circle(40, 80 / 2)
# forward(50)
# circle(16, 180)
# forward(40)
# done()
# # 练习2
# from turtle import *
# pensize(25)
# for i in range(4):
# fd(300)
# left(90)
# done()
# # 练习3
# from turtle import *
# pensize(25)
# for i in range(6):
# fd(200)
# left(60)
# done()
# # 练习4
# from turtle import *
# pensize(15)
# for i in range(9):
# fd(200)
# left(80)
# done()
# # 练习5
# import turtle as t
# t.pensize(2)
# for i in range(4):
# t.seth(90*i)
# t.fd(150)
# t.right(90)
# t.circle(-150, 45)
# t.goto(0,0)
# from turtle import *
# pensize(15)
# setheading(135)
# for i in range(4):
# forward(200)
# left(90)
# circle(200, 45)
# left(90)
# forward(200)
# left(45)
# done()
# # 测验1
# import turtle as t
# t.pensize(2)
# for i in range(8):
# t.fd(100)
# t.left(45)
# # 测验2
# import turtle as t
# t.pensize(2)
# for i in range(8):
# t.fd(150)
# t.left(135)
|
34285608be053d54a240f38590098d6b4196e8b4 | Carlos123b/X-Serv-Python-Multiplica | /mult.py | 222 | 3.96875 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
for i in range(1,11):
print("Tabla del " + str(i) + ":")
print("---------------------------")
for j in range(1,11):
print(i,"por",j,"es",i*j)
print("\n")
|
0d74013d13a6d16001e6cdae2986a24644ddb023 | ezvone/advent_of_code_2019 | /python/src/solve12.py | 3,077 | 3.5625 | 4 | import itertools
from math import gcd
from input_reader import read_moons
class Moon1D:
def __init__(self, x, v=0):
self.x = x
self.v = v
def __repr__(self):
return f'<Moon1D {self.x} -> {self.v}>'
def __eq__(self, other):
return (self.x == other.x and self.v == other.v)
def apply_gravity(self, other):
"""apply gravity on *both* moons"""
if self.x > other.x:
gravity = -1
elif self.x < other.x:
gravity = 1
else:
gravity = 0
self.v += gravity
other.v -= gravity
def apply_velocity(self):
self.x += self.v
class Moons1D:
def __init__(self, coords):
self.moons = [Moon1D(coord) for coord in coords]
def __repr__(self):
return f'<Moon1D {self.moons!r}>'
def __eq__(self, other):
return all(m1 == m2
for m1, m2 in itertools.zip_longest(self.moons, other.moons))
def apply_step(self):
for m1, m2 in itertools.combinations(self.moons, 2):
m1.apply_gravity(m2)
for m in self.moons:
m.apply_velocity()
class Moons3D:
def __init__(self, list_of_moon_coords):
xs, ys, zs = zip(*list_of_moon_coords)
self.dimensions = [Moons1D(dim_coords) for dim_coords in (xs, ys, zs)]
def apply_step(self):
for dim in self.dimensions:
dim.apply_step()
def get_moons(self):
coords_by_dim = [
[moon1d.x for moon1d in dim.moons]
for dim in self.dimensions]
coords_by_moon = zip(*coords_by_dim)
velocities_by_dim = [
[moon1d.v for moon1d in dim.moons]
for dim in self.dimensions]
velocities_by_moon = zip(*velocities_by_dim)
return zip(coords_by_moon, velocities_by_moon)
def get_total_energy(self):
total = 0
for (x, y, z), (vx, vy, vz) in self.get_moons():
potential = abs(x) + abs(y) + abs(z)
kinetic = abs(vx) + abs(vy) + abs(vz)
total += potential * kinetic
return total
def puzzle1():
moons = Moons3D(read_moons('day12input.txt'))
for _i in range(1000):
moons.apply_step()
return moons.get_total_energy()
def get_common_period(*periods):
rtn = 1
for p in periods:
rtn *= p // gcd(rtn, p)
return rtn
def puzzle2():
moon_coords = list(read_moons('day12input.txt'))
xs, ys, zs = zip(*moon_coords)
initial_moons_dims = [Moons1D(coords) for coords in (xs, ys, zs)]
moons_dims = [Moons1D(coords) for coords in (xs, ys, zs)]
dimension_repetition_periods = []
for moons, init_moons in zip(moons_dims, initial_moons_dims):
for i in itertools.count(1):
moons.apply_step()
if moons == init_moons:
dimension_repetition_periods.append(i)
break
return get_common_period(*dimension_repetition_periods)
if __name__ == "__main__":
assert puzzle1() == 7471
assert puzzle2() == 376243355967784
print('OK.')
|
2ded271d6edb4ab7060cc67d17fceb9aef8c0a19 | Kaustav-G23/Python_prog | /descending_list.py | 153 | 3.875 | 4 | lst = []
n = int(input("Enter the number of inputs: "))
for i in range(0, n):
ele = input()
lst.append(ele)
lst.sort(reverse = True)
print(lst)
|
343638e772118f92de1d7442e4f439b52fbc19ae | justindodson/PythonProjects | /CPR_Temps/resources/card_template.py | 3,410 | 3.53125 | 4 | import docx
from docx.shared import Pt
# class to create the Word templates
class Template:
# constructor takes a student object and file name as aruments.
def __init__(self, user, file_name):
self.user = user
self.file_name = file_name
self.document = docx.Document('../files/template.docx') # this is preset location and should not change
# TODO: Create option to import template from file location.
# this method creates the template in a Word document.
def create_template(self):
doc = self.document # set the document to a variable
# Space variables used for formating the page correctly
space1 = " " * 40
space2 = " " * 76
space3 = " " * 40
space4 = space1 + (" " * 28) + space2
space5 = " " * 165
space6 = space5 + (" " * 50)
# instantiate an Instructor object.
instructor = Instructor()
# Each doc.paragraphs operation below is removing the existing line at
# the index and replacing it with proper spacing and text data from the
# student object passed into the constructor.
doc.paragraphs[5].clear()
doc.paragraphs[5].add_run((" " * 5) + self.user.user)
doc.paragraphs[6].clear()
doc.paragraphs[6].add_run((" " * 5) + self.user.address1)
doc.paragraphs[7].clear()
doc.paragraphs[7].add_run((" " * 5) + self.user.address2)
doc.paragraphs[8].clear()
doc.paragraphs[8].add_run((" " * 5) + "{}, {} {}".format(self.user.city, self.user.state, self.user.zipcode))
doc.paragraphs[11].clear()
doc.paragraphs[11].add_run((" " * 5) + space1 + self.user.date + space2 + self.user.facility)
doc.paragraphs[12].clear()
doc.paragraphs[12].add_run((" " * 5) + space1 + self.user.exp_date + space2 + instructor.name)
doc.paragraphs[13].clear()
doc.paragraphs[13].add_run((" " * 5) + space4 + (" " * 4) + instructor.number)
doc.paragraphs[15].clear()
run = doc.paragraphs[15].add_run(space3 + self.user.user)
font = run.font
font.size = Pt(20)
doc.paragraphs[26].clear()
doc.paragraphs[26].add_run((" " * 135 )+ self.user.user)
doc.paragraphs[28].clear()
run = doc.paragraphs[28].add_run(space5 + self.user.facility)
font = run.font
font.size = Pt(9)
doc.paragraphs[29].clear()
run = doc.paragraphs[29].add_run(space5 + self.user.date)
font = run.font
font.size = Pt(9)
doc.paragraphs[30].clear()
run = doc.paragraphs[30].add_run(space5 + self.user.exp_date + (" " * 53 ) + str(self.user.course_hours))
font = run.font
font.size = Pt(9)
doc.paragraphs[31].clear()
doc.paragraphs[31].add_run((" " * 40) + instructor.number)
# saves the document to a folder on the desktop.
doc.save('../../../../cpr_templates/' + self.file_name + '.docx')
# TODO: Create a method for saving the documents to a specified location
# used to print the Word template to the console for development purposes in
# getting the formatting of the generated template correct.
def print_template():
doc = docx.Document('../files/template.docx')
counter = 0
for para in doc.paragraphs:
print(para.text + str(counter))
counter += 1
|
3b2ef800db7e55959d07634bcfbbb5d3823d88bb | BezK97/alx-higher_level_programming | /0x04-python-more_data_structures/2-uniq_add.py | 329 | 3.625 | 4 | #!/usr/bin/python3
def uniq_add(my_list=[]):
sum_unique = my_list[0]
n = 0
for i in range(1, len(my_list)):
for j in range(i):
if my_list[i] == my_list[j]:
n = 0
break
else:
n = my_list[i]
sum_unique += n
return (sum_unique)
|
412b8d4c072a90cca2e41d61100ce2d507d79de3 | kyokley/ProjEuler | /projEuler35.py | 1,830 | 3.53125 | 4 | #!/usr/bin/python
import projEulerFuncs
savedPrimes = projEulerFuncs.savedPrimes
isPrime = projEulerFuncs.isPrime
permuteRec = projEulerFuncs.permuteRec
def convertToList(num):
strNum = str(num)
lst = [int(x) for x in strNum]
return lst
def convertFromList(lst):
tempStr = ""
for i in lst:
tempStr += str(i)
return int(tempStr)
def rotateLst(num):
lst = []
strNum = str(num)
for i in xrange(len(strNum)):
newStr = ""
for j in xrange(i, i + len(strNum)):
idx = j
if idx >= len(strNum):
idx -= len(strNum)
newStr += strNum[idx]
lst.append(int(newStr))
return lst
def binary_search(x, lst):
if x > lst[-1]:
return False
elif x < lst[0]:
return False
if x == lst[0] or x == lst[-1]:
return True
if len(lst) == 1:
if x == lst[0]:
return True
else:
return False
else:
mid = len(lst)/2
if x < lst[mid]:
return binary_search(x, lst[:mid])
elif x > lst[mid]:
return binary_search(x, lst[mid+1:])
else:
return True
def binary(x, lst):
upper = len(lst)
lower = 0
while upper > lower:
mid = (upper + lower) / 2
if x == lst[mid]:
return mid
elif x < lst[mid]:
upper = mid - 1
elif x > lst[mid]:
lower = mid + 1
else:
return None
def main():
circPrimes = []
testPrimes = savedPrimes[:]
for i in xrange(len(testPrimes)):
if i >= len(testPrimes):
break
if not testPrimes[i]:
continue
print testPrimes[i]
rots = rotateLst(testPrimes[i])
for j in rots:
if not binary_search(j, savedPrimes):
break
else:
circPrimes += rots
for k in rots:
try:
idx = binary(k, testPrimes)
if idx:
testPrimes[idx] = 0
except:
pass
circPrimes = [i for i in circPrimes if i < 10**6]
for i in circPrimes:
print i
print len(circPrimes)
return circPrimes
if __name__ == "__main__":
main()
|
8011dbdefa7ee07880fcb1ae94e6f00becd95e6f | kyokley/ProjEuler | /projEuler29.py | 725 | 3.765625 | 4 | #!/usr/bin/python2.7
import math
from projEulerFuncs import print_timing
def main():
res1 = listPowers()
res2 = setPowers()
print res1, res2
@print_timing
def listPowers():
upperBound = 101
lowerBound = 2
results = []
for i in range(lowerBound, upperBound):
for j in range(lowerBound, upperBound):
power = math.pow(i,j)
if not power in results:
results.append(power)
return len(results)
@print_timing
def setPowers():
upperBound = 101
lowerBound = 2
results = set()
for i in range(lowerBound, upperBound):
for j in range(lowerBound, upperBound):
power = math.pow(i,j)
if not power in results:
results.add(power)
return len(results)
if __name__ == "__main__":
main()
|
d9c96086c62ec3cf38f630057c63120699c50b82 | kyokley/ProjEuler | /projEuler41.py | 444 | 3.5625 | 4 | #!/usr/bin/python
import projEulerFuncs
isPrime = projEulerFuncs.isPrime
permuteRec = projEulerFuncs.permuteRec
reverseDigitize = projEulerFuncs.reverseDigitize
def main():
results = []
for i in xrange(8, 2, -1):
lst = permuteRec(range(1, i))
lst = [reverseDigitize(x) for x in lst]
for j in lst:
if isPrime(j):
results.append(j)
results = sorted(results)
for i in results:
print i
if __name__ == "__main__":
main()
|
a5807fbb80791e78d47a6f7656f9e492414541cb | kyokley/ProjEuler | /projEuler45.py | 677 | 3.953125 | 4 | #!/usr/bin/python
def triangle():
n = 1
while 1:
yield (n * (n + 1)) / 2
n += 1
def pentagonal():
n = 1
while 1:
yield (n * (3*n - 1)) / 2
n += 1
def hexagonal():
n = 1
while 1:
yield n * (2*n -1)
n += 1
def main():
gen1 = hexagonal()
gen2 = pentagonal()
gen3 = triangle()
for i in xrange(144):
gen3.next()
while 1:
testNum1 = gen1.next()
testNum2 = gen2.next()
testNum3 = gen3.next()
while testNum2 < testNum1:
testNum2 = gen2.next()
while testNum3 < testNum1:
testNum3 = gen3.next()
print testNum1, testNum2, testNum3
if testNum1 == testNum2 and testNum1 == testNum3:
break
if __name__ == "__main__":
main()
|
9abd265657ff11174be5a9f761359716b8fbee32 | FelipeDasr/Python | /FundamentosPython/Interpolação.py | 301 | 3.65625 | 4 | from string import Template
nome, idade = "Ana", 30
print("Nome: %s Idade: %d %r %r" % (nome, idade, True, False))
print("Nome: {} Idade: {}".format(nome, idade))
print(f'Nome: {nome} Idade: {idade}')
s = Template('Nome: $nome Idade: $idade')
print(s.substitute(nome =nome, idade = idade)) |
4c75bfd29fdbb14b06271e3916ac6d2c43f81b83 | FelipeDasr/Python | /EstruturasDeControle/For04.py | 102 | 3.59375 | 4 | #!python
for i in range(1, 11):
if i == 6:
break
print(i)
else:
print("Fim") |
916af4c0e1759dfe3cc68c5e2a37cfbfdbf66352 | FelipeDasr/Python | /EstruturasDeControle/SimulandoOSwitch.py | 576 | 3.953125 | 4 | #!python
def getDiaSemana(dia):
dias = {
1: "Domingo",
2: "Segunda",
3: "Terca",
4: "Quarta",
5: "Quinta",
6: "Sexta",
7: "Sabado"
}
return dias.get(dia, "Dia Invalido")
def getTipoDia(dia):
if dia == 1 or dia == 7:
return "Fim de semana"
elif dia in range(2, 7):
return "Dia util"
else:
return "Dia Invalido"
if __name__ == "__main__":
for dia in range(1, 8):
print("{} eh {}".format(getDiaSemana(dia), getTipoDia(dia)))
|
5515124d6212b93ea990f6fa86662590cc5e6c71 | FelipeDasr/Python | /POO/Construtor.py | 310 | 3.53125 | 4 | #!python
class Data:
def __init__(self, dia = 1, mes = 1, ano = 1970):
self.dia = dia
self.mes = mes
self.ano = ano
def __str__(self):
return f"{self.dia}/{self.mes}/{self.ano}"
if __name__ == "__main__":
d1 = Data(ano = 2020)
print(d1) |
0df18f9f12d36d7db0025c31f648f644bb8b3e26 | JamesAsuraA93/CMU_Python | /assignment#3/third.py | 704 | 3.6875 | 4 | def prime(x):
m = x // 2
for i in range(2, m + 1):
if x % i == 0:
return False
return True
def compo(x):
lst = []
keep = x
start = 2
while x != 1:
if x % start != 0:
start += 1
if start % 2 == 0 and start != 2:
start += 1
x //= start
lst.append(start)
com = str(lst)[1:-1].replace(",", " *")
say = f"{keep} is " + com
return say
def factorize(x):
if x == 0:
return f"{x} is 0"
elif x == 1:
return f"{x} is 1"
if x > 1 and prime(x):
return f"{x} is prime"
elif x > 1 and (prime(x) == False):
say = compo(x)
return say
|
d5a49a42495246cfaa3c6870476d66b271a0e188 | ElineSophie/Smart_grid_alt | /cable.py | 556 | 3.59375 | 4 | from house import House
from battery import Battery
class Cable(object):
def __init__(self, house, battery):
self.house = house
self.battery = battery
self.route = route
def distance(self):
"""
Calculates a route between battery and house
according to the manhatten distance
"""
coordinates_h = House.get_coord()
coordinates_b = Battery.get_coord()
length = abs(coordinates_h[0] - coordinates_b[0]) + abs(coordinates_h[1] - coordinates_b[1])
return length
|
6eef9efebad6e30050ee372b6e4f3b3fbcc0ef79 | ElineSophie/Smart_grid_alt | /code/classes/battery.py | 443 | 3.6875 | 4 | class Battery(object):
def __init__(self, id, x_pos, y_pos, capacity):
"""
Initializes an Item
"""
self.id = id
self.x_battery = int(x_pos)
self.y_battery = int(y_pos)
self.capacity = float(capacity)
self.capacity_available = 0
def __str__(self):
return f"House {self.id} \nCoordinates (x,y): {self._x_house},{self._y_house}\nMaximum Output: {self.max_output}"
|
a5b02e9dce6abc5b3ff30a257bdab3caf371186d | KamalNaidu/Competitive_Programming | /Week-1/Day-2/Making_Change.py | 646 | 4 | 4 | #5 Making Change
def change_possibilities(amount, denominations):
"""
Computes the number of ways to make amount of money with coins of the available denominations.
Dynamic space efficient programming solution
"""
if (len(denominations) == 0) or (amount < 0):
return 0
results = [0 for x in range(amount+1)]
# Fill the entries for 0 value case (amount = 0)
results[0] = 1
for coin in denominations:
for next_amount in range(coin, amount + 1):
remainder = next_amount - coin
results[next_amount] += results[remainder]
return results[amount]
|
e40ea40cf7b6a96c8da57942ec7ec0d5029916f2 | foresthz/numpy_basics | /src/basic/np_genarray.py | 859 | 3.59375 | 4 | '''
Created on 2017-06-11
@author: btws
'''
import numpy as np
a = np.array([1,2])
print a.shape
b = np.array([ [1,2], [3,4] ])
print b.shape
c = np.array([[[1,2],[3,4]], [[5,6],[7,8]]])
print c.shape
d = np.zeros([3,3])
print d
# the type is object
e = np.array([[1,2],[3,4],[5,6,7]])
print e
print e.shape
# specify data type
f = np.array([1,2,3], dtype=np.int64)
print f
print f.dtype
g = np.array([1,2,3], dtype=np.int32)
print g
print g.dtype
h = np.array([1,2,3,4,5,6,7,8,9,10,11,12])
print h.shape, h
h.shape= 2,6
print h
# row, column
h.shape = 6,2
print h
# if col is set to be -1, the size of col would be calculated automatically
h.shape = 3,-1
print h
h.shape= [4,-3]
print h
h.shape=[2,-1]
print h
# not initialize the memory
i = np.empty((4,4), np.int)
print 'i -----'
print i
|
63ca4f68c05708f2482045d06775fa5d7d22ea55 | loudan-arc/schafertuts | /conds.py | 1,574 | 4.1875 | 4 | #unlike with other programming languages that require parentheses ()
#python does not need it for if-else statements, but it works with it
fake = False
empty = None
stmt = 0
f = 69
k = 420
hz = [60, 75, 90, 120, 144, 240, 360]
if k > f:
print(f"no parentheses if condition: {k} > {f}")
if (k > f):
print(f"with parentheses if condition: {k} > {f}")
if not k==hz[5]:
print(f"variable {k=}, not {hz[5]}")
#not can be used in place of != inequality
#or just evaluating if a statement is false and accept it if false
#for fstrings in pythong, using {var_name=}
#will print the variable name with the actual value of it directly'
#you must include the = sign
#otherwise it will just print value, period
#-------------------
#CONDITIONALS
if fake == False:
print(f"Fake == {fake}, empty == {empty}")
#evalutes to print the fact that it is false
if not empty:
print("empty will also evaluate to False")
#while empty is strictly set to None, which means using "if empty == None"
#will be skipped by the program
#if you use "if not empty"
#it will like on the above example, try to evaluate to false
#and None will evaluate to False in this specific way, so it will print
#the statement, it will not skip
if stmt == 0:
print("0 is also false")
else:
print("True bruh")
#What evals to False:
# * any variable = False
# * any variable = None
# * any variable = 0
# * any variable = '', (), [] which is an empty list or tuple
# * any variable = {} empty dict
#-------------------
#LOOPING
|
4afceabb3673acbe934061dd9888d06e0457a152 | dark5eid83/algos | /Easy/palindrome_check.py | 330 | 4.25 | 4 | # Write a function that takes in a non-empty string that returns a boolean representing
# whether or not the string is a palindrome.
# Sample input: "abcdcba"
# Sample output: True
def isPalindrome(string, i=0):
j = len(string) - 1 - i
return True if i >= j else string[i] == string[j] and isPalindrome(string, i + 1) |
a2e7a66a04141aaa578c4dc025bfc70d11b95e8f | xstonekingx/project_euler | /projectEuler21.py | 355 | 3.5 | 4 | def d(a):
divisor_sum = 0
for i in range(1, a):
if a%i == 0:
divisor_sum += i
return divisor_sum
total_sum = 0
#send numbers 1-10000 into d
#if it returns add it to total_sum
for a in range(1, 10001):
b = d(a)
if d(b) == a and a!=b:
total_sum = total_sum + a
print (total_sum)
|
7c8c84d00d944b074c6627731c10762658d581d5 | farshadnp/Data-Mining-Exercises-Code | /Ex1/03.py | 506 | 3.671875 | 4 | import keyboard
while True:
print("_____________________________Tamrin #3 _________________________________\n\n")
MySentence = input("Please enter a long sentence : ")
MySentence_Splited = MySentence.split(" ")
print("\nBe soorat List kalamate jomle vared shode : ",MySentence_Splited)
print("Words totall: ",len(MySentence_Splited))
print("\n___________________________Farshad NematPour ___________________________\n\n")
keyboard.wait('q')
keyboard.send('ctrl+6')
|
7d0101020d591a15c25bae422b9c7702cc6fdd60 | AdamMartinCote/IntroductionToAI | /tp1/src/state.py | 3,420 | 3.53125 | 4 | from typing import List
import numpy as np
from tp1.src.car import Car
class State:
def __init__(self, pos, c=None, d=None, previous_state=None):
"""
Contructeur d'un état initial
pos donne la position de la voiture i (première case occupée par la voiture);
"""
self.pos = np.array(pos, dtype=np.int64)
"""
c, d et prev permettent de retracer l'état précédent et le dernier mouvement effectué
"""
self.c = c
self.d = d
self.prev = previous_state
self.h = 0
try:
self.nb_moves = previous_state.nb_moves + 1
except AttributeError:
self.nb_moves = 0
def move(self, c: int, d: int) -> 'State':
"""
Constructeur d'un état à partir mouvement (c,d)
:param c: index of the car [0, nb_cars - 1]
:param d: direction of the move [-1, 1]
:return: State object
"""
new_positions = np.copy(self.pos)
new_positions[c] += d
return State(new_positions, c, d, self)
def success(self):
""" est il final? """
return self.pos[0] >= 4
def estimee1(self) -> int:
"""
Estimation du nombre de coup restants
"""
red_car_position = self.pos[0]
goal_position = 4
return int(goal_position - red_car_position)
def estimee2(self, free_pos: np.ndarray, cars: List[Car]) -> int:
"""
Estimation du nombre de blocage entre l'auto rouge et la sortie
"""
red_car = cars[0]
space_after_red_car = self.pos[0] + red_car.length
impediments = 0
for i in range(space_after_red_car, len(free_pos[0])):
if not free_pos[red_car.move_on_index][i]:
impediments += 1
return impediments * 2 + self.estimee1()
def estimee3(self, free_pos: np.ndarray, cars: List[Car]) -> int:
"""
Heuristique de prédiction 3
on utilise comme valeur le nombre d'autos qui empêchent l'auto rouge d'avancer
"""
space_after_red_car = self.pos[0] + cars[0].length
impediments = 0
for i, car in enumerate(cars):
if car.is_horizontal or \
car.move_on_index < space_after_red_car:
continue
space_after_current_car = self.pos[i] + car.length
space_before_current_car = self.pos[i] - 1
def increment_if_inbound_and_occupied(space, col) -> bool:
return 0 <= space < 6 and not free_pos[space][col]
impediments += increment_if_inbound_and_occupied(space_after_current_car, car.move_on_index)
impediments += increment_if_inbound_and_occupied(space_before_current_car, car.move_on_index)
return impediments + self.estimee2(free_pos, cars)
def __eq__(self, other: 'State') -> bool:
if not isinstance(other, State):
return NotImplemented
if len(self.pos) != len(other.pos):
raise Exception("les états n'ont pas le même nombre de voitures")
return np.array_equal(self.pos, other.pos)
def __hash__(self) -> int:
h = 0
for i in range(len(self.pos)):
h = 37 * h + self.pos[i]
return int(h)
def __lt__(self, other: 'State') -> bool:
return (self.nb_moves + self.h) < (other.nb_moves + other.h)
|
a767f1479e709878cdfdd0705f3e1ddb0e5d7bfc | xjy611/grokking_algorithms | /chapter1/binary_search.py | 734 | 4.03125 | 4 | # _*_ coding : UTF-8 _*_
# 开发人员 : 16092
# 开发时间 : 2020/7/8 13:58
# 文件名称 : binary_search.PY
# 开发工具 : PyCharm
def binary_search(list, item):
"""
二分查找法
Args:
list: 需要查找的列表
item:需要查找的元素
Returns:
mid:元素索引
None:查找不到返回空
"""
low = 0
high = len(list) - 1
while low <= high:
mid = (low + high) // 2
guess = list[mid]
if guess == item:
return mid
if guess < item:
low = mid + 1
else:
high = mid - 1
return None
my_list = [1, 3, 5, 7, 9]
print(binary_search(my_list, 3))
print(binary_search(my_list, 2))
|
6849ca836d10f111664ba453e7798bc36dc40128 | Ursulinocosta/circunferencia | /11/circunferencia.py | 196 | 3.859375 | 4 | raio = float(input('Entre com o valor do raio para obter a circunferencia do circulo: '))
circunferencia = 2 * 3.14 * raio
print("A circunferencia do circulo: {:.2f}".format(circunferencia)) |
529002f634849ccd180872ea5dc4e514bcd2fd0a | Prateek1992/Coding_Projects | /sequenceOperators.py | 375 | 4.09375 | 4 | string1 = "he is "
string2 = "probably "
string3 = "pining "
string4 = "for the "
string5 = "fjords"
print(string1 + string2 + string3 + string4 + string5) # string concatenation
print("he is " "probably " "pining " "for the " "fjords")
print("Hello \n"*(2*2)) # strings can be multiplied in python
today = "monday"
print("day" in today) # True
print("Tue" in today) #False |
691d59f03de0cb41fab482f3f7387a5d8cbb1b00 | alexander-mc/Other_Projects | /01_Python_Projects/01_Hangman_Game/hangman.py | 2,709 | 3.953125 | 4 | # Python 2.17.13
# Project name: Hangman!
# Project details: Guess the word in 8 tries
# Course: MITx 6.001x
# -----------------------------------
# Helper code
import random
import string
WORDLIST_FILENAME = "/Users/Alexander/Documents/Coding/0_GitHub_Portfolio/Other_Projects/01_Python_Projects/01_Hangman_Game/words.txt"
def loadWords():
print "Loading word list from file..."
inFile = open(WORDLIST_FILENAME, 'r', 0)
line = inFile.readline()
wordlist = string.split(line)
print " ", len(wordlist), "words loaded. \n\
"
return wordlist
def chooseWord(wordlist):
return random.choice(wordlist)
# end of helper code
# -----------------------------------
wordlist = loadWords()
def isWordGuessed(secretWord, lettersGuessed):
for i in secretWord:
if i not in lettersGuessed:
return False
return True
def getGuessedWord(secretWord, lettersGuessed):
stringAns = secretWord
for i in range(len(secretWord)):
if secretWord[i] not in lettersGuessed:
stringAns = stringAns.replace(secretWord[i],'_ ')
return stringAns
def getAvailableLetters(lettersGuessed):
import string
alphab = string.ascii_lowercase
lLeft = ""
for i in alphab:
if i not in lettersGuessed:
lLeft = lLeft + i
return lLeft
def hangman(secretWord):
numGuesses = 8
lettersGuessed = []
print 'Welcome to the game, Hangman! \n\
I am thinking of a word that is '+str(len(secretWord))+' letters long. \n\
'
while numGuesses > 0:
print 'You have '+str(numGuesses)+' guesses left. \n\
Available letters: '+ getAvailableLetters(lettersGuessed)
g = raw_input('Please guess a letter:')
g = g.lower()
if g not in getAvailableLetters(lettersGuessed):
print 'Oops! You\'ve already guessed that letter: '+getGuessedWord(secretWord,lettersGuessed)+'\n\
'
else:
lettersGuessed.append(g)
if g in secretWord:
print 'Good guess: '+getGuessedWord(secretWord,lettersGuessed)+'\n\
'
if isWordGuessed(secretWord, lettersGuessed) == True:
print 'Congratulations, you won!'
break
else:
numGuesses -= 1
print 'Oops! That letter is not in my word: '+getGuessedWord(secretWord,lettersGuessed)+'\n\
'
if numGuesses == 0:
print 'Sorry, you ran out of guesses. The word was '+str(secretWord)+'.'
secretWord = chooseWord(wordlist).lower()
hangman(secretWord)
|
b38851862e7c1546740708b72ca0b4dcf51efe0c | alexander-mc/Other_Projects | /04_MIT_6.001x_Course/Lessons/L6P10.py | 432 | 3.625 | 4 | animals = { 'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati']}
animals['d'] = ['donkey']
animals['d'].append('dog')
animals['d'].append('dingo')
a = {'l': []}
b = {}
def biggest(aDict):
count = 0
key = ""
if aDict == {}:
return None
for k in aDict:
if len(aDict[k]) >= count:
count = len(aDict[k])
key = k
return key
print biggest(b) |
280aa4ae96a202fe41ca16459456f9527ee9b4ff | alexander-mc/Other_Projects | /04_MIT_6.001x_Course/Problem_Sets/Problem_Set_2/PS2Q1.py | 578 | 3.875 | 4 | balance = 4213
annualInterestRate = .2
monthlyPaymentRate = .04
monthlyInterestRate = annualInterestRate/12
totalPaid = 0
for m in range(1,13):
print 'Month:',m
print 'Minimum monthly payment:', float("{0:.2f}".format(balance*monthlyPaymentRate))
totalPaid += balance*monthlyPaymentRate
balance -= balance*monthlyPaymentRate
balance *= monthlyInterestRate+1
print 'Remaining balance:', float("{0:.2f}".format(balance))
print 'Total paid:', float("{0:.2f}".format(totalPaid))
print 'Remaining balance:', float("{0:.2f}".format(balance)) |
19d96e01d939f855d225f07dd20d5df3a2d21993 | rickychau2780/practicePython | /exercise9.py | 417 | 4.03125 | 4 | import random
num = random.randint(1,9)
count = 0
while True:
guess = input("What is your guess? (0-9): ")
if guess == "exit":
break
guess = int(guess)
count += 1
if guess > num:
print("it is too high!")
elif guess < num:
print("it is too low!")
else:
print("it is correct. It took you " + str(count) + " tries!")
count = 0
|
3b58e7105a1d46c41da745ee2f52a25d8dfcce88 | ngophuongthuy/NgoPhuongThuybaitap | /Matplotlib4.py | 302 | 3.734375 | 4 | import matplotlib.pyplot as plt
import numpy as np
divisions = ["Python","PHP","CSS","JAVA","C++"]
divisions_average_marks = [92,76,9,67,51]
plt.bar(divisions, divisions_average_marks,color='pink')
plt.title("Bar Graph")
plt.xlabel("ngôn ngữ lập trình")
plt.ylabel("tỷ lệ")
plt.show() |
a5783a5103f9f7873bf1e412b65b0666cf532fcb | nestorcolt/smartninja | /curso_python/clase_006/player_manager.py | 528 | 3.734375 | 4 | """
This module holds the abstract class for player data model
All players will inhered from this class
"""
class Player:
def __init__(self, first_name, last_name, height_cm, weight_kg):
self.first_name = first_name
self.last_name = last_name
self.height_cm = height_cm
self.weight_kg = weight_kg
def weight_to_lbs(self):
pounds = self.weight_kg * 2.20462262
return pounds
#############################################################################################
|
de6efec5a642dc7843543d771395385f0ad85c33 | doudouhhh/Stanford_dogs-classification-by-CNN | /Rename.py | 596 | 3.734375 | 4 | # coding:utf-8
import os
import sys
def rename():
path=input("请输入路径:")
name=input("请输入开头名:")
startNumber='1'
fileType='.jpg'
print("正在生成以"+name+startNumber+fileType+"迭代的文件名")
count=0
filelist=os.listdir(path)
for files in filelist:
Olddir=os.path.join(path,files)
if os.path.isdir(Olddir):
continue
Newdir=os.path.join(path,name+'_'+str(count+int(startNumber))+fileType)
os.rename(Olddir,Newdir)
count+=1
print("一共修改了"+str(count)+"个文件")
rename()
|
9adde924d98de1abadf6249fbb952124f337114b | naranundra/python3 | /dasgal3.py | 324 | 3.78125 | 4 | # хүний нэр өгөгдсөн бол 2 оос дээш а үсэг орсон эсэхийг шалга
ner = input("нэр ээ оруулна уу:")
c = ner.count("a")
print(c)
ner = input("нэр ээ оруулна уу:")
c = ner.count("a")
if c>2:
print("2-оос олон а үсэг орсон") |
70547602bad5568d71dd4a664cc5324af9e5b55c | gvimpy/Abhinav | /direction = input ("choose operation mul.py | 1,356 | 3.96875 | 4 | direction = input ("choose operation mult add sub div:")
if direction == "add":
ans = input ("Number One:")
rad = input ("Number Two:")
result = int(ans) + int(rad)
print (result)
if direction == "mult":
an = input ("Number One:")
ra = input ("Number Two:")
ww = int(an) * int(ra)
print (ww)
if direction == "sub":
a = input ("Number One:")
r = input ("Number Two:")
Thang = int(a) - int(r)
print (Thang)
if direction == "div":
abhinavscool = input ("Number One:")
abhinavsuck = input ("Number Two:")
hi = int(abhinavscool) / int(abhinavsuck)
print (hi)
would = input ("Would you like to continue:")
if would == "yes":
direction = input ("choose operation mult add sub div:")
if direction == "add":
ans = input ("Number One:")
rad = input ("Number Two:")
result = int(ans) + int(rad)
print (result)
if direction == "mult":
an = input ("Number One:")
ra = input ("Number Two:")
ww = int(an) * int(ra)
print (ww)
if direction == "sub":
a = input ("Number One:")
r = input ("Number Two:")
Thang = int(a) - int(r)
print (Thang)
if direction == "div":
abhinavscool = input ("Number One:")
abhinavsuck = input ("Number Two:")
hi = int(abhinavscool) / int(abhinavsuck)
print (hi)
if would == "no":
print ("See you later then.") |
7ce3fe03de726250fbad7573e0f6a12afa5fcc4a | AshishKadam2666/Daisy | /swap.py | 219 | 4.125 | 4 | # Taking user inputs:
x = 20
y = 10
# creating a temporary variable to swap the values
temp = x
x = y
y = temp
print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}'.format(y))
|
7186b81599cf00acbf1f1dd1436fc21d467abfa2 | kunigami/blog-examples | /huffman/simple_queue_test.py | 1,130 | 3.8125 | 4 | import unittest
from simple_queue import Queue
class QueueTest(unittest.TestCase):
def test_operations(self):
q = Queue()
self.assertTrue(q.is_empty())
self.assertEqual(q.front(), None)
self.assertEqual(q.pop(), None)
q.push(1)
self.assertFalse(q.is_empty())
self.assertEqual(q.front(), 1)
q.push(2)
self.assertEqual(q.front(), 1)
val = q.pop()
self.assertEqual(val, 1)
self.assertEqual(q.front(), 2)
val = q.pop()
self.assertEqual(val, 2)
self.assertTrue(q.is_empty())
def test_initialized_queue(self):
init = [1, 2, 3, 4, 5]
q = Queue([1, 2, 3, 4, 5])
arr = get_array(q)
self.assertEqual(arr, init)
def test_multiple_queues(self):
q1 = Queue()
q2 = Queue()
q1.push(1)
q2.push(2)
self.assertEqual(get_array(q1), [1])
self.assertEqual(get_array(q2), [2])
def get_array(q):
arr = []
while not q.is_empty():
arr.append(q.pop())
return arr
if __name__ == '__main__':
unittest.main()
|
98ca8affd941f3bafcd9e2b9ae8fa35dfdf89166 | hchang18/nonparametric-methods | /exchangeability_test.py | 2,105 | 3.5 | 4 | # exchangeability_test.py
import numpy as np
def exchangeability_test(x, y, size):
"""
Calculate the variance test.
This test tests the null hypothesis that two distributions on X and Y have
same variance. This time, the assumptions on medians are relaxed, but it
requires the existence of the 4th moment.
Parameters
----------
X : array of floats
Y : array of floats
Returns
-------
statistic : float
The difference between the variances of X except for xi and variances
of Y except for yi
p_value : float
THe p-value for the two-sided test
"""
ab = []
for i in range(size):
ab.append((x[i], y[i], min(x[i], y[i]), max(x[i], y[i]))) # x, y, a, b
ab.sort(key=lambda x: x[2])
r = []
for i in range(size):
if ab[i][0] == ab[i][2]:
r.append(1)
else:
r.append(-1)
d = []
T_j = []
for j in range(size):
d_j = []
for i in range(size):
if ab[j][3] >= ab[i][3] > ab[j][2] >= ab[i][2]:
d_j.append(1)
else:
d_j.append(0)
t = [x * y for x, y in zip(r, d_j)]
T_j.append(sum(t))
d.append(d_j)
A_obs = sum([t ** 2 for t in T_j]) / (size ** 2)
print(A_obs)
r_n = []
possible_outcomes = 2 ** size
for i in range(possible_outcomes):
binary = bin(i)[2:].zfill(size)
r = list(map(int, binary))
r = [-1 if x == 0 else x for x in r]
r_n.append(r)
A = []
T = []
for i in range(possible_outcomes):
for j in range(size):
t = [x * y for x, y in zip(r_n[i], d[j])]
T.append(sum(t))
A.append(sum([t ** 2 for t in T]) / (size ** 2))
alpha = 0.95
m = 2 ** size - np.floor(2 ** size * alpha)
print(A[int(m)])
# test at 5% confidence level
# testing exchangeability
print("exchangeability test")
if A_obs > A[int(m)]:
print("reject H0 that x and y are exchangeable")
else:
print("cannot reject H0")
return A_obs
|
ef3a0ab8ca46680697e312f31094b9ce455a37bb | Choe-Yun/Algorithm | /LeetCode/문자열 다루기/02.Reverse_String.py | 746 | 4.15625 | 4 | ### 문제
# Write a function that reverses a string. The input string is given as an array of characters s.
# 문자열을 뒤집는 함수를 작성해라. 인풋값은 배열이다
### Example 1
# Input: s = ["h","e","l","l","o"]
# Output: ["o","l","l","e","h"]
###### code
from typing import List
# 투 포인터를 이용한 스왑 방식
class Solution:
def reverseString(self, s: List[str]) -> None:
left, right = 0, len(s) - 1
while left < right:
s[left], s[right] = s[right], s[left]
left += 1
right -= 1
# 파이싼의 reverse() 함수를 이용한 방식
from typing import List
class Solution:
def reverseString(self, s: List[str]) -> None:
s.reverse() |
539f504f6b4ec2b2e07d8900fc7290d0c7ee3f39 | seangrant82/AI | /graphs/streamlit/streamlit_newNode_txtInput.py | 1,187 | 3.59375 | 4 | import streamlit as st
from neo4j import GraphDatabase
from py2neo import graph
# Add your Neo4j database credentials here
uri = "bolt://localhost:7687"
user = "neo4j"
password = "password"
# Create a driver instance to connect to the Neo4j database
driver = GraphDatabase.driver(uri, auth=(user, password))
# Create a function that will create a node in the database
def create_node(tx, label, properties):
query = f"MERGE (n:{label} {properties})"
tx.run(query)
# Create the main app
def main():
st.title("Neo4j Node Creator")
label = st.text_input("Enter node label:")
properties = st.text_area("Enter node properties (in JSON format-e.g. {date: '1/1/11', notes: 'added new feature'}):")
if st.button("Create node"):
with driver.session() as session:
session.write_transaction(create_node, label, properties)
st.success("Node created successfully!")
if st.button('Get all nodes'):
cypher = "MATCH (n) RETURN n"
result =graph.run(cypher)
#Present nodes
st.write("All nodes:")
st.write(list(result))
if __name__ == '__main__':
main() |
00911f42a052a0a3a3b3f2ace57d324657fd8758 | valekovski/ssts | /python/vaje_resitve3.py | 1,689 | 3.625 | 4 | # 1. Fibonaccijevo zaporedje
st_clenov = 20 # št. členov zaporedja, ki jih bomo generirali
predzadnji_clen = 1 # inicializiramo začetna dva člena
zadnji_clen = 1
print(predzadnji_clen, " ", end="")
print(zadnji_clen, " ", end="")
# odštejemo 2, ker smo prva dva člena že izpisali
for i in range(st_clenov - 2):
nasl_clen = predzadnji_clen + zadnji_clen
print(nasl_clen, " ", end="")
# pripravimo števila za naslednjo iteracijo
predzadnji_clen = zadnji_clen
zadnji_clen = nasl_clen
# 2. Tekmovanje iz poštevanke
tekmovalec1_tocke = 0
tekmovalec2_tocke = 0
# igra se ponavlja, dokler absolutna razlika med točkama tekmovalcev ni vsaj 2
while (abs(tekmovalec1_tocke - tekmovalec2_tocke) < 2):
# dobra praksa narekuje, da vsako spremenljivko pred uporabo inicializiramo
faktor1 = 0
faktor2 = 0
produkt = 0
faktor1 = int(input("Tekmovalec 1, prvi faktor? "))
faktor2 = int(input("Tekmovalec 1, drugi faktor? "))
produkt = int(input("Tekmovalec 2, produkt?"))
# pazite na uporabo primerjalnega operatorja == in ne priredilnega =
if (produkt == (faktor1*faktor2)):
tekmovalec2_tocke += 1
print()
faktor1 = int(input("Tekmovalec 2, prvi faktor? "))
faktor2 = int(input("Tekmovalec 2, drugi faktor? "))
produkt = int(input("Tekmovalec 1, produkt?"))
if (produkt == (faktor1*faktor2)):
tekmovalec1_tocke += 1
# po vsaki iteraciji izpišemo trenutni rezultat
print()
print("Trenutni rezultat: ", tekmovalec1_tocke, " : ", tekmovalec2_tocke)
print()
# na koncu še pohvalimo zmagovalca
if (tekmovalec1_tocke > tekmovalec2_tocke):
print("Bravo prvi! Drugi, cvek!")
else:
print("Bravo drugi! Prvi, cvek!")
|
c2329fb310cf7ab43c20f56ccb00b0bdf6bb3ae4 | CullenMar/205proj1section2 | /project_1.py | 1,244 | 3.625 | 4 | # this is a comment, yo -> https://github.com/CullenMar/205proj1section2
from PIL import Image
def median( inputList ): #gets median value from an array
a = 0
while a < 8:
if (inputList[a] > inputList[a + 1]):
b = inputList[a]
inputList[a] = inputList[a + 1]
inputList[a + 1] = b
if (a > 1):
a -= 2
a += 1
return (inputList[4])
imageList = []
for z in range (1, 10):
im1 = Image.open("Images/" + str(z) + ".png")
imageList.append(im1)
width1, height1 = im1.size #gets width and height values
finalImage = Image.new("RGB", (width1, height1), "RED")
pixel = finalImage.load()
redList = []
greenList = []
blueList = []
for x in range (width1): #analyzes each pixel and paints median value to new image
for y in range (height1):
for myImage in imageList:
red1, green1, blue1 = myImage.getpixel((x, y))
redList.append(red1)
greenList.append(green1)
blueList.append(blue1)
pixel[x, y] = (median(redList), median(greenList), median(blueList))
del redList[:]
del greenList[:]
del blueList[:]
finalImage.save("Images/finalImage.png") #saves result to a png file |
ac298bd148566e21a3868973a35dab63d7ea8b47 | dgolov/autoru_parser | /utils.py | 1,200 | 3.640625 | 4 | from parser import ParserSlugs
def convert_entered_data_to_int(message_to_input):
""" Конвертирует вводимое число в integer
В случае ошибки обрабатывает исключение и возвращает 0
:param message_to_input: - число в текстовом формате
:return: - Integer
"""
try:
response = int(input(message_to_input))
except ValueError:
response = 0
return response
def write_cars_to_file(cars_list):
""" Запись спарсенных данных (марок и серий) в текстовый файл
:param cars_list: - список строк полученных в результате парсинга
"""
with open('cars.txt', 'w') as file:
file.write('') # Удаление данных из файла перед новой записью
with open('cars.txt', 'a') as file:
for line_for_write in cars_list:
file.write(line_for_write + '\n')
if __name__ == '__main__':
parser = ParserSlugs()
data_list = parser.run_parsing()
if data_list:
write_cars_to_file(cars_list=data_list)
|
bb155d4d67a7611506849ea6160074b6fec2d01f | kalpitthakkar/daily-coding | /problems/Jane_Street/P5_consCarCdr.py | 1,420 | 4.125 | 4 | def cons(a, b):
def pair(f):
return f(a, b)
return pair
class Problem5(object):
def __init__(self,
name):
self.name = name
# The whole idea of this problem is functional programming.
# Use the function cons(a, b) to understand the functional
# interface required to write functions car(f) and cdr(f).
# car/cdr takes a function as input => as cons(a,b) returns a
# function. The returned function takes a function as input,
# which has two arguments like cons => this inner function
# like cons can be made by us according to whether it is called
# from car or cdr.
def solver_car(self, f):
def first(x, y):
return x
return f(first)
def solver_cdr(self, f):
def last(x, y):
return y
return f(last)
def __repr__(self):
return "Problem #5 [Medium]: " + self.name + "\nThis problem was asked by Jane Street"
if __name__ == '__main__':
p = Problem5('Return first element of pair using car and second using cdr')
print(p)
x = cons(2, cons(cons(3, 4), 5))
car = getattr(p, 'solver_car')
cdr = getattr(p, 'solver_cdr')
print("Input: x = cons(2, cons(cons(3, 4), 5))")
print("Solution from solver for car function: car(x) = {}".format(car(x)))
print("Solution from solver for cdr function: cdr(cdr(x)) = {}".format(cdr(cdr(x))))
|
55bbfa30507bc3fb63ab5385aa33f80b827e0395 | kalpitthakkar/daily-coding | /problems/Amazon/P12_numberOfSteppingWays.py | 927 | 3.8125 | 4 | class Problem12(object):
def __init__(self,
name):
self.name = name
def solver_dp(self, N, steps=[1,2]):
dp = [0] * (N + 1)
dp[0] = 1
for i in range(1, N+1):
val = 0
for j in steps:
if (i - j) >= 0:
val += dp[i-j]
dp[i] = val
return dp[N]
def __repr__(self):
return "Problem #12 [Hard]: " + self.name + "\nThis problem was asked by Amazon"
if __name__ == '__main__':
p = Problem12('Given number of steps and allowed steps at a time, find number of ways to climb')
print(p)
N = input("Enter the number of steps: ")
N = int(N)
x = input("Enter the steps allowed (space separated): ")
x = [int(x) for x in x.split()]
num_ways = getattr(p, 'solver_dp')
print("Number of ways in which we can climb the steps: {}".format(num_ways(N, x)))
|
11b8b5e7175b685c7f3718409d22ce34322dbb11 | mariagarciau/EntregaPractica3 | /ejercicioadivinar.py | 1,884 | 4.125 | 4 | """
En este desafío, probamos su conocimiento sobre el uso de declaraciones
condicionales if-else para automatizar los procesos de toma de decisiones.
Juguemos un juego para darte una idea de cómo diferentes algoritmos para el mismo
problema pueden tener eficiencias muy diferentes.
Deberás desarrollar un algoritmo que seleccionará aleatoriamente un número entero
entre 1 y 15.
El usuario deberá ser adivinando, deberemos permanecer en la condición hasta
encontrar el número seleccionado.
Además nos deberá dar una pista( si es mayor o menor) en cada intento.
Ahora desarrolla el código para un número del 1 al 300, sabiendo que no deberías
necesitar más de 9 intentos.
"""
import random
numeroRandom = random.randint(1,15)
numeroIntroducido = int(input("Introduzca un número entre 1 y 15: "))
while numeroIntroducido != numeroRandom:
if numeroRandom < numeroIntroducido:
print("El número que debe adivinar es menor")
numeroIntroducido = int(input("Introduzca un número entre 1 y 15: "))
elif numeroRandom > numeroIntroducido:
print("El número que debe adivinar es mayor")
numeroIntroducido = int(input("Introduzca un número entre 1 y 15: "))
print("Has acertado el número")
numeroRandom2 = random.randint(1,300)
numeroIntroducido2 = int(input("Introduzca un número entre 1 y 300: "))
intentos : int
intentos = 1
while numeroIntroducido2 != numeroRandom2:
intentos +=1
if intentos>9:
break
elif numeroRandom2 < numeroIntroducido2:
print("El número que debe adivinar es menor")
numeroIntroducido2 = int(input("Introduzca un número entre 1 y 300: "))
elif numeroRandom2 > numeroIntroducido2:
print("El número que debe adivinar es mayor")
numeroIntroducido2 = int(input("Introduzca un número entre 1 y 300: "))
if intentos<9:
print("Has acertado el número")
|
4069cdb0e12ef67a163ace35f8869c91a1c3dcad | mdcoolcat/CandB | /B/python/matrix_simple.py | 1,744 | 3.734375 | 4 | # simple matrix manipulation
# from CareerCup Ch1
import sys
import os
import commands
import re
from sets import Set
def show(m):
for row in m:
print row
# rotate a N*N matrix by 90 degrees in place
def rotate_right_90(m):
if len(m) != len(m[0]):
raise ValueError('not N*N')
show(m)
n = len(m)
# rotate layer by layer, from outmost
for layer in range(n / 2):
print 'layer ' + str(layer) + '****'
start = layer
end = n - 1 - layer
j = start
while j < end:
offset = j - start
tmp = m[start][j]
m[start][j] = m[end -offset][start] # left bottom->top
m[end - offset][start] = m[end][end - offset] # right bottom->left bottom
m[end][end - offset] = m[j][end] # right top->bottom
m[j][end] = tmp
j += 1
show(m)
return m
# if an element in an MxN matrix is 0, its entire row and col
# is set to 0
def set_zero(m):
show(m)
rows = Set()
cols = Set()
# 1st loop flag the row & col index
for i in range(len(m)):
for j in range(len(m[0])):
if m[i][j] == 0:
rows.add(i)
cols.add(j)
# 2nd loop set 0
for i in range(len(m)):
for j in range(len(m[0])):
if (i in rows) or (j in cols):
m[i][j] = 0
print
show(m)
def main():
matrix = [ [1, 2, 3, 3],
[4, 5, 6, 3],
[7, 8, 9, 0],
[0, 1, 2, 3] ]
try:
set_zero(matrix)
#result = rotate_right_90(matrix)
#show(result)
except ValueError, e:
print 'Illegal argument: ' + str(e)
if __name__ == '__main__':
main()
|
85aa86cdbb15c78367f9eeef853e848dcf517054 | mdcoolcat/CandB | /B/python/linked_list.py | 4,405 | 4.0625 | 4 | # Implementation of single linked_list
# Danielle Mei
import sys
import os
import commands
import re
class Node(object):
def __init__(self, key):
self.key = key
self.next = None
def __repr__(self):
return '%r' % (self.key)
def __str__(self):
return str(self.key)
def __cmp__(self, other):
return self.key - other.key
class Linked_list(object):
def __init__(self):
self.__head = None
self.__tail = None
self.__len = 0
def size(self):
return self.__len
# **** get ****
def get_first(self):
return self.__head
def get_last(self):
return self.__tail
# return index of the element, -1 if not found
def index_of(self, element):
if self.__len == 0:
return -1
index = 0
n = self.__head
while n is not None and n is not element:
n = n.next
index += 1
if n is None:
return -1
return index
# **** add ****
# append a node to list end. O(1)
def append(self, element):
if self.__len == 0:
self.__head = element
self.__tail = element
else:
self.__tail.next = element
self.__tail = element
self.__len += 1
# prepend a node O(1)
def prepend(self, element):
if self.__len == 0:
self.__head = element
self.__tail = element
else:
element.next = self.__head
self.__head = element
self.__len += 1
# insert a node as sorted (natual order of key), O(n)
def insert(self, element):
if (self.__len == 0) or \
(self.__len > 0 and self.__head >= element):
self.prepend(element)
else:
n = self.__head
while n.next is not None and n.next < element:
n = n.next
element.next = n.next
n.next = element
if element.next is None:
self.__tail = element
self.__len += 1
# ***** remove ****
def remove_first(self):
if self.__len == 0:
return None
ele = self.__head
self.__head = self.__head.next
if self.__len == 1: # it's the only element
self.__tail = None
self.__len -= 0
return ele
def remove_last(self):
if self.__len == 0:
return None
elif self.__len == 1:
ele = self.__head
self.__head = None
self.__tail = None
self.__len = 0
return ele
else:
# find the new last... should impl as double list to lower time
ele = self.__tail
prev = self.__head
while prev.next is not self.__tail:
prev = prev.next
prev.next = None
self.__tail = prev
self.__len -= 1
return ele
# delete node
# return the deleted node, or None if not found
def remove(self, element):
if self.__len == 0:
return None
n = self.__head
while n.next is not None and n.next is not element:
n = n.next
if n.next is None:
return None
ele = n.next # the one will be deleted
n.next = ele.next
if ele.next is None:
self.__tail = n
self.__len -= 1
return ele
# print the list
def __str__(self):
s = str()
n = self.__head
while n is not None:
s = s + str(n.key) + ' -> '
n = n.next
return s
# Simple provided test() function used in main() to print
# what each function returns vs. what it's supposed to return.
def test(got, expected):
if got == expected:
prefix = ' OK '
else:
prefix = ' X '
print '%s got: %s expected: %s' % (prefix, repr(got), repr(expected))
def main():
l = Linked_list()
n = Node(6)
n2 = Node(-1)
n3 = Node(0)
l.insert(Node(2))
l.insert(n)
l.insert(Node(5))
l.insert(n2)
l.prepend(Node(6))
print l, l.get_first(), l.get_last()
print l.index_of(n), l.index_of(n3)
print l.remove(n)
print l, l.get_first(), l.get_last()
print l.remove_last()
print l, l.get_first(), l.get_last()
if __name__ == '__main__':
main()
|
84f2c41dd849d194eb1bbdbb5abc97ae9f05bfcd | trishajjohnson/python-ds-practice | /fs_1_is_odd_string/is_odd_string.py | 974 | 4.21875 | 4 | def is_odd_string(word):
"""Is the sum of the character-positions odd?
Word is a simple word of uppercase/lowercase letters without punctuation.
For each character, find it's "character position" ("a"=1, "b"=2, etc).
Return True/False, depending on whether sum of those numbers is odd.
For example, these sum to 1, which is odd:
>>> is_odd_string('a')
True
>>> is_odd_string('A')
True
These sum to 4, which is not odd:
>>> is_odd_string('aaaa')
False
>>> is_odd_string('AAaa')
False
Longer example:
>>> is_odd_string('amazing')
True
"""
abcs = list('abcdefghijklmnopqrstuvwxyz')
count = 0
word = word.lower()
for letter in word:
idx = abcs.index(letter) + 1
count += idx
if count % 2 == 1:
return True
else:
return False
# Hint: you may find the ord() function useful here |
011c454aef55fecb05e327744b8cf001fd90ed5a | smirnoffmg/codeforces | /591A.py | 116 | 3.640625 | 4 | # -*- coding: utf-8 -*-
l = int(raw_input())
p = int(raw_input())
q = int(raw_input())
print(p * l / float(p + q))
|
9f88b91a2834e93146e7dc4c5b0cc1a38dba5553 | smirnoffmg/codeforces | /519A.py | 416 | 3.609375 | 4 | # -*- coding: utf-8 -*-
res = ''
for i in xrange(8):
res += raw_input()
white_sum = res.count('Q') * 9 + res.count('R') * 5 + res.count('B') * 3 + res.count('N') * 3 + res.count('P')
black_sum = res.count('q') * 9 + res.count('r') * 5 + res.count('b') * 3 + res.count('n') * 3 + res.count('p')
if white_sum > black_sum:
print('White')
elif white_sum < black_sum:
print('Black')
else:
print('Draw')
|
1991e34b3272b9374e485fb49abe10f2adfb7b3b | smirnoffmg/codeforces | /519B.py | 303 | 4.15625 | 4 | # -*- coding: utf-8 -*-
n = int(raw_input())
first_row = map(int, raw_input().split(' '))
second_row = map(int, raw_input().split(' '))
third_row = map(int, raw_input().split(' '))
print [item for item in first_row if item not in second_row]
print [item for item in second_row if item not in third_row] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.