blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
31bfe34578928e596fb926b71a25b8b30e541498 | jmih1/introduction-to-python | /max_val(midterm).py | 1,255 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Aug 19 23:49:41 2018
@author: brown
"""
def max_val(t):
""" t, tuple or list
Each element of t is either an int, a tuple, or a list
No tuple or list is empty
Returns the maximum int in t or (recursively) in an element of t
"""
tupMax = 0... |
61308ea6a35a92b606004cd4b9460921f8c4c400 | Khushi-S-B/Python_3.x_Programmes | /recursive factorial function.py | 143 | 3.984375 | 4 | def factorial(a):
if a==1:
return 1
else:
fact=a*factorial(a-1)
return fact
print(factorial(3))
|
91dee64b1db462d7d9d05f00e7613392b09f64bf | Aisha-K/MonteCarloSimulation | /CommissionsMCS.py | 2,407 | 3.609375 | 4 | #monte carlo simulation to estimate money for comission sales
#comission rate is based on percent to target
#Modified from https://pbpython.com/monte-carlo.html
import pandas as pd
import numpy as np
#import seaborn as sns
#sns.set_style('whitegrid')
class CommissionsMCS:
#defaults
num_reps=300 #employees that ha... |
76b5e03c3bd4a8ae33895e2d1cc2600bb9ef5b79 | emaestre/leet-code | /swap-nodes-in-pairs/swap-nodes-in-pairs.py | 439 | 3.65625 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
if(head == None or head.next == None):
return head
node = ListNode(head.next.val)
... |
44c5292f683a0e944e2ff81ae14e54d13e1fa53e | JatinRanaV1/Emirp-Number | /Emirp Number.py | 891 | 4.09375 | 4 | another_no = "yes"
while another_no == "yes" or another_no == "y" or another_no == "Y" or another_no == "Yes" or another_no == "YES":
x=int(input("Enter a number: "))
if x>=2:
y = x
rem = 0
sum = 0
count1 = 0
count2 = 0
y = str(x)[::-1]
y = int... |
16cdd78e56cbcbb3027ab8404e509fac85ea7b42 | LEO1612D/Python-Automation | /Testing/rearrange_test.py | 726 | 3.625 | 4 | from rearrange import rearrange_name
import unittest
class TestRearrange(unittest.TestCase):
def test_basic(self):
testcase = "Sparrow, Jack"
expected = "Jack Sparrow"
self.assertEqual(rearrange_name(testcase),expected)
#Edge cases
def test_empty(self):
testcase = ""
... |
a084bbf07ceb03dbfde4a4f4ca942c1fff5e6091 | frmeu9/EulerProject | /problems/Problem05.py | 924 | 3.609375 | 4 | # Smallest multiple
# Problem 5
# 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
# What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
# Il faut sortir tous les multiples de tous les nombres de 1 à 20 et trouver ... |
d3d1eb8dd6f228d5698b27494f059bb417e7a52e | khunpanggg/The-Internship-2020 | /Floating Prime.py | 668 | 3.921875 | 4 | """ Floating Prime """
def main():
""" main function """
while True:
num = float(input())
if(num == 0.0):
break
else:
if(10 >= num >= 1):
if((function(num) == True) or (function(num*10) == True) or (function(num*100) == True) or (function(num*1000... |
ec1c37abe1d795625f1aba5c8758fa931088df16 | IWever/thesis | /Model/Version-B/src/dynamicObjects.py | 3,000 | 3.890625 | 4 | from src.ship import Ship
""" Containing functions to create dynamic objects and ship definitions """
# Definition methods
def addShip(shipList, key, name, MMSI, LBP, width, depth, displacement, deadweight, nominalSpeed_kn):
shipList[key] = Ship(name, MMSI, LBP, width, depth, displacement, deadweight, nominalSp... |
5670ac0a2fd5f48a03289a22342c10656d16d753 | umutcangungor/python-tkinter-calculator | /calculator1.py | 5,615 | 4.0625 | 4 | # Importing the necessary modules
from tkinter import *
import parser
from math import factorial
root = Tk()
root.title('Calculator')
# It keeps the track of current position on the input text field
i = 0
# Receives the digit as parameter and display it on the input field
def get_variables(num):
g... |
c064c63b925af907dd427c7e940a3f95a4daafd5 | DianaGao/Unsupervised-learning-k-means-model | /K-means.py | 1,489 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 23 22:45:47 2019
@author: diana
"""
# import the libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#import the dataset
df = pd.read_csv('Mall_Customers.csv')
x = df.iloc[:, [-2,-1]]
#find the ideal number of clusters using W... |
5d9fe67b95331cbcde3f1c56d3b4cc5de85fb55a | ed-/chompy | /whom.py | 687 | 3.671875 | 4 | #!/usr/bin/env python
"""
WHOM.PY
Pipe in a prettytable document, and the table will be
whomped into a JSON document, a list of dictionaries
using the table headers as keys.
"""
import json
import sys
def whomp(table):
keys, rows = [], []
for line in table.split('\n'):
if not line or line.startswith(... |
c06ef5cb94f67c5eb25168e92affcca8476e633a | zschuster/Udemy_AdvancedPython | /Threads/multi_threading.py | 636 | 3.84375 | 4 | from threading import Thread
import threading
import math
# create some function that takes 1 argument
def sqrt_num(x):
"""
Take the square root of x
:param x: a list of real positive numbers
:return: printed square roots of numbers in x
"""
print(threading.current_thread().getName(), 'has begun.')
for num in ... |
017c1ef733a1e05dd2f0f76c3f9001fdf3e1c0b8 | zephyr-c/snake-game | /snake.py | 1,791 | 3.609375 | 4 | import turtle as t
STARTING_POSITIONS = [(0,0), (-20, 0), (-40, 0)]
MOVE_DISTANCE = 20
UP = 90
DOWN = 270
LEFT = 180
RIGHT = 0
DEFAULT_COLOR = ("lime")
# t.colormode(255)
from food import random_color
class Snake():
def __init__(self):
self.segments = []
self.create_snake()
self.head = self... |
eb3e9ca84c62fad89eb940b0444b396129d9e07b | popcorn1429/leetcode_algorithm | /leetcode_algorithm_00349.py | 328 | 3.671875 | 4 | class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
s = set(nums1)
t = set()
for i in nums2:
if i in s:
t.add(i)
r = list(t)
r... |
f8fc7c7ad2cafd41bc58afc4667c119d9db2fc49 | ayobamibolaji/CS_337_Project_2 | /fetch_recipe.py | 3,117 | 3.671875 | 4 | import sys
import json
import re
import urllib.request # for fetching the html content of a url
# documentation: https://docs.python.org/3/howto/urllib2.html
from bs4 import BeautifulSoup # for parsing the html content
# documentation: https://www.crummy.com/software/BeautifulSoup/bs4/doc/
'''
Parser Must Recogniz... |
a743e360c5680d77fd663432d697fdf546235770 | linannn/LeetCode_Solution | /103.二叉树的锯齿形层次遍历.py | 1,160 | 3.609375 | 4 | #
# @lc app=leetcode.cn id=103 lang=python3
#
# [103] 二叉树的锯齿形层次遍历
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import deque
from typing import List
class Solution:
... |
5d0cc11b3b98b09ab6d0ec275bfca85872043a91 | Bharti20/python_list_questions | /smallest_number.py | 152 | 3.53125 | 4 | numbers=[8,30,4,99,2,1]
index=0
i=numbers[index]
while index<len(numbers):
if numbers[index]<i:
i = numbers[index]
index=index+1
print(i) |
4b1ce5bd649632f983d0a9807eab4d0b8d476250 | Muhammadabuabakr/cs101-ITC-s18B | /a06.py | 1,319 | 3.5 | 4 | ## IMPORTS GO HERE
## END OF IMPORTS
### YOUR CODE FOR cumulative_marks() FUNCTION GOES HERE ###
def cumulative_marks(string):
"""This function change format of roll_number then read the name of student and
at last add the number of student.After that it append all data into new list """
lst =[]
lst1 = []... |
994b2d6fe508eb8c25ad5728fb80432c70503587 | santia-bot/python | /trabajos de la clase/tuplas.py | 1,078 | 4.3125 | 4 | """
tuplas
"""
"""
tupla = ("guadalupe", "antonio", "pilio", 32, "30076375609")
print("llamar un elemento:", tupla[0])
print("numeros de elementos",len(tupla))
subt = [:]
print( "\n subtupla:",subt )
#print(tupla[-2])
#tupla.append("juan") no se puede agregar
for i in lista2: #obtener los elementos de las listas
pr... |
9a0c957db71ef96b993835d9439ee0c0d6788cf7 | sourav-gomes/Python | /Part - II (Advanced Python)/Chapter 13 - Advanced Python 2/02_lambda.py | 617 | 4.375 | 4 | # Lambda functions: Functions created using an expression using 'lambda' keyword
# It can be used as a normal function. Usually done when trying to pass function as argument
## NORMAL FUNCTION AS WE WRITE
def func(a):
return a+5
x = 40
print(func(x)) # This will print 45
## WRITING THE SAME fUNCTION USING ... |
d7c454d311c5983410d05d5b6642d8b4818cffb2 | tomp/AOC-2016 | /day13/day13.py | 3,233 | 3.921875 | 4 | #!/usr/bin/env python3
#
# Advent of Code 2016 - Day 13
#
def is_open(x, y, seed=0):
"""Return True if (x,y) is not a wall. """
val = x*(3 + x) + y*(y + 2*x + 1) + seed
bits = bin(val).count('1')
return (bits % 2 == 0)
def display(xmax, ymax, history, seed=0):
"""Return a string representation o... |
49255fd44821406f8ced2fb07062409f8e3f316f | Kogoon/Algorithm-Study | /algorithmPractice/p01-1-sum.py | 499 | 3.5625 | 4 | # 2020.01.26
# 모두의 알고리즘 with 파이썬/이승찬/길벗
# 1부터 n까지 연속한 숫자의 합을 구하는 알고리즘 1.
# 입력: n
# 출력: 1부터 n까지 숫자를 더한 값.
def sum_n(n):
sum = 0 # 합을 계산할 변수 sum
for i in range(1, n+1):
sum = sum + i
return sum
print(sum_n(10)) # 1부터 10까지의 합. (입력: 10, 출력: 55)
print(sum_n(100)) # 1부터 100... |
de9feab7ce0c211a2c8da9deb0007dfc0cfbbee6 | Kcpf/MITx-6.00.1x | /Week 2-Simple Programs/problemSet2_problem1.py | 1,952 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jun 20 10:50:38 2020
@author: Fernando
"""
"""
Problem 1 - Paying Debt off in a Year
Write a program to calculate the credit card balance after one year if a person
only pays the minimum monthly payment required by the credit card company each month.
The following variabl... |
43c87a479002b825518d6c5d27c5fa25224f9f6b | SandraCoburn/python-django | /python-overview/error_exceptions.py | 4,031 | 4.65625 | 5 | ######################################
# #Errors and Exception Handling
######################################
#
# In this lecture we will learn about Errors and Exception Handling in Python.
# You've definitely already encountered errors by this point in the course.
# For example:
'''
print('Hello
'''
# Note how we g... |
71871f500d6dd0353616e7680a28088150d9db6d | dylanbaghel/python-complete-course | /section_23_decorators/02_decorator.py | 651 | 4.21875 | 4 | """
Decorator:
--> Decorators are functions.
--> Decorators wrap other function and enhace their behaviour.
--> Decorators are examples of higher order functions.
--> Decorators have their own syntax, using '@' (syntactic sugar)
"""
def be_polite(fn):
def wrapper():
print("What a pleasure t... |
745bbbd3500c08a279d0431a9d155c1b8d2c7c20 | johnalexwelch/Euler | /python/015_Lattice_Paths.py | 538 | 3.6875 | 4 | '''
Starting in the top left corner of a 2x2 grid, and only being able to move to the right and down,
there are exactly 6 routes to the bottom right corner.
How many such routes are there through a 20x20 grid?
'''
import time
def binomial(n,k):
total = 1
if k > n-k:
k = n-k
for i in range(1,k+... |
7c860de8f1488b3b4fa640c895b79ffa31832bef | paulofreitasnobrega/coursera-introducao-a-ciencia-da-computacao-com-python-parte-2 | /week1/matriz_mult.py | 798 | 4.125 | 4 | # Week 1 - Exercícios Adicionais (Opcionais)
# Exercício 2 - Matrizes multiplicáveis
# Duas matrizes são multiplicáveis se o número de colunas da primeira é igual
# ao número de linhas da segunda. Escreva a função sao_multiplicaveis(m1, m2)
# que recebe duas matrizes como parâmetro e devolve True se as matrizes forem
... |
1dd5384c6ec265ad5b8c40b6c0b9f4fd05226e90 | Raghumk/TestRepository | /File_IO.py | 778 | 3.71875 | 4 |
#Reading keyboard input
# Input & Output works in command line
'''
Name = input("Enter Name: ")\
print (Name)
'''
file = open('File_IO.py')
print ("Name of file : ", file.name)
print("Open/Closed : ", file.closed)
print("Opening mode: ", file.mode)
print ("File contents\n------")
print(file.r... |
90866ca82654fd087f09b959ae1c56371e7dc9bb | KRLoyd/holbertonschool-higher_level_programming | /original_repo/0x06-python-test_driven_development/0-add_integer.py | 407 | 4.3125 | 4 | #!/usr/bin/python3
def add_integer(a, b):
"""
Adds 2 integers.
Args:
a -- first integer
b -- second integer
Return: integer result of a and b
"""
if isinstance(a, (int, float, complex)) is False:
raise TypeError("a must be an integer")
if isinstance(b, (int, float, complex)... |
a17a9227738549dd3b36ea1316c5d87e84de6565 | papamuda-15/ujian-bootcamp-15 | /2.py | 763 | 3.609375 | 4 | import re
def is_username_valid(str):
check=False
x = re.findall("\W", str)
y = re.findall("[a-z]", str)
z=re.findall("[A-Z0-9]",str)
if (len(y) >0 and (len(str) >=5 and len(str) <=9) and len(x)==0 and len(z)==0):
check=True
else:
check=False
print("username",str," = ",check)
def is_password... |
d867a8ccdf3887c84493b0caa63a2c3e66a9e740 | BarSick69/for-range | /for3.py | 79 | 3.8125 | 4 | n=int(input("dati n "))
for n in range(0,n+1,+2):
if n!=0:
print(n) |
9c14b4bcc0d46975c199d11b8f5d33d9d7237c6a | jhennecruz/jhenne01 | /main.py | 1,241 | 3.71875 | 4 | import requests, sys
# Gets the contents of an image on the Internet to be
# sent to the machine learning model for classifying
def getImageUrlData(wwwLocationOfImage):
data = requests.get(wwwLocationOfImage).content
if sys.version_info[0] < 3:
# Python 2 approach to handling bytes
return data.... |
2bf539b4a9be7c92dfb8286d8a2e825df141a9e2 | ctc316/algorithm-python | /Lintcode/Ladder_28_S/1_Easy/213. String Compression.py | 521 | 3.609375 | 4 | class Solution:
"""
@param str: a string
@return: a compressed string
"""
def compress(self, str):
result = ""
prev_ch = ""
count = 0
for ch in str:
if ch != prev_ch and count > 0:
result += prev_ch + count.__str__()
... |
41bfc915547b5aa7b3b6d581695b2a124dac23a9 | giorgiagandolfi/programming_giorgia_gandolfi | /exercises/N-W_affinegap.py | 2,962 | 3.53125 | 4 | #import from math module infinite value
from math import inf
#create the dictionary to calculate the scores
f=open("./matrix.txt","r")
matrix=[]
score_matrix={}
for line in f:
line=line.rstrip()
line=line.split()
matrix.append(line)
for i in range(len(matrix[0])):
for j in range(1,len(matrix)):
... |
ec4f8ca867f1633abee278ebc0e5be2d79f6fdb6 | Tashwri93/Python-Exercise6 | /exercise6.2.py | 208 | 3.703125 | 4 | known_rivers = {
'nile': 'egypt',
'thames':'england',
'jordan': 'israel'}
for river, country in known_rivers.items():
print("The " + river.title()+ " runs through " + country.title())
|
fbacd8364cc1ff0b7e69dd8692393a92eecbd770 | KusumaNavya/cspp1-assignments | /M22/assignment5/frequency_graph.py | 503 | 4.25 | 4 | '''
Write a function to print a dictionary with the keys in sorted order along with the
frequency of each word. Display the frequency values using “#” as a text based graph
'''
def frequency_graph(dictionary):
"""frequency value"""
n_n = list(dictionary.keys())
n_n.sort()
for key in n_n:
print(... |
bd8f6c84ecfe8294f1b84d7e55af46894de7b373 | XuSShuai/data-structure-and-algorithm | /bit_array.py | 471 | 3.734375 | 4 | # 实现一个bit类型的数组0 ~ 319
arr = [0] * 10 # type(a[0]) = int, 10 * 32 = 320
index = 300
int_index = index // 32
bit_index = index % 32
print(int_index, bit_index, 1 << bit_index)
arr[int_index] = (arr[int_index] | 1 << bit_index)
print(arr[int_index])
print(arr)
index = 301
int_index = index // 32
bit_index = index %... |
d2fcbad138e8bb955bc7fc2642ebc93ea53a0469 | CyrilYenTW/LeetCodePractice | /PythonTest/Self Dividing Numbers.py | 417 | 3.515625 | 4 | class Solution:
def selfDividingNumbers(self, left, right):
result = []
for i in range(left, right + 1):
s = str(i)
flag = True
for index in range(1, len(s) + 1):
if ( s[index - 1] == '0' or i % (int)(s[index - 1]) != 0):
flag = False
break
if flag :
... |
1e726ea1541e252f466a18aa5fc1c15b4eba855f | Heartyhp/lpthw | /function/practice/ex_24.py | 1,058 | 4.28125 | 4 | print("Lets practice everthing")
print('you \'d need to know \'bout escaps with \\ that do :')
print('\n newlines\t tabs')
poem = """ \tTwinkle twinkle little stars
how i wonder what you are\n
up above world so high
\n \tlike a diamond in the sky """
print("-------------------")
pr... |
42c3139e47649a5c0659b519f9ad884550e578e7 | judeaugustinej/python-work-book | /Property/how_to_property_three.py | 1,545 | 3.5625 | 4 | class Wallet:
"""Accepts money in rupees
but store it in dollars
"""
def __init__(self,rupees):
self.rupees = rupees
#Getter Function
@property
def rupees(self):
return self._dollars
#Setter Function
@rupees.setter
def rupees(self,value):
self._do... |
c01298cd6c4e9677a612f30a06a7d89768e591aa | lavaFist/PythonLearning | /ex13.py | 540 | 3.953125 | 4 | """
This is a sample of script, you need to key in same number of
variables to use this script. In this case, the number of variables
is 3. So following is an example on how to use this script:
python ex13.py this is sample
"""
from sys import argv
script, first, second, third = argv
print "The script i... |
79c7ccbf5428b6a1bcf9810cda0bd0e0dc1866d3 | kurtrm/code-katas | /src/complex_num_mult.py | 594 | 3.96875 | 4 | """
Given two strings representing complex numbers,
return a string of the result of multiplying two complex numbers.
"""
def complexNumberMultiply(a, b):
"""
"""
complex_a, complex_b = eval(a.replace('i', 'j')), eval(b.replace('i', 'j'))
result = complex_a * complex_b
stringed_result =... |
a151a01a4284ec39b2cebb5bd1eb04bd88ab0792 | benjamindotrussell/Pentago | /Board.py | 19,617 | 3.53125 | 4 | import Tile
import Node
from copy import deepcopy
class Board(object):
def __init__(self):
self.board_state = []
self.score = 0
self.p1_win = None
self.p2_win = None
'''
make an empty board
return: an empty board
'''
def generate_board(self):
fo... |
5e3b73662269d1179da9ca211cdab29102789aa6 | vipulshah31120/Project2 | /Class2.py | 730 | 4.375 | 4 | # program to show that the variables with a value
# assigned in the class declaration, are class variables and
# variables inside methods and constructors are instance
# variables.
class Dog :
animal = 'dog'
def __init__(self, breed, color) :
self.breed = breed
self.color = color
Jackie = Dog... |
1c71b95dc14038dcd3f895935501f3df5fde3f4a | codefellows/seattle-python-401n2 | /class-04/lab-starter/band.py | 378 | 3.703125 | 4 | class Band:
def __init__(self, name, members=None):
self.name = name
self.members = members
def __str__(self):
return f"The band {self.name}"
def __repr__(self):
return f"Band instance. name={self.name}, members={self.members}"
class Musician:
pass
class Guitarist:
... |
3a9cc6198913843ea4b41f515f15426e5e31bcc7 | WinrichSy/Codewars_Solutions | /Python/7kyu/Largest5DigitNumberInASeries.py | 273 | 3.703125 | 4 | #Largest 5 Digit Number in a series
#https://www.codewars.com/kata/51675d17e0c1bed195000001
def solution(digits):
highests = []
for idx, val in enumerate(digits):
if val == '9':
highests.append(int(digits[idx:idx+5]))
return max(highests)
|
0dca9a3ab387eb5e097e37cfdccbbdf65db24996 | alvinalmodal/codewars | /tests/test_split_in_parts.py | 375 | 3.546875 | 4 | import unittest
from src.split_in_parts import split
class TestSplitInParts(unittest.TestCase):
def test_split(self):
self.assertEqual(split("supercalifragilisticexpialidocious", 3), "sup erc ali fra gil ist ice xpi ali doc iou s")
self.assertEqual(split("HelloKata", 1), "H e l l o K a t a")
... |
52fc951f03b2b220d999bd0363ca22a48d0e4df4 | tstu92197t/SC-project | /stanCode_Projects/boggle_game_solver/largest_digit.py | 800 | 4.46875 | 4 | """
File: largest_digit.py
Name: Wu Ting
----------------------------------
This file recursively prints the biggest digit in
5 different integers, 12345, 281, 6, -111, -9453
If your implementation is correct, you should see
5, 8, 6, 1, 9 on Console.
"""
def main():
print(find_largest_digit(12345)) # 5
print(f... |
9cb2b75de260727fd7ee2f889820fdaa4de254bf | ElaineVicente/ExerciciosPython | /circulo.py | 97 | 3.984375 | 4 | raio = float(input("Digite um numero "))
n = 3.14159
area = n * (raio *raio)
print("A = ", area) |
d3b75ce1d42b5e561fded9a37c47f93104cb0c05 | Alejandro-08/Practica_02 | /Tarea_1_1.py | 1,029 | 3.75 | 4 | # Tarea_1_1
class Restaurant():
def __init__(self, name, type, open):
self.restaurant_name=name
self.cuisine_type=type
self.number_served = 0
def describe_restaurant(self):
print("\nThe name of the restaurant is " + self.restaurant_name + '.')
print("T... |
5d63922623a89870243213a15f3e2be5accecb8d | michaelseyo/blackjack | /Blackjack.py | 13,092 | 4.3125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri May 15 21:05:13 2020
@author: Mike
"""
import random
from random import shuffle
#create BLACKJACK, play against the com. OOP? How do i incorporate classes/methods/inheritance
class Deck:
def __init__(self):
'''Creates an instance of a list ... |
b2c47a9cb587dfc4d94f4c3a4ad0892fac965cc9 | hwynn/tagger | /guiTesting/TextTagsDynamic.py | 1,845 | 3.5 | 4 | from kivy.app import App
from kivy.lang import Builder
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ListProperty
from kivy.factory import Factory
from kivy.uix.textinput imp... |
142c03a8c7e9a6f119f15353674f1d749bb6b093 | rdspring1/comp509 | /misc/hwk3.py | 3,246 | 3.71875 | 4 | #!/usr/bin/env python
# Propositional Connectives:
# Not !
# Atomic Proposition = Integers
import copy
prepositional_connectives = ["!", "&", "^", "?", "="]
binary_connectives = ["&", "^", "?", "="]
# cnf - A formula represented in Conjunctive Normal Form
# prop - A set of truth assignments for AP
def sat_solver(cnf,... |
5ecccc31f12068a6074bacc6d61e22fd1035bc8d | apalaciosc/quantum_python | /clase_02/sum.py | 204 | 3.71875 | 4 | a = int(input('Ingresa el primer número: '))
b = int(input('Ingresa el segundo número: '))
def suma(a, b):
resultado_suma = a + b
return resultado_suma
resultado = suma(a, b)
print(resultado)
|
2bf8812e755e5463c001fcda7c5852c02bff4840 | Zhouyinyun/lpthw2018 | /ex13.py | 344 | 3.578125 | 4 | # -*- coding: utf-8 -*-
from sys import argv #从系统中提取参数
script, one, two, three, fourth = argv
print "The script is called:", script
script = raw_input("what is script?")
print "Your first variable is:", one
print "Your second variable is:", two
print "Your third variable is:", three
print "Your fourth variable is:", ... |
e978f3a72d5380c8fe6552992fc8cf3cda1af009 | avinpereira/code-forces | /easy_problem.py | 344 | 3.546875 | 4 | # def is_hard(l):
# for i in l:
# if(i == 1):
# return "HARD"
# return "EASY"
def is_hard(l,p):
sorted_list = sorted(l)
if sorted_list[p - 1] == 0:
return "EASY"
return "HARD"
people = int(input())
response_list = [int(x) for x in input().split(' ')]
print(is_hard(res... |
0ad5ca7704d6a1f8f5c1b852a59e6b8a01092cd2 | asaf19-meet/YL1-201718 | /lab5/lab5.py | 378 | 3.84375 | 4 | from turtle import *
import random
class Square(Turtle):
def __init__(self,size):
Turtle.__init__(self)
self.shapesize(size)
self.shape("square")
def random_color(self):
a = random.randint(0,255)
b = random.randint(0,255)
c = random.randint(0,255)
self.col... |
5a6732c8a7f71e752fa8389cc05c2079972dea84 | 382982408/myPythonStudy | /pythonBase/下划线.py | 1,059 | 3.65625 | 4 | #! usr/bin/env python
# -*- coding: utf-8 -*-
# Author: zhang xiong
# Time: 2018/3/27
'''
_halfprivate_method()可以直接访问,确实是。不过根据python的约定,应该将其视作private,而不要在外部使用它们,
(如果你非要使用也没辙),良好的编程习惯是不要在外部使用它。同时,根据Python docs的说明,_object和__object的作用域限制在本模块内。
'''
class A(object):
def __init__(self):
pass
def __fullpriv... |
108f7c1f4f3048c999b174fcdfde52426ae73dea | Studies-Alison-Juliano/geek_university_curso_python | /secao5_etrutuas_logicas_e_condicionais/estrutura_logica_and_or_not_is.py | 976 | 4.28125 | 4 | """
Estrutura logica : And, or, not, is
Operadores unário:
not
Operadores binário:
and, or, is
if ativo or logado:
print('Bem vindo(a) usuário!')
else:
print('Você precisa ativar sua conta. Pf verifique seu email')
Regras de funcionamento:
Para o "and" ambos valores precisam ser True
Para o "or" um o... |
15c27d59d68465fafa505b5a1009976247e54dc4 | ITInfra-101/Python_practice_public_repo | /exercise_11_primary_number_function_pub.py | 601 | 4.28125 | 4 | # Ask the user for a number and determine whether the number is prime or not.
# (For those who have forgotten, a prime number is a number that has no divisors.).
# You can (and should!) use your answer to Exercise 4 to help you. Take this opportunity to practice using functions, described below.
def prime_number():
... |
edc2bf6d232cd487d69dc83417cf9f78a773c4a1 | buxizhizhoum/leetcode | /maximum_depth_of_binary_tree_1.py | 1,295 | 4.34375 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9... |
26b78526d7323cd49861d7f0fc7ab57437ef0944 | Matt-Brigida/project_euler | /1/vector_approach.py | 558 | 3.828125 | 4 | # If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
import math
import numpy as np
three_max = int(math.floor(999 / 3))
three_vec = np.empty([three_max + 1])
for i in range(thre... |
02e3c28490bbed17dbca0c2fc2ef4e59fdca2929 | DaHuO/Supergraph | /codes/CodeJamCrawler/16_0_2/smaree/pancakes.py | 734 | 3.828125 | 4 | # input() reads a string with a line of input, stripping the '\n' (newline) at the end.
# This is all you need for most Google Code Jam problems.
t = int(input()) # read a line with a single integer
for i in range(1, t + 1):
# input is the string
stack = input()
# We count how many groups of symb... |
908e6ef9ca84ca1ce836f283423f4ec2757d9c6d | satyampandeygit/ds-algo-solutions | /Algorithms/Strings/Caesar Cipher/solution.py | 636 | 3.921875 | 4 | def main():
#input the length of the unencrypted string
l = input()
#input unencrypted string
st = input()
# input the number of letters to rotate the alphabet by
s = int(input())
l_s = [chr(i) for i in range(ord('a'),ord('z')+1)]
l_b = [chr(i) for i in range(ord('A'),ord... |
ccd17da0c20a05b47deb8abe5432dbf439627036 | luckychummy/practice | /bubbleSort.py | 214 | 3.953125 | 4 | def bubbleSort(arr):
n=len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j+1]<arr[j]:
arr[j+1], arr[j] = arr[j],arr[j+1]
return arr
A=[5,3,4,2,1]
print(bubbleSort(A))
#i=1, j=0, 3<5, |
83200b2c2c9bfb7bdc65004fe72911fd55185597 | SandeepPadhi/Algorithmic_Database | /Strings/largest_word_Dictionary.py | 705 | 4.03125 | 4 | """
Date:16/02/2021
The following problem is solved using Stack.
Link:https://practice.geeksforgeeks.org/problems/find-largest-word-in-dictionary2430/1#
"""
class Solution:
def findLongestWord (ob, S, d):
# code here
Ans=""
D=d
for d in D:
s=[i for i in S]
... |
e3d7a6d6b6d2d00f1720aae2dd4a778f589726d9 | BubbleXu/leetcode | /190_reverse_bits/reverse_bits.py | 644 | 3.96875 | 4 | # Reverse bits of a given 32 bits unsigned integer.
#
# For example, given input 43261596 (represented in binary as 00000010100101000001111010011100),
# return 964176192 (represented in binary as 00111001011110000010100101000000).
#
# Follow up:
# If this function is called many times, how would you optimize it?
class... |
b125b1878debb416672f6233bc1f5c9d57e9db2f | williamBieneman/Patent-Word-Count | /Release/PatentWordCount.py | 10,417 | 4.46875 | 4 | import patent_search as ps
# Welcomes user, gives them options.
print("""\
Hello! Welcome to Patent Word Count v0.1.0-alpha
This program can:
• Find patent information
• Find the most used words in a patent
• Find patent numbers and other information from given criteria\
Remember you can press ctrl+c at ... |
7f03db39276442deb343ffc585058cb106bd92ce | avallarino-ar/leetcode | /python/medium/longest_palindromic_substring.py | 1,135 | 4.0625 | 4 | #!/usr/bin/env python
#
# description: Longest Palindromic Substring
# difficulty: Medium
# leetcode_num: 5
# leetcode_url: https://leetcode.com/problems/longest-palindromic-substring/
#
# Given a string s, find the longest palindromic substring in s. You may
# assume that the maximum length of s is 1000.
#
# Example 1... |
710f69987f9d2c5b3eb45823ecfc7853c7f6dd82 | sonumja/HackForyourMother-CenterForMunicipalFinance | /Scrapper.py | 572 | 3.546875 | 4 | import pandas as pd
from googlesearch import search
# read test file and get first url to be scrapped.
df = pd.read_excel("Test.xlsx")
#Create the search term
targeturl=df.iloc[0,2]+df.iloc[0,3]
state=df.iloc[0,0]
name=df.iloc[0,1]
#Google url save it into a csv file
for url in search(targeturl, tld='... |
fc00c752d00b7e8bbfb3105b7159d2d483441588 | viveksharmapoudel/python_pycharm | /threadInBanking.py | 1,282 | 3.515625 | 4 | import threading
import time
import random
class BankAccount(threading.Thread):
accountBalance= 100
def __init__(self, name, moneyRequest):
threading.Thread.__init__(self)
self.name=name
self.moneyRequest=moneyRequest
def run(self):
threadLock.acquire()
BankAcco... |
1b63f735de06c9be16047f1fab1a765a6ebb834c | maksimkolasau/Python-Interview-Data-Scientist | /6. class.py | 168 | 3.75 | 4 | class Car:
def __init__(self, color, speed):
self.color = color
self.speed = speed
car = Car('blue', '100 mph')
print(car.speed)
print(car.color)
|
e5ededa4a32ba1fd28339f7b06c7337f57616567 | HUSTXUECHENGXI/Biometric_in_NUS | /hw1Q1.py | 419 | 3.96875 | 4 | #nus biometrics Assignment 1
# Part1
# Q1
# Add up the even numbers from 1 to 100 and output their sum, using while and for loops.(5)
def addevenfor():
sum=0
for a in range(1,101):
if a%2!=0:
continue
else:
sum=sum+a
print(sum)
def addevenwhile():
sum=0
a=0
while (a<100):
a += 1
... |
e09c22f234bf4c20ef29e3338670fbed6571e6de | edgardeng/design-patterns-in-python | /Strategy/transportation_strategies.py | 1,421 | 3.921875 | 4 | from __future__ import annotations
from abc import ABC, abstractmethod
from typing import List
class Routing(ABC):
"""
routing algorithm can be extracted to its own class with a single buildRoute method.
The method accepts an origin and destination and returns a collection of the route’s checkpoints.
... |
b2e7144589ded22a25a9fe2657efca972a84bc0e | chetan-mali/Python-Traning | /Python Programs/string.py | 325 | 3.703125 | 4 | while(True):
try:
name = input("Enter name :")
lst = name.split()
if(len(lst)<2):
raise ValueError("Only one name Entered !!")
except Exception as e:
print("Invalid Input !!", e)
else:
break
index = name.index(' ')
print(name[index:],name[0:in... |
36d85118154cb78750e412b67e19bbe741885c31 | nickom/python-class | /lesson-5/html_write.py | 552 | 3.8125 | 4 | import csv
html = "<table>"
# writing out the header of the html
html = html + "<thead><tr><th>title1</th><th>title2</th><th>title3</th></tr></thead><tbody>\n"
with open("eggs.csv", "rU") as csvfile:
reader = csv.reader(csvfile)
for row in reader:
# we replaced this written out line with a loop below
# html = h... |
47576974f98fae9eba046893a56bbd3ccf8861b1 | sameer0000/atm | /bank.py | 611 | 3.84375 | 4 | bank=customer
bal=50000
bank=input("how can i help you ")
if atmpin == 2000:
print('select 1 for eng\n')
print('select 2 for withdrawl\n')
print('select 3 for deposit\n')
x=input('')
if x==1:
print('Your balance')
print(bal)
elif x==2:
print('enter the amount you want to withdrawl')
y=input('')
if y>bal... |
56d9c42bd70b36cac46302447fcd72060c9d8dd7 | YOON81/PY4E-classes | /10_Tuple/tuples.py | 2,187 | 3.796875 | 4 | t = tuple('lupins')
#print(t) # ('l', 'u', 'p', 'i', 'n', 's')
#print(t[0]) # l
#print(t[1:3]) # ('u', 'p')
t = ('L',) + t[1:] # 튜플의 요소를 수정 살 수 없다. 하지만 또 다른 하나의 튜플을 대체 할 수 있다 **
#print(t) # ('L', 'u', 'p', 'i', 'n', 's')
# Comparing tuples
txt = 'but soft what light in youder window breaks'
words = txt.split()
t... |
5ae8619617213db7a65c50aa53145b371f9787a8 | youssefzaky/phd | /Vision-with-Function-Spaces/datasets.py | 1,885 | 3.890625 | 4 | import os
import urllib
def fetch_file(url, destname, force=False):
"""Fetch a dataset file from a URL.
Parameters
----------
url : string
The URL where the file is located.
dest : string
Relative path to the destination.
force : bool, optional
If True, download the da... |
76b6953896dfba0b5d2cd3df56dd8a360a4f0c32 | SaiSriLakshmiYellariMandapaka/python_programs | /age.py | 1,622 | 3.625 | 4 | import datetime
import tkinter as tk
from PIL import Image,ImageTk
#window
window=tk.Tk()
window.geometry("300x500")
window.title(" Age Calculator App ")
#labels
nlabel=tk.Label(text="Name: ",font=("Helvetica",10))
nlabel.grid(column=0,row=1)
ylabel=tk.Label(text="Year ",font=("Helvetica",10))
ylabel.grid(column=0,ro... |
3ca98e71ef0f7c9341dd918d6c1f585aeb06c757 | Rilord/math | /number.py | 334 | 3.734375 | 4 | num = int(input("Введите целое число К"))
b = set()
print('Повторяющиеся элементы')
while num > 0:
t = num % 10
b.add(t)
if (t not in b):
b.add(t)
elif (t in b) and ((-t - 1) not in b):
b.discard(t)
b.add(-t - 1)
print(t)
num //= 10
print(b)
|
1ff0296c6c3071ae7bb3f800b660977b72e1bf5b | vuanhtu1993/Python-fundamental | /linear_regression/linear_regression/simple_linear_regression.py | 1,360 | 3.875 | 4 | import matplotlib.pyplot as plt
import numpy as np
my_data = np.genfromtxt('data.csv', delimiter=',') # read the data
X = my_data[:, 0].reshape(-1, 1) # -1 tells numpy to figure out the dimension by itself
ones = np.ones([X.shape[0], 1]) # create a array containing only ones
X = np.concatenate([ones, X], 1) # coca... |
54b379a462a3aaf1608ff3da896a10c1436ba209 | QtTao/daily_leetcode | /88.合并两个有序数组/solution.py | 1,449 | 3.796875 | 4 | # !/usr/bin/python
# -*- coding: utf-8 -*-
# author : Tao Qitian
# email : taoqt@mail2.sysu.edu.cn
# datetime : 2021/6/17 00:11
# filename : solution.py
# description : LC 88 合并两个有序数组
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
""" 双指针 """
... |
40c2dd8b71910df84d7dd0a9f91919a9c35860a0 | MikeOnAMission/Password_Cracker | /password_cracker.py | 1,626 | 4.375 | 4 | from sys import argv
import string
alphabet = ''
alphabet += string.ascii_letters
alphabet += string.digits
alphabet += string.punctuation
"""A program that generates every possible combination of a string using '*' for unknown characters."""
script, string = argv
def first_character():
"""Returns list containi... |
982876fe49794c84708a9ad91c6b60efca869de3 | MTES-MCT/ecobalyse | /data/common/distances/distances.py | 7,007 | 3.625 | 4 | import json
import requests
import pandas as pd
import geopy.distance
import random
import time
from datetime import datetime
"""Script to get the distances between countries for a list of countries. To identify countries we use the 2 letters code (France->FR).
# Runtime
Takes about 1 minute to compute 10 routes.
1... |
f50460af3ede45af0f44bfda6f26be9948bcf098 | jennikimfer/CoMoDo_Password_Generator | /Main.py | 2,144 | 3.75 | 4 | from random import randint, choice
import string
def findPassLength():
#print("reached findPassLength")
length = randint(10, 25)
#print(length)
return length
def checkValid(password):
file = open("passwords", "r")
contents = file.read()
if (password in contents):
retur... |
5e824e80b1fc165be33154f8d1c69028f5814e3c | hadrizia/coding | /code/advanced_algorithms_problems/list_2/resort.py | 1,415 | 3.78125 | 4 | '''
Valera is afraid of getting lost on the resort. So he wants you to come up with a path he would walk along. The path must consist of objects v1, v2, ..., vk (k ≥ 1) and meet the following conditions:
Objects with numbers v1, v2, ..., vk - 1 are mountains and the object with number vk is the hotel.
For any in... |
fe01c04cbdbb970d7b25aa612831f015e65cb479 | alexpsimone/leetcode | /easy/unique_morse_code_words.py | 1,640 | 3.75 | 4 | # Return the number of different transformations among all the words, given a list of words.
# If empty list, will there be 1 or 0 transformations?
# If there's a letter/character not in the alphabet, should I handle it a certain way?
# Are the words sorted in a certain way (alphabetically, for instance)?
def uni... |
74f96a1efe1f49887ab77bdc474dcaa0d431431f | ashishpratikpatil/garbage_collector_blynk_app | /forward_backward.py | 875 | 3.5625 | 4 | import RPi.GPIO as GPIO
from time import sleep
GPIO.setmode(GPIO.BOARD)
GPIO.setup(35,GPIO.OUT)
GPIO.setup(36,GPIO.OUT)
GPIO.setup(37,GPIO.OUT)
GPIO.setup(38,GPIO.OUT)
#sleep(3)
print("car moving forward")
GPIO.output(35,GPIO.HIGH)
GPIO.output(36,GPIO.LOW)
GPIO.output(37,GPIO.HIGH)
GPIO.output(38,GPIO.LOW)
sleep(2)
p... |
c7d7f6389823b6b157f3649a539aa89d2b776899 | Parzha/Second_assignment | /assi2project2.py | 1,565 | 4.0625 | 4 | import random
game_choices = ["paper","rock","scissors"]
print("Welcome to rock paper scissors We are going to play for 5 rounds and after that we decide the winner ")
round_counter=0
draw_counter=0
win_counter=0
lose_counter=0
while(round_counter<5):
print("Round", round_counter+1)
print("... |
17e34e398801c8a45b74f78e2f109118b731f250 | SarcoImp682/Simple-Tic-Tac-Toe | /Topics/Nested lists/Running average/main.py | 245 | 3.859375 | 4 | my_string = input()
int_list = [int(letter) for letter in my_string]
counter = 0
average_list = []
while counter < len(my_string) - 1:
average_list.append((int_list[counter] + int_list[counter + 1]) / 2)
counter += 1
print(average_list)
|
2c6182a1cde958aec2d7dba39bf6bc88046e0f40 | Santiagozm16/Simulacion | /Simulacion Masa Resorte Amortiguada.py | 2,928 | 3.71875 | 4 | import numpy as np
import matplotlib.pyplot as plt
import math
"""Desarrollado Por:
Alejandra Pedraza Cárdenas
Santiago Rodríguez Prada"""
#datos - Ingreso por teclado
m = float(input("Ingrese el valor de la masa (Kg): "))
c = float(input("Ingrese el valor de la constante de amortiguamiento (Kg/s): "))
k = float(inpu... |
e3a86787da10d73647eb983b2783f895debeefc6 | elsys/python-2017-2018 | /2018-05-31-maze/maze.py | 2,885 | 3.828125 | 4 | import turtle
import random
class Cell(object):
STEP = 20
DOWN = 0
RIGHT = 1
UP = 2
LEFT = 3
def __init__(self, row, col):
self.row = row
self.col = col
self.walls = [True, True, True, True]
self.visited = False
@staticmethod
def oposite_direction(direction):
return (direction + 2) % 4
def s... |
30504a6faa16baa44283084994f3c861e5f2d5af | ndvssankar/cspp1-assignments | /M8/p2/assignment2.py | 589 | 4.15625 | 4 | # Exercise: Assignment-2
# Write a Python function, sumofdigits, that takes in one number and returns the sum of digits of given number.
# This function takes in one number and returns one number.
s = 0
def sumofdigits(n):
'''
n is positive Integer
returns: a positive integer, the sum of digits... |
260035440b9149f0df279e78f6fbea6ddaceb39f | purpurato/eul | /Problem19.py | 206 | 3.78125 | 4 | """
Project Euler
Problem 19 - Counting Sundays
"""
import datetime
count = 0
for y in range(1901,2001):
for m in range(1,13):
if datetime.date(y, m, 1).isoweekday() == 6:
count += 1
print(count)
|
be8c5691c30486e4e3d1ae2913eb0a71b34dd666 | furas/python-examples | /turtle/spiderweb/main.py | 720 | 4.1875 | 4 | from turtle import *
from math import sin, cos, pi
shape("circle")
turtlesize(0.3)
speed(0)
#--- settings ---
# number of main lines
#n = int(input("give number of main lines: "))
n = 15
# length of main lines
#r = int(input("give length of main lines: "))
length = 200
# number of steps on every main line
steps = ... |
b8875e6443015af52e29d3ff40c3cec92355ccfa | cbnsndwch/sagefy | /server/modules/sequencer/pmf.py | 1,998 | 3.53125 | 4 | """
PMF, or Probability Mass Function.
"""
class PMF(object):
def __init__(self, hypotheses=None):
"""
Create a new PMF, given a list of hypotheses.
Internally, hypotheses is a dict of hypo: probability.
"""
if isinstance(hypotheses, (tuple, list)):
self.hypoth... |
1c937f0ffbd997ff30ee1d35fd49c12aa3ff4c09 | tbnsok40/Algorithm | /BAEKJOON/[baek] 10410.py | 485 | 3.828125 | 4 | # for _ in range(int(input())):
#
# name, date, birth, courses = input().split()
# date = date.split('/')
# year = int(date[0])
#
# birth = birth.split('/')
# year_birth = int(birth[0])
# courses = int(courses)
# if year >=2010:
# print(name, 'eligible')
# elif year_bi... |
3477de7be95e800c564efbfd4dba97bf14116ceb | mavb86/ejercicios-python | /seccion3/ejercicio15.py | 522 | 4.15625 | 4 | # Ejercicio 15
# Dadas dos variables numéricas A y B, que el usuario debe teclear, se pide realizar un algoritmo que intercambie
# los valores de ambas variables y muestre cuanto valen al final las dos variables.
print("****************************")
print("* SECCION 3 - EJERCICIO 15 *")
print("***********************... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.