blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
cd20fdf9ed002034e3d703e4e51a1b22ce1536dc | mike1e/projecteuler | /problem4.py | 359 | 4.09375 | 4 | def largest_palindrone():
'''
Finds largest palindrone of 3 digit products.
'''
palindrone = 0
for a in xrange(100,999):
for b in xrange(100,999):
product = a*b
if product > palindrone and str(product) == str(product)[::-1]:
palindrone = product
... |
dee9c8306605f2f2fb9fca0c52e1584821ba02b9 | zhouqihong/homework | /learn-NLP-luhuibo-master NLP第四期同学的/lesson-03/loss_abs.py | 2,180 | 3.671875 | 4 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''=================================================
@IDE :PyCharm
@Author :LuckyHuibo
@Date :2019/7/25 17:55
@Desc :use the absolution to count the loss
according the code given in class, change the loss
to abs, and try the differences.
=============================... |
6c4b0c19178e429502ec93f1ecf98f116a291c57 | Vibinmundackal/chpc-assignments | /cuberoot-newton.py | 151 | 3.671875 | 4 | i=input('Enter the number ')
x=0.3*i
error=0.000000001
while(abs((x**3)-i)>error):
fx=(x**3)-i
dfx=3*(x**2)
x=x-(fx/dfx)
print 'Cube root: ',x
|
bfdfcac6ad433868c248872b0283eef2af3ec94b | gangulymalini/swe2-inclass-2 | /divisors.py | 95 | 3.90625 | 4 | num = input("Enter number: ")
for x in range(1, num):
if (num % x) == 0:
print(x) |
e8d054966da105eb8436188311bddfd89dec69a5 | Rafaelahs/SA2_exercicio_python | /ativ03.py | 401 | 3.796875 | 4 | #3
soma = 0
maior = 0
menor = 0
quant= 0
for i in range(20):
valor = int(input('Digite um valor: '))
soma = soma + valor
quant +=1
if quant == 1:
maior=menor=valor
else:
if valor>maior:
maior = valor
if valor <menor:
menor = valor
med = soma/20
print('a média é: ', ... |
ec9d5565918bbc5cb0d8e25ea23095c864c3eb12 | Insua/python-learn | /007/002.py | 963 | 3.5 | 4 | class Student(object):
pass
s = Student()
s.score = 9999
class Student(object):
def get_score(self):
return self._score
def set_score(self, value):
if not isinstance(value, int):
raise ValueError('score must be an integer!')
if value < 0 or value > 100:
r... |
20e3a4745ada6205609be9466b2022183b446cf3 | Insua/python-learn | /001/004.py | 536 | 3.921875 | 4 | d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
print(d['Michael'])
d['Adam'] = 67
print(d)
d['Jack'] = 90
print(d['Jack'])
d['Jack'] = 88
print(d['Jack'])
# print(d['Thomas'])
print('Thomas' in d)
print(d.get('Thomas'))
print(d.get('Thomas', -1))
d.pop('Bob')
print(d)
# key = [1, 2, 3]
# d[key] = 'a list'
# print... |
b60e87eada01fc99e8d59fde1520e7062da8a930 | svanis71/codewars | /codewars.python/tests/subseqsum_tests.py | 1,359 | 3.609375 | 4 | import unittest
def subsequence_sums(arr, s):
"""
https://www.codewars.com/kata/60df63c6ce1e7b0023d4af5c/train/python
:param arr: array of ints -10000 <= x <= 10000
:param s: Value to test against
:return: Number of subsequences that sums to testval
"""
# map = defaultdict(list)
runn... |
c03964529a0d6feb48bda46200488f0eab755e81 | svanis71/codewars | /codewars.python/last_digits.py | 273 | 3.5 | 4 | """
https://www.codewars.com/kata/5cd5ba1ce4471a00256930c0/train/python
"""
def solution(n, d):
last_digits = []
while d > 0:
n, r = divmod(n, 10)
d -= 1
last_digits.insert(0, r)
if n == 0:
break
return last_digits
|
a2929fd09d1daf91b1b4e2b08446820d38f75d67 | aleksandramitula/PYTHON_ola | /Dzien3/dzien3.py | 1,108 | 4.125 | 4 | temperature = input("Podaj temperature: ")
#DUZYMI LITERAMI piszemy stala, nie zmienna. To sa te wartosci, ktorych nie chcemy zmieniac w srodku w kodzie, ale mozna zmienic na poczatku:
HOT_TEMPERATURE=30
WARM_TEMPERATURE=25
NOT_COLD_NOT_WARM_TEMPERATURE=20
if temperature >=HOT_TEMPERATURE:
print("it's hot")
elif t... |
39a63b94d26ddf4fb28f910dc9a99049d20263ad | aleksandramitula/PYTHON_ola | /Trainings/lists_examples_1.py | 178 | 3.515625 | 4 | rzeczy = ["doniczka", "kwiatek", "ziemia", "woda"]
print(rzeczy[1])
print(rzeczy[1:3])
print(len(rzeczy))
# imie = "Anna"
# imie[2] = "i"
rzeczy[2] = "konewka"
print(rzeczy)
|
1655862dcc4822c7a02427f9ff2f684d1448d137 | aleksandramitula/PYTHON_ola | /Trainings/for_loop_with_break.py | 137 | 3.75 | 4 |
for x in range(20):
if x**2 > 280:
print("Znalazłem element:", x)
break
print("Pierwsza instrukcja po pętli.")
|
a81f60dc1957a71e503fb3dfb8b3ba80ad93bbee | aleksandramitula/PYTHON_ola | /Dzien10/game.py | 2,052 | 3.546875 | 4 | import random
class Dice(object):
def __init__(self, sides=6):
self.sides = sides
def roll(self):
return random.choice(range(1, self.sides+1))
class Character(object):
def __init__(self, health = 10, strength = 5, damage = 2, armor = 5):
self.health = health
self.strength... |
c3c55f445493c42e5e4a3bf06a843cd95c41f035 | findraya/Tucil2_13519171 | /src/13519171.py | 3,933 | 4.1875 | 4 | # NIM : 13519171
# Nama : Fauzan Yubairi Indrayadi
# Topik : Tugas Kecil 2
# Kelas Kuliah untuk menyimpan nama matkul, semester, jumlah prerequisite, next matkul, dan list prerequisitenya
class Kuliah:
def __init__(self, matkul=None):
self.matkul = matkul
self.sem = None
self.preqcount =... |
0a743f95cc5cc5939ac7e40fde724d38de7315f9 | tniranjanreddy11989/Hangman-Mini-project | /Hangman code.py | 2,190 | 4 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
choose = 'Watch the ABC Shows online at abc com Get exclusive videos and free episodes'.split()
#A random word will be taken from the above sentence using the below code written for word.
from random import randint
word = choose[randint(0,len(choose))] #word is selecte... |
0b70916964c0dafedea82c60c9182b3f1ae57244 | nbrahman/HackerRank | /01 Algorithms/02 Implementation/Designer-PDF-Viewer.py | 1,997 | 4.0625 | 4 | '''
When you select a contiguous block of text in a PDF viewer, the selection is highlighted with a blue rectangle. In a new kind of PDF viewer, the selection of each word is independent of the other words; this means that each rectangular selection area forms independently around each highlighted word. For example:
... |
7c77ebea7fcd9b61fd6be8b613cc646565b15697 | nbrahman/HackerRank | /01 Algorithms/01 Warmup/PlusMinus.py | 1,456 | 3.953125 | 4 | '''
Given an array of integers, calculate which fraction of its elements are positive, which fraction of its elements are negative, and which fraction of its elements are zeroes, respectively. Print the decimal value of each fraction on a new line.
Note: This challenge introduces precision problems. The test cases are... |
3610edbc01048d26aa18a06bbbf876e4a7161e43 | nbrahman/HackerRank | /01 Algorithms/02 Implementation/Cats-and-a-Mouse.py | 1,760 | 3.765625 | 4 | '''
Two cats named A and B are standing at integral points on the x-axis. Cat A is standing at point x and cat B is standing at point y. Both cats run at the same speed, and they want to catch a mouse named C that's hiding at integral point z on the x-axis. Can you determine who will catch the mouse?
You are given q q... |
b8fb6273b757d8af0e9f62bcd617c127ecc59466 | nbrahman/HackerRank | /04 Cracking the Coding Interview/DP-Coin-Change.py | 411 | 3.546875 | 4 | #!/bin/python3
import sys
def make_change(coins, n, m):
table = [0 for k in range(n + 1)]
table[0] = 1
for i in range(0, m):
for j in range(coins[i], n + 1):
table[j] += table[j - coins[i]]
return table[n]
n, m = input().strip().split(' ')
n, m = [int(n), int(m)]
coins = [int... |
e4975175bb97edd715411f62c8a168dfe32570eb | nbrahman/HackerRank | /03 10 Days of Statistics/Day08-01-Least-Square-Regression-Line.py | 1,450 | 4.21875 | 4 | '''
Objective
In this challenge, we practice using linear regression techniques. Check out the Tutorial tab for learning materials!
Task
A group of five students enrolls in Statistics immediately after taking a Math aptitude test. Each student's Math aptitude test score, x, and Statistics course grade, y, can be expre... |
ad3ee4e06335113f426b2461f11c8fcd12b67ab8 | nbrahman/HackerRank | /01 Algorithms/11 Recursion/The-Power-Sum.py | 1,327 | 4.09375 | 4 | '''
Find the number of ways that a given integer, X, can be expressed as the sum of the Nth power of unique, natural numbers.
Input Format
The first line contains an integer X.
The second line contains an integer N.
Constraints
1<=X<=1000
2<=N<=10
Output Format
Output a single integer, the answer to the problem ex... |
395e1d9a4958b503675ea32766c7b3d6d5c32ed1 | nbrahman/HackerRank | /03 10 Days of Statistics/Day06-01-The-Central-Limit-Theorem-II.py | 1,558 | 3.921875 | 4 | '''
Objective
In this challenge, we practice solving problems based on the Central Limit Theorem. We recommend reviewing the Central Limit Theorem Tutorial before attempting this challenge.
Task
The number of tickets purchased by each student for the University X vs. University Y football game follows a distribution t... |
6ff6315f1751f5d5a53654405578521fac1fada3 | nbrahman/HackerRank | /01 Algorithms/02 Implementation/Save-the-Prisoner.py | 1,792 | 3.890625 | 4 | '''
A jail has N prisoners, and each prisoner has a unique id number, S, ranging from 1 to N. There are M sweets that must be distributed to the prisoners.
The jailer decides the fairest way to do this is by sitting the prisoners down in a circle (ordered by ascending S), and then, starting with some random S, distri... |
0f6b10dcc4daa71cd5b0d0ebc8c45e884e0fb12a | nbrahman/HackerRank | /01 Algorithms/02 Implementation/Grading-Students.py | 2,195 | 3.96875 | 4 | '''
HackerLand University has the following grading policy:
Every student receives a grade in the inclusive range from 0 to 100.
Any grade less than is a failing grade.
Sam is a professor at the university and likes to round each student's grade according to these rules:
If the difference between the gra... |
7d1e10a0303d71f3ff95a22bf44e2963b3745f22 | nbrahman/HackerRank | /01 Algorithms/01 Warmup/TimeConversion.py | 969 | 4.25 | 4 | '''
Given a time in 12-hour AM/PM format, convert it to military (24-hour) time.
Note: Midnight is 12:00:00AM on a 12-hour clock, and 00:00:00 on a 24-hour clock. Noon is 12:00:00PM on a 12-hour clock, and 12:00:00 on a 24-hour clock.
Input Format
A single string containing a time in 12-hour clock format (i.e.: hh:m... |
fd4be7ead12bb78ac455902f0721c2655643d7f4 | nbrahman/HackerRank | /01 Algorithms/02 Implementation/Utopian-Tree.py | 1,421 | 4.21875 | 4 | '''
The Utopian Tree goes through 2 cycles of growth every year. Each spring, it doubles in height. Each summer, its height increases by 1 meter.
Laura plants a Utopian Tree sapling with a height of 1 meter at the onset of spring. How tall will her tree be after N growth cycles?
Input Format
The first line contains ... |
13c10b8411890edb52c47de0543427793125cd55 | nbrahman/HackerRank | /01 Algorithms/02 Implementation/Circular-Array-Rotation.py | 1,807 | 4.28125 | 4 | '''
John Watson performs an operation called a right circular rotation on an array of integers, [a0, a1, a2, an-1]. After performing one right circular rotation operation, the array is transformed from [a0, a1,
a2, an-1] to [an-1, a0, a1, a2, an-2].
Watson performs this operation k times. To test Sherlock's ability to... |
f491956806d8ff595c96793382597a409ef9fcf5 | Tahlor/word-rnn-tensorflow | /processing/4_clean_gutenberg.py | 4,142 | 3.640625 | 4 | import os
import re
# Input a list of things to find before first string or just first string
def parse(text, begin, end, exclude_targets = True, full_list = False):
# Position 1
# If full_list false specified, this presently will ignore elements not found
pos1 = 0
if begin == None:
pos1 = 0
... |
0a7b661a177032f2f1ab14d4e77c0589f1f446d8 | fmojica30/leetcode_practice | /test.py | 754 | 3.734375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class Solution(object):
def combine(self, n, k):
"""
:type n: int
:type k: int
:rtype: List[List[int]]
"""
temp = []
self.result = []
position = 1
self.helper(n, k, position, temp)
... |
df307b32dcfc44b71ea43837301578018d436931 | fmojica30/leetcode_practice | /sliding_windows.py | 5,371 | 3.875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from copy import deepcopy
class Solution(object):
def slidingPuzzle(self, board):
"""
:type board: List[List[int]]
:rtype: int
"""
current_moves = 0
self.lowest_moves = -1
zero_x = None
zero_y = N... |
52e052955b23c16b2907b3543c6e839bfc39327e | MatthewSwart/ScriptingCollege | /Week7/hourly_pay.py | 740 | 3.84375 | 4 | #Example of a subclass called hourly pay
from employee import Employee
class Hourly_pay(Employee):
def __init__(self, staff_name, staff_id, hourly_rate, hours_worked):
Employee.__init__(self, staff_name, staff_id)
self.hourly_rate = hourly_rate
self.hours_worked = hours_worked
def t... |
641b0855ee0ee095ae620ad7ea39e1bef25ed8bf | crankocial/dz2 | /dz2.py | 784 | 3.671875 | 4 | import random as rand
import copy
def matrix_create():
out = []
inside = []
print('input the size of matrix nxm n=m= ')
c = input()
c = int(c)
for m in range(c):
for n in range(c):
inside.append(rand.randint(1, 10))
out.append(inside)
inside = []
return ... |
bd43d2debf0e6c37ada21db2427e748cc1cadcd7 | kumarchandan/Data-Structures-Python | /3-linked_lists/c7_find_middle_node/main_brute.py | 668 | 4 | 4 | from LinkedList import LinkedList
# Access head_node => list.get_head()
# Check if list is empty => list.is_empty()
# Length of the list => list.length()
# Node class { int data ; Node next_element;}
def find_mid(lst):
# Write your code here
lst_len = lst.length()
if lst_len % 2 == 0:
mid = int(... |
5d0df4565c0a9c8ddd4442a609050631ae3310f9 | kumarchandan/Data-Structures-Python | /3-linked_lists/c6_detect_loop_in_linked_list/main-floyd-algo.py | 1,201 | 4.125 | 4 | '''
This is perhaps the fastest algorithm for detecting a linked list loop. We keep
track of two iterators, onestep and twostep.
onestep moves forward one node at a time, while twostep iterates over two nodes. In this way,
twostep is the faster iterator.
By principle, if a loop exists, the two iterators will meet. ... |
03c87691be0f56361dbc61c2d54ba22a727cf84d | kumarchandan/Data-Structures-Python | /5-graphs/breadth-first-traversal/main.py | 2,476 | 3.953125 | 4 | from Graph import Graph
from Queue import MyQueue
# You can check the input graph in console tab
# Create Queue => queue = MyQueue()
# Functions of Queue => enqueue(int), dequeue(), size(), front(), is_empty()
# Create Stack => stack = MyStack()
# Functions of Stack => push(int), pop(), top(), is_empty()
# Create Gra... |
f3fd6cf2971a7fe8f9a0ca27e4fe235348f09138 | ramksharma1674/pyprojold | /temp.py | 413 | 3.796875 | 4 | def to_celcius(f):
celcius = (f - 32) * 5/9
return celcius
def to_frnh(c):
frnh = c * 9/5 + 32
return frnh
def main():
for temp in range(0, 212, 40):
print(temp, "Fahrenheit = ", round(to_celcius(temp)), "Celcius")
for temp in range(0, 100, 20):
print(temp, "Celcius = ", r... |
ff57f60e1ff5fc7d7eafa36fca18f789ca4106ab | ramksharma1674/pyprojold | /tmpcall.py | 477 | 3.84375 | 4 | from temp import to_celcius
import random
c= to_celcius(70)
print (c)
number, number2, number3 = random.random(), random.randint(1,6), random.randrange(100,500,5)
#print("number=", random.random())
#number2 = random.randint(1,6)
#number3 = random.randrange(100,500,5)
print (number)
print (number2)
print (number3)
li... |
a2cec71acb752162fd833d90afe930ad194deee8 | ramksharma1674/pyprojold | /fwords.py | 442 | 3.921875 | 4 | def fetch_words(url):
"""Fetch a list of words from a URL. """
with urlopen(url) as story:
story_words = []
for line in story:
line_words = line.decode('utf8').split()
for word in line_words:
story_words.append(word)
return story_words
new_words = []
new_words = fetch_words("https://app.pluralsight.c... |
47c80060ef95bf9fb0845bfae99a07786cb44df8 | XuanYang-cn/pymilvus | /pymilvus/orm/role.py | 4,004 | 3.5 | 4 | from .connections import connections
"""
Role, can be granted privileges which are allowed to execute some objects' apis.
"""
class Role:
""" Constructs a role by name
:param name: role name.
:type name: str
"""
def __init__(self, name: str, using="default", **kwargs):
self._name = name
... |
454f38ee02907ba01828939fa28507c6d4920213 | bboti86/own-scripts | /MNB_arfolyam.py | 3,298 | 3.859375 | 4 | """
MNB árfolyam puller.
Simple tool for querying the currency exchange rate of the
Hungarian National Bank for one particular day
"""
from time import sleep
def MNBArfolyam(date, currency="EUR"):
"""
MNB árfolyam puller.
Simple tool for querying the currency exchange rate of the
Hungarian National ... |
00c6170a47f3f0454a1de026c7e05dd19f6516b3 | JamesMerfeld/Coursera_BioInfoForBeginners | /Replication.py | 4,954 | 3.65625 | 4 | # Input: Strings Pattern and Text
# Output: The number of times Pattern appears in Text
def PatternCount(Pattern, Text):
count = 0 # output variable
for i in range(len(Text)-len(Pattern)+1):
if Text[i:i+len(Pattern)] == Pattern:
count = count+1
return count
# Input: Two strings, P... |
754bb3d65ac97f3ddfecc9b21bfdd227fdd2b629 | kuldeepsinghshekhawat/CodeVita_preparation | /sheldom_cooper.py | 574 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jul 10 09:58:35 2020
@author: kdban
"""
def solve(N,Q,X):
sortedQ=sorted(Q)
for i in range(N-2):
for j in range(1,N-1):
for k in range(2,N):
if i==j or i==k or j==k:
continue
... |
990fce6b884155dfd26af2a857cd30b854d3f432 | vivekadithya/streamlit-projects | /src/dna_count_app.py | 1,886 | 3.59375 | 4 | import streamlit as st
import pandas as pd
import altair as alt
st.write("""
# DNA Count Web Application
This app counts the nuecleotide composition of query DNA!
""")
st.header("""
Enter DNA Sequence
""")
sequence_input = ">DNA Query 2\nGAACACGTGGAGGCAAACAGGAAGGTGAAG... |
d7833a2c523c5146fadfb8249197eec25c6d4f02 | sato-makoto/misc | /python3/hana2.py | 249 | 3.984375 | 4 | #!/usr/bin/env python3
# shuffle and print argv[1]
from sys import argv
from random import shuffle
print("from:", argv[1])
mystr = list(argv[1])
shuffle(mystr)
print("to: ", sep=" ", end="")
for x in mystr:
print(x, sep="", end="")
print("")
|
6fad9e4823abd4926e2e9b2a60c9785bdcb47f85 | kimhansol1/shingu | /hh.py | 102 | 3.703125 | 4 | a=[5,3,4,1,2]
print a.index(2)
print a.counnt(5)
a.sort()
print
a.reverse()
print
b = sorted(a)
print
|
6240ae392a7628acd05d8618b18a60cbed7bab2f | kimhansol1/shingu | /k.py | 224 | 3.65625 | 4 | color = ['red','blue','green']
color2=['orange','black','white']
print color + color2
len(color)
color[0]='yellow'
print color*2
'blue'in color2
total_color = color + color2
for each_color in total_color
print each_color
|
994acbe7ddc30b9fc335b455d9c27a3c91512ea5 | koushikckm/PythonLearnings | /workspace/Practice/stringoperations.py | 312 | 3.96875 | 4 | myStr="Hello World!!!"
print("Length of myStr is %d " %len(myStr))
print(myStr.index("o"))
print(myStr.count("!"))
print(myStr[3:7])
print(myStr[0:10:2])
print(myStr.upper())
print(myStr.lower())
print(myStr.startswith("Hello"))
print(myStr.endswith("asdfasdfasdf"))
afewwords = myStr.split(" ")
print(afewwords) |
fbefb3156f8c8abaa4a55007e32a7f7bcbb0ae76 | koushikckm/PythonLearnings | /workspace/OOP/oop.py | 495 | 3.625 | 4 | class Animal():
habitat='land'
def __init__(self,a,b,c=1):
self.limbs=b
self.tail=c
self.animaltype=a
def animaldetails(self,color,hair,breed):
print('Color of the '+self.animaltype+' is '+color)
print('Hair type is '+hair)
print('Breed of the '+self... |
b48eb6ba80f29592486f30acd96976c6a3c7ebd0 | LuluDavid/Polynomial-Interpolation | /src/polynomes.py | 1,942 | 4.03125 | 4 | # Basic functions on polynomials
import numpy as np
import matplotlib.pyplot as plt
# Polynomials as lists of coefficients
# P+Q: max(deg(P),deg(Q)) operations
def add_polynomials(P, Q):
somme = []
n = len(P)
m = len(Q)
if n < m:
P += (m - n) * [0]
elif n < m:
Q += (n - m) * [0]... |
31e0ed2e6f0f97bd6083184d59bc1374cfb1c8a5 | default1337/Digicert_API | /Legacy_Converter.py | 1,675 | 3.71875 | 4 | #Import the requests module
import requests
#Get Certificate Order ID
Cert_Order_Id = input("Enter Cert ID: ")
#Digicert Cert Central API Endpoint for looking up Legacy Order IDs returning new Digicert Cert Central Order IDs
Legacy_Endpoint = f"https://www.digicert.com/services/v2/oem-migration/{Cert_Order_Id}/order... |
0a95023ce6b3d7f67e245fc33cd602997f15d8de | womenwhocodedc/python-community | /intro_to_flask/tutorial_2.py | 7,004 | 4 | 4 | """
tutorial_2.py
Contents:
This is a very basic flask application that will
return data population data about states when called.
Usage:
To start your flask web app on the command line, you need to do two steps
1. Tell flask the name of your FLASK_APP
2. Start flask program for local development
-- flask wil... |
b1140ae24bbcacf7cfd9ad2f491716e62303cb92 | LiFu-ChrisLee/algorithm | /leetcode/98.validate-binary-search-tree.py | 1,156 | 3.859375 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def __init__(self):
self.pre = None
def isValidBST(self, root):
"""
:type root: TreeNod... |
689fd15c1cf818d93b78fe048942282348895c3d | nikolasjdawson/mapping-career-causeways | /codebase/data/download_data.py | 1,631 | 3.5 | 4 | import urllib.request
import os
import zipfile
import sys
"""
Usage
-----
Option 1, for downloading all data files, to replicate all analyses:
$ python download_data.py
Option 2, for downloading only data required for generating transitions:
$ python download_data.py lite
"""
# Choose which archive to download
if (... |
6e789479eed88e588c246581fa8f8ae884c7baec | betulependule/redhat | /automat.py | 1,120 | 3.546875 | 4 | #! /usr/bin/env python3
vstup = 37
def automat(vstup):
padekoruny = 0
dvackoruny = 0
desekoruny = 0
petkoruny = 0
dvoukoruny = 0
koruny = 0
while vstup > 0:
if vstup >= 50:
vstup = vstup - 50
padekoruny = padekoruny + 1
elif 50 > vstup >= 20:
... |
acb654897c06b347ccb06afc0c4a549fbb6fb6b3 | lamsnakesgit/hyperskillpyth | /Problems/Desks/main.py | 219 | 3.578125 | 4 | # 3 3 3 = 2 2 2 = 6
a = int(input())
b = int(input())
c = int(input())
add = 0
if (a % 2) == 1:
add += 1
if (b % 2) == 1:
add += 1
if (c % 2) == 1:
add += 1
print(int(a / 2) + int(b / 2) + int(c / 2) + add)
|
cc852059071f818f73ad47e9848ad70ff272d71b | kitkogan/python_sandbox | /variables.py | 708 | 3.90625 | 4 | # A variable is a container for a value, which can be of various types
'''
This is a
multiline comment
or docstring (used to define a functions purpose)
can be single or double quotes
'''
"""
VARIABLE RULES:
- Variable names are case sensitive (name and NAME are different variables)
- Must start with a letter or... |
9d236be114dc565a66d49389de8b03be86448bae | Chiefautoparts/Python_Party | /RPS/paper.py | 265 | 3.734375 | 4 | user = input('paper')
win = 0
lose = 0
tie = 0
from random import randint
c = ['rock', 'paper', 'scissors']
comp = c[randint(0,2)]
print comp
if comp == rock:
print 'you win'
win++
elif comp == paper:
print 'you tie'
tie++
else:
print 'you lose!!'
lose++ |
bc2adc0ed688b4114e68ea7cac74d42ff899093b | junnychen/pythonhomework | /pybank/pybank.py | 792 | 3.671875 | 4 | #!/usr/bin/env python
# coding: utf-8
import pandas as pd
path = "budget_data.csv"
budget = pd.read_csv(path)
month = len(budget["Date"].unique())
total = budget["Profit/Losses"].sum()
difference = budget["Profit/Losses"].diff()
average = difference.mean()
max_difference = difference.max()
max_month = budget["Date... |
950ee7777849a573b979f3d4a8605943e8aaa406 | tamura0425/test | /git/Python/rank_c.py | 284 | 3.671875 | 4 |
num = int(input()) #ループ回数
sum = 0 # 合計
for i in range(num):
inputNum = input()
array = inputNum.split()
if array[0] == array[1]:
sum += int(array[0]) * int(array[1])
else:
sum += int(array[0]) + int(array[1])
print(sum) |
6bd9ff3b359f46cbf414950c141caf44ef34b3bf | tamura0425/test | /git/Python/b_rank.py | 1,673 | 3.75 | 4 | #! /usr/local/bin/python3
board = []
for i in range(5):
board.append(input())
def row():
result = 'D'
for line in board:
pivot = line[0]
count = 0
for stone in line:
if stone != '.' and stone == pivot:
count += 1
else:
... |
2ca05f2a953490b7279a8b2acd3304c05ab1085f | san-git/covid19-severity-prediction | /viz/viz.py | 8,550 | 3.53125 | 4 | from bokeh.sampledata import us_states, us_counties
from bokeh.plotting import figure, show, output_notebook, output_file, save
from bokeh import palettes
from bokeh.models import ColorBar,HoverTool,LinearColorMapper,ColumnDataSource,FixedTicker, LogColorMapper
output_notebook()
import re
import numpy as np
import pl... |
db1693e64a45f26924be480fac120375f72931c7 | juliagodas/lab-python-inatel | /ex_2.py | 144 | 4.09375 | 4 |
num=int(input("Entre com um número: "))
ant = num - 1;
suc = num + 1;
print('Antecessor : {} numero: {} Sucessor: {}'.format(ant,num,suc))
|
4f611a567e0a8442a08ed74c08f0000b982b701b | SamiMannila/Cube-Jump | /enemybrain.py | 1,351 | 3.90625 | 4 | from enemy import Enemy
from location import SQUARE_SIZE
class EnemyBrain(Enemy):
'''
This class generates the brain (AI) to the enemies. This class is responsible of moving
the enemy and a enemy brain is equipped
with an algorithm for determining what a robot should do depending of player's location,... |
82e2550cf9c179b42007493c0e02b802773af03b | SamiMannila/Cube-Jump | /turningenemy.py | 1,029 | 3.734375 | 4 | from enemybrain import EnemyBrain
class TurningEnemy(EnemyBrain):
'''
This class is responsible of creating enemy brain to the Turning type enemy.
Turning enemy is only aware of its own location and doesn't care about the player.
Turning enemy moves forward 220 times after it turns and moves 220 times... |
fe4576b779abc8137d6dd5d16e78df5d523d111d | StefanLage/Location-Generator | /External/gpx-generator.py | 3,533 | 3.671875 | 4 | #!/usr/bin/python
import sys, os, argparse, json, urllib
from datetime import datetime
# Define properties
address = 'Downtown'
city = ''
country = ''
postalCode = ''
path = os.path.dirname(os.path.realpath(__file__))
output = 'gpxFile'
latitude = 0
longitude = 0
# Do the process expected
def main():
global address... |
dc570a6aab77cc667d0b2b62b68a6afa739c9a85 | Atanasfd/Calculator | /calculator.py | 3,787 | 4.21875 | 4 | from tkinter import *
from math import *
root=Tk()
#the functions
def add_0():
string.set(string.get()+"0")
def add_1():
string.set(string.get()+"1")
def add_2():
string.set(string.get()+"2")
def add_3():
string.set(string.get()+"3")
def add_4():
string.set(string.get()+"4")
de... |
8b2ced82e84ea42b832f95d6cb1b6996d1bc9dc2 | Vincenttainan/hi2 | /hi2.py | 214 | 3.78125 | 4 | print('hi')
username=input('what is your name?')
print('hello',username)
age=input('how old are you?')
gender=input('what is your gender?')
print('You,',username ,',are a-',age, '-year-old',gender,)
print('\>_</')
|
65b2aafb25f9220991f23c9afd9bd997cec9b0c2 | chadondata/charpsberry_piduino | /easy_raspberry_pi/dimmer.py | 520 | 3.546875 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
Uses a potentiometer to manually adjust resistance to LED, creating a dimmer.
Parts needed:
Raspberry Pi
Breadboard
10k ohm potentiometer
MCP3008 chip
5mm LED
330 ohm resistor
Jumper wires
"""
from gpiozero import PWMLED, MCP3008
from time im... |
450d4fa19990baba92165ef261ffee00d2f214ff | ygretharekar/hr_py | /implementation/medium/three_d_surface_area.py | 890 | 3.5 | 4 | "https://www.hackerrank.com/challenges/3d-surface-area/problem"
class ThreeDSurfaceArea:
"Solution"
def solution(self, grid_weights):
"solution"
row_len = len(grid_weights)
col_len = len(grid_weights[0])
c_offset = (1, 0, -1, 0)
r_offset = (0, 1, 0, -1)
s_area =... |
4c090447088ebb64d0fafd8eefe47ffb8fa84c27 | ygretharekar/hr_py | /implementation/medium/encryption.py | 547 | 3.5625 | 4 | """
https://www.hackerrank.com/challenges/encryption/problem
"""
class Encryption:
"""
solving
"""
def solution(self):
"""solution"""
inp_str = input().replace(" ", "")
import math
l_b = math.floor(math.sqrt(len(inp_str)))
u_b = math.ceil(math.sqrt(len(inp_st... |
06ab0818a1914ca36da224dceda1de6f993bacc8 | lian999111/ANN-Tutorials | /9 Multi-Layer Perceptron/prob_mlp.py | 4,902 | 3.796875 | 4 | # imports
import numpy as np
import matplotlib.pyplot as plt
def metric(y_hat, y):
y_hat = np.reshape(y_hat, (-1))
y = np.reshape(y, (-1))
MSE = np.mean((y_hat - y)**2)
classifications = y_hat
classifications[y_hat >= 0] = 1
classifications[y_hat < 0] = -1
accuracy = np.sum(classification... |
6fb12a06b85202ca2e2e90d5baf5d198727d7cf0 | Unrealplace/Python | /Python基础教程/loop.py | 395 | 4.34375 | 4 | # 循环的使用
namelist = ['fanyangyang','yangyangfan','oliverlee']
nametuple = ('hello','world','nice ','to','meet you')
# Python的循环有两种,一种是for...in循环,依次把list或tuple中的每个元素迭代出来,看例子:
for name in namelist:
print(name)
pass
for item in nametuple:
print(item)
pass
#遍历索引的方式
for x in range(1,10):
print(x)
pass |
eadd85e29a427e40633a13df4f210465ec611766 | Unrealplace/Python | /Python基础教程/数据类型和变量.py | 703 | 3.78125 | 4 | a = 100
if a > 10:
print('a>10')
else:
print('a<=10')
pass
# 布尔值
# 布尔值可以进行 and or not 运算 对应的是 && || !
b = 44
c = 444
d = True
e = False
if b > c:
a = b + c
pass
if d and e:
print(a)
pass
if d or e:
print(b)
pass
if not e:
print(c)
pass
# 空值 None
f = None
print(f)
# 常量 用大写的变量名表示 常量 PI = 3.14159265... |
0e810c80bb52c2c2dda64c34b28f708158075807 | xzient/Hispanofonicos | /word.py | 12,155 | 3.65625 | 4 |
STRONG_VOWELS = ['a','e','o','á','é','í','ó','ú','ý']
WEAK_VOWELS = ['i','ü','u','y','w']
# It does not include semi-vowels/consonants
FULL_VOWELS = ['a','e','o','á','é','í','ó','ú','ý','i','ü','u']
class vowel:
def __init__(self, vowel_num, ind, text):
self.vowel_num = vowel_num
self.index = ... |
2cd31229ab52d519b2ab5324fc3783c12bf2dab4 | Waszker/Pattern-recognition | /Python2/loading.py | 3,304 | 3.59375 | 4 | #!/usr/bin/python2.7
import csv
import numpy
def get_normalize_vector():
"""
Returns vector used in normalization that is extracted
from all numbers in data set.
"""
for i in range(0, 10):
[train, test] = _load_number_set(i, 0.7)
if i == 0:
all_numbers = train
... |
9adb103b73c932c3377992e8f69b778f0cc93283 | liamwb/A_Tricky_Sum | /main.py | 408 | 3.625 | 4 | from math import log
a = input()
b = []
for i in range(int(a)):
b.append(int(input()))
def sumLessPowersOfTwo(N):
# Sum of an AP is (n/2)*(a + l)
sumToN = int((N*(1 + N))//2)
# Sum of a GP is (a(r^n - 1)/(r-1), and a = 1, r - 1 = 1
# r = 2, and to find n
n = int(log(N, 2) + 1)
sumOfTwos =... |
3b2324665f3ccfcdf830c9c0becd46427f090a2b | Chris-grant1995/Spring-2016-TA-Labs | /Lab 1/Lab1.py | 253 | 3.765625 | 4 | bill = float(input("Please provide the total amount for the bill: "))
avg = bill * .15
good = bill * .20
great = bill * .25
print('Your bill was {0:.2f}:\nAvg Tip = ${1:.2f}\n\
Good Tip = ${2:.2f}\nGreat Tip = ${3:.2f}'.format(bill,avg,good,great))
|
0e967bb9c142a9e704b34cfbd27aef3be62cbfcd | mfyc/Simple-Connect-Four-Game | /connect_four.py | 1,961 | 3.609375 | 4 | #
# A Connect Four Game
#
from board import Board
from player import Player
from aiplayer import AIPlayer
import random
def connect_four(player1, player2):
""" Plays a game of Connect Four between the two specified players,
and returns the Board object as it looks at the end of the game.
... |
9985b32d8d79fb4bfde8d0ffbec712e5b88ac8d4 | gomanish/Python | /Linked_List/add_and_delete_last_node.py | 910 | 4.25 | 4 | # Add and Delete Last Node in a linked list
class Node:
def __init__(self,val):
self.value = val
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
def printallnodeval(llist):
temp=llist.head
while temp:
print temp.value
temp=temp.next
return
de... |
eae27424746c9423d92b345429cf1acb5d5656e9 | gomanish/Python | /basic/threesquares.py | 348 | 4.1875 | 4 | '''Write a Python function threesquares(m) that takes an integer m as input and returns True.
if m can be expressed as the sum of three squares and False otherwise.
(If m is not positive, your function should return False.)'''
def threesquares(n):
if n<0:
return False
while(n%4==0):
n=n/4
n=n-7
if(n%8==0):
... |
0a9cb0887ec9dda5fda826c960c4f52a6e863c40 | gomanish/Python | /Recursion/4th.py | 162 | 4.09375 | 4 | # Reverse String
def reverse(s):
if len(s)<=1:
return s
return s[-1]+reverse(s[0:len(s)-1])
print reverse('My name is manish kumar')
print reverse('123456789')
|
dc13fe7dc20df9ef32422f292b2b42d9e6b056ed | gomanish/Python | /Stacks, Queues and Deques/Implementation of Deque.py | 486 | 3.828125 | 4 | # Implementation of Deque
class Deque:
def __init__(self):
self.item=[]
def addfront(self,num):
self.item.append(num)
def addrear(self,num):
self.item.insert(0,num)
def removefront(self):
return self.item.pop()
def removerear(self):
return self.item.pop(0)
def isempty(self):
return self.item==[]
def... |
330d2a6ca01fc917abb00bee36f125ec935b032c | gomanish/Python | /array/RemoveDuplicate.py | 494 | 3.984375 | 4 | # Program to remove Duplicate element
# This function return new size of modified array
def removeDuplicates(arr,n):
if n==0 or n==1:
return n
# To store store index of next unique element
j = 0
for i in range(n-1):
if arr[i]!=arr[i+1]:
arr[j]=arr[i]
j... |
044001b42864bae9a75bc81f1e5ad3bfeea7313f | gomanish/Python | /basic/20th.py | 565 | 3.96875 | 4 | # anagram Check
def anagram(text1,text2):
text1=''.join(text1.lower().split())
text2=''.join(text2.lower().split())
if len(text1) != len(text2):
return False
temp ={}
for k in text1:
if k in temp:
temp[k] +=1
else:
temp[k]=1
for k1 in text2:
if k1 in temp:
temp[k1] -= 1
else:
temp[k1]=1... |
43e136170a2c3bf7fc04d148f8089ce20bfa7eff | gomanish/Python | /Recursion/2nd.py | 225 | 3.875 | 4 | ''' Given an integer, creat a function which returns the sum of all the
individual digits in that integer. '''
def sum_func(num):
if num/10==0:
return num
return (num%10)+(sum_func(num/10))
print sum_func(987654321)
|
9f87a25dd45adc9aebb4be7683e96a117ed3c387 | alan199355/Python-Crawler | /list-reverse.py | 594 | 3.890625 | 4 | # coding=utf-8
arg=[]
arg2=[]
arg3=[]
x=input()
for num in x.split(" "):
try:
arg.append(int(num))
except ValueError:
print('%s is not number!'%num)
row=1
while row<=arg[0]:
y=input()
col=[]
for num in y.split(" "):
col.append(int(num))
arg2.append(col)
row=row+1
# arg2=[[1,2,3,4],[5,6,7,8],[9,10,11,12]... |
9208ddace2fc6562868c067e04f46cc8632f4b3f | carriehe7/bootcamp | /TupleCollection.py | 600 | 3.859375 | 4 | # create tuple collection
professions_in_industry = ('front-end', 'back-end', 'dev_ops', 'qa')
# print tuple
print('professions in industry : ' +str(professions_in_industry))
# print class of collection
print(type(professions_in_industry))
# get value in index 1
print('cell index 1 : ' +str(professions_in_industry[1... |
aeb0316a77be749d734a371d1c3c5041cec1b09c | carriehe7/bootcamp | /InheritanceHW.py | 3,884 | 4.25 | 4 | """
We will create 2 classes :
1. Parent class - Employee
2. Child class - Programmer
Employee class would have :
★ #1 property - self.years_of_experience [Integer]
★ #2 property - self.position_name [String]
★ #3 property - self.employee_name [String]
❖ #1 method - calculated_salary()
Create a ‘calculated_salary’ va... |
39bcbe9d664219f56608744cc6e2b0e88261fa2a | carriehe7/bootcamp | /IfStatementBasics.py | 1,118 | 4.125 | 4 | # if statements basics part 1
salary = 8000
if salary < 5000:
print('my salary is too low, need to change my job')
else:
print('salary is above 5000, okay for now')
age = 30
if age > 50:
print('you are above 50. you are a senior developer for sure')
elif age > 40:
print('your age is bigger than 40. you... |
e180350b63cc478a403a3df45cc5e781d70c5d5f | carriehe7/bootcamp | /TupleCollectionHW.py | 1,642 | 4.5625 | 5 | # 1. Create a ‘technological_terms’ tuple that will contain the following items:
# a. python
# b. pycharm IDE
# c. tuple
# d. collections
# e. string
technological_terms = ('python', 'pycharm IDE', 'tuple', 'collections', 'string')
print('technological terms tuple collection : ' +str(technological_terms))
# 2. Print t... |
b50f799cc178142d142a44cb61d14999da786fc4 | tkouleris/PyTendex | /PyTendex.py | 2,901 | 3.5625 | 4 | #!/usr/bin/python
from Tkinter import *
import Tkinter
import tkMessageBox
def calculateTendex():
#Exception in case the user inserts string and not a number
try:
pointsVar = float(points.get())
missedFreeThrowsVar = float(missedFreeThrows.get())
missedShotsVar = float(missedShots.get())
reboundsVar =... |
f2fb1b2fca43fa13047dd4effc1063b70b65d904 | jhondoeelmisterio/traductor- | /traductor.py | 7,101 | 3.515625 | 4 | #Created with much love by Jhon Doe
#Importes
import os
import sys
#Bienvenida
os.system("sleep 2")
print (" >>>>>>>>>>>>>>>")
print (" Bienvenido ")
print (" <<<<<<<<<<<<<<<")
os.system("sleep 2")
print ("")
print ("Este script nos brinda un encripta... |
4b16ace8a2fea39cedd4ac67c30cf65b46752df4 | Fengkp/WGUPS-Routing-Program | /src/Controller/PackageAllocation.py | 1,383 | 3.71875 | 4 | # Algorithm to decide which packages go on which truck
# Return packages in lists?
# For now we'll just use the address.
# In the future, the first address to be noted will be the hub address.
# This address/distance will be referenced every time a truck runs out of packages.
def next_package(current_package, ready_pa... |
480305dca1ba463e7282ce08bd51f588f9533726 | charlesed/py-scripts | /Python2/sales-tax.py | 383 | 4 | 4 | #!/usr/bin/env python2
# Calculating some sales tax...
# What's your tax rate?
tax_percentage = float(raw_input("Tax rate(%): "))
tax_rate = tax_percentage / 100
# Now what's your price?
subtotal = float(raw_input("Subtotal: "))
# Do some math and print the total
print round(subtotal + (subtotal * tax_rate), 2)
#... |
efc8c80a3f474b8e7d42e54ad9b7d73f59b2f29a | ChebaCheba/Katas | /evenorodd.py | 200 | 4.15625 | 4 | 'Create a function that takes a number as an argument and returns "even" for even numbers and "odd" for odd numbers.'
def isEvenOrOdd(num):
if num%2==0:
return 'even'
else:
return 'odd'
|
7c71b651dc1c6ec01f7a716816811cd7de7ef56f | Wh1te-Crow/STACK | /Steck.py | 1,971 | 4 | 4 | #Клас стек
class Stack:
#Инициализация стека
def __init__(self):
self._stack = []
#Снять со стека элемент
def take(self):
a=self._stack[len(self._stack)-1]
self._stack=self._stack[:len(self._stack)-1]
return a
#Поместить элемент на стек
def put(self, x):
self._stack.append(x)
#Количество элементов в ст... |
a0468dc68f85e674418d364939a4439483c67290 | majj/AtlasCopco_prg | /test_class.py | 3,726 | 4.375 | 4 | """Примеры по созданию и использованию классов в питоне
Всё есть объект!
"""
class FirstClass: #когда интерпретатор достигнет инструкции class, он начнёт создавать объект класса с именем (ссылкой на объект)FirstClass
def set_data(self, value): #интерпретатор определяет метод класса (поведени... |
3b62c512ac80beed7afaad5de91c1b48cc079f10 | Werstef/LaB-CP | /Python/p1.py | 176 | 3.75 | 4 | #Lab1 II 5
for i in range(1, 11):
print("Efrem Ion Stefan")
#Lab1 II 6
for i in range(1, 13):
print(i, i ** 2)
#Lab1 I 4
a = 5
b = 4
print(a+b, a-b, a*b, int(a/b), a/b, a%b )
|
ab2bf9a36fb6f4c3cb80eac08716f0372743c817 | Linueks/fys3150 | /project_3/earth_sun.py | 1,190 | 3.6875 | 4 | import numpy as np
import matplotlib.pyplot as plt
plt.style.use("ggplot")
total_time = 1 #year
dt = 1e-3
time_steps = int(total_time/dt)
positions = np.zeros((time_steps, 2))
velocities = np.zeros((time_steps, 2))
accelerations = np.zeros((time_steps, 2))
def get_acceleration(t):
GM = 4 * np.pi ** 2 # [AU... |
fb0bc3c0d45f9b467c0935f9337f8d46b59dcd05 | fviaren/covid-19-stats | /dataframes.py | 862 | 3.578125 | 4 | import pandas as pd
# Create dataframe with data from summary of all countries
def create_countries_df(data=dict) -> "pandas.core.frame.DataFrame":
df = (
pd.DataFrame(data)
.transpose()
.sort_values(by=["Total Confirmed Cases"], ascending=False)
)
df = df.reset_index().rename(colu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.