blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
456ee627755a5e76e7d40d513f7e6dad89f42b20 | JoseJaramillo/Pseudolabel | /Final.py | 5,906 | 3.640625 | 4 | """
Created on Mon Oct 23 14:18:35 2017
Artificial Intelligence & Robotics
Neural Networks project
Pseudolabel as supervised learning
Comparison NN vs NN+PL
"""
# This code runs parallelly a Neural Network with and without Pseudolabeling
import tensorflow as tf
import numpy as np
import matplotlib.pyplot ... |
734f20e8699851f17305ed7f56f9e6037e8c1122 | mselivanov/pysharpen-the-tools | /pysharpen/algorithms/new_year_chaos.py | 2,460 | 4.21875 | 4 | """
Module solves assignment from hackerrank
It's New Year's Day and everyone's in line for the Wonderland rollercoaster ride!
There are a number of people queued up, and each person wears a sticker indicating
their initial position in the queue.
Initial positions increment by from at the front of the line to at th... |
7e179944a196918964990be007e2828c68d61ebc | jamithireddy/programming_basics | /Python_Basics/loops.py | 767 | 4.21875 | 4 | # While loops:
# use ctrl + c to break an infinite loop
from random import randint
print("Lets play a guessing game!")
start = input("Do you want to play?(Y/N): ")
if start.lower() == 'y':
print("I have guessed an integer between 0 and 25. You guess the number")
num = randint(0, 26)
n = 1
while True:
... |
eb8ca51d6ca834f045467d2dc6120746e767bfe3 | yanggak12/Numerical-Analysis | /linear algebra/cramer.py | 762 | 3.6875 | 4 | # Ax = b 형태의 선형 연립 방정식을 푸는 방식
# b 행렬을 A1에서는 1열에 넣어 det(A1)을 만들고 A2에서는 2열에 넣어 det(A2)를 만든다.
# 이를 이용해 x1, x2를 구한다.
# x1 = det(A1)/det(A) , x2 = det(A2)/det(A)
from numpy import array
from numpy.linalg import det
A = array([[4, 1, -1], [3, -1, 2], [-1, 2, 3]])
B = array([-2, 1, 1])
A1 = array([[-2, 1, -1], [1, -1, 2], [... |
38bb1990540511f3ff778c8c3364531f684381f1 | songchaogeng/store | /Jason_store.py | 5,366 | 3.671875 | 4 | '''
任务:
优化购物小条
10张机械革命优惠券,打0.5
20张卫龙辣条优惠券 打0.3
15张HUA WEI WATCH 打0.8
随机抽取一张优惠券。
商城:
1.准备一些商品
2.有空的购物车
3.钱包
4.结算
流程:
看你输入的产品存不存在,
若存在
若钱够了:
将商品添加到购物车
钱包余额减去... |
efed1754139fa490e23fd00d8d8664ac16bf3b1e | shriharshs/AlgoDaily | /leetcode/624-maximum-distance-in-arrays/main.py | 1,033 | 3.796875 | 4 | """
1st approach:
- since we need to find the min/max from a different array, we need 2 variables to store the previous min and max
e.g. min max
[
[4,5],
[1,2,3], 4 5
[1,2,2], 1 5
[-10,1], 1 5
]
144 ms, faster than 38... |
40077fcb20ed188caa62b290992b6da43d4e0223 | AliceSaraOtt/PythonPros | /Test/control/function.py | 754 | 3.734375 | 4 | # -*- coding:utf-8 -*-
def fun1(): # 没有返回值的时候 返回None
for i in range(101):
print i
def fun2(num2,num1=10):
return num1 + num2
def fun3(city):
n_city = []
for i in city:
if i != '广州':
n_city.append(i)
return n_city
city = ['哈尔滨','北京','杭州','广州','深圳']
n_city = fun3(city)... |
9ebbe0bdb51e5ebb8f05f792141d01366111f8a5 | DineshDDi/full-python | /while.py | 314 | 4.125 | 4 | '''
a = 0
while a<3:
b = 0
while b<3:
print(a,b," ",end=" ")
b+=1
print("")
a+=1
'''
'''
for a in range(0,3):
for b in range(0,3):
print(a,b," ",end=" ")
print("")
'''
'''
a = float(input("numbers"))
b= a%2
if b!=0:
print("odd")
else:
print("even")
'''
|
2e9aecd995546f4b92721cdf9b06824b2a100012 | qwerty1910/DSA-LAB-WORK | /LAB3/Hanoi.py | 591 | 3.75 | 4 | from mystack import Stack
class Hanoi:
def __init__(self,numdisk):
self.numdisk=numdisk
self.towers=[Stack(),Stack(),Stack()]
for i in range(numdisk,-1,-1):
self.towers[0].push(i)
def moveDisk(self,src,dest):
self.towers[dest].push(self.towers[src].pop())
def moveTower(self,n,src,spare,dest):
if n==0:
... |
1d8e1fb16c627322ee63e6ec493543887f4b2c5d | JavierBH/IS1_P3 | /csv-to-sql.py | 436 | 3.640625 | 4 | #!/usr/bin/env python3
import sys,os
import sqlite3
con = sqlite3.connect("database.db")
cur = con.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS {0} (id,lat,long,name);".format(sys.argv[1]))
to_db = []
for line in sys.stdin:
print(line)
if(line[0] != '@'):
to_db.append(line.split(",",3))
cur.exe... |
c9b8b244e7a93df12e79ad271ff5972397492f3f | codekebabs/python_learning | /calculator/main.py | 1,703 | 4 | 4 | def add(a, b):
c = a + b
print("Sum of {0} and {1} is {2}".format(a,b,c))
def multiply(a, b):
c = a * b
print("Product of {0} and {1} is {2}".format(a,b,c))
def divide(a, b):
c = a / b
print("Quotient of {0} and {1} is {2}".format(a,b,c))
def substract(a, b):
c = a - b
print("Differen... |
df47b527d15f85cb3a97ea6198089b7ea7caf0d9 | Zirafnik/conways-game-of-life | /conways.py | 2,571 | 3.765625 | 4 | import random, time, copy
def game():
# choose grid height and width
HEIGHT = int(input('Choose grid HEIGHT: '))
WIDTH = int(input('Choose grid WIDTH: '))
new_grid = []
# fill initial grid
for i in range(HEIGHT):
row = []
# fill row with column values
for j in... |
b608f2dcd51b3d362661ad42161b640ffa62421f | liamthanrahan/lunchtime-python | /2017/session-2/problem2.py | 208 | 3.9375 | 4 | def build_triangle(n):
triangle = ""
for i in range(int(n)):
triangle += "*" * (i + 1)
if (i != int(n) - 1):
triangle += "\n"
return triangle
print(build_triangle(5))
|
c79b517ace1c7c05af5d5c9e0bbf802b78df280d | stylate/paxos | /gift/test_solution.py | 3,012 | 3.734375 | 4 | #!/usr/bin/python3
import unittest
from solution import find_gifts, output
class TestGift(unittest.TestCase):
def test_basic(self):
prices = [
('Candy Bar', 500), ('Paperback Book', 700), ('Detergent', 1000), ('Headphones', 1400),
('Earmuffs', 2000), ('Bluetooth Stereo', 6000)
... |
43b6edf68aa1623232afd5b9884d0ef819210c7a | namnguyen3019/Dynamic-Programming-Problem | /Construct-Word/count_construct_memoi.py | 859 | 4.03125 | 4 | '''
Given a target string and list of words.
Return number of way that the target string can be generated from the list
'''
def countConstruct(target, words, memo={}):
if target in memo: return memo[target]
if target == '': return 1
totalCount = 0
for word in words:
if target.find... |
fb6c35ff70362ca174757ffc5557e8876ea0dbe8 | murchie85/OpenWeatherMap | /getcurrentWeather.py | 3,368 | 3.609375 | 4 | import APIconnect
import urllib, json
import os
import urllib.request
from json import dumps
from datetime import datetime
"""
-----------------------------------------------------------------------------------------------
PROGRAM: currentWeather.py
Author: Adam McMurchie
Summary: This program is designed to pull curr... |
909d45129a4cb6f2b64f4c649578e52693374c2e | sslockk/Ai_data_structure_base_main | /Lesson02/L02_work_08.py | 320 | 3.609375 | 4 | num = int(input('Введите натуральное число'))
x = int(input('Введите число для поиска'))
i = 0
while num != 0:
n = num % 10
num = num // 10
if x == n:
i += 1
print(f'Количество искомой цифры {x} встречается - {i} раз')
|
fc2dd050f63ba4146291cdf7a5d570df5fe002fd | JoTaijiquan/Python | /Python101-Revised/1-6/1-0613.py | 508 | 3.5625 | 4 | #Example 1.6.13
#Python 3.6.5
#Created By Jooompot Sriyapan
def example_613():
x = [1,2,3]
try:
print (x[2])
except:
print ("Ha Ha Ha")
try:
print (x[6])
except:
print ("Error x is out of range")
example_613()
'''
try:
except
ใช้ดักจับ error เมื่... |
8d4b3dceef527ebc2b2d072a2d190580605c7381 | thalyssa/python-studies | /Básico/pre-and-sucessor.py | 187 | 3.984375 | 4 | #Recebe um número e mostra o antecessor e o sucessor do mesmo
var = int(input())
print('Você digitou o número: {}, cujo antecessor é {} e o sucessor é {}'.format(var, var-1, var+1))
|
a503bc76e0d0a1fa5a4509634662b544c534d952 | un4ckn0wl3z/pythonpract | /files/friends.py | 579 | 3.734375 | 4 | friends = input('Input the friend names, separate by commas (no space, please) : ').split(',')
people = open('people.txt', 'r')
people_nearby = [line.strip() for line in people.readlines()]
people.close()
friends_set = set(friends)
people_nearby_set = set(people_nearby)
friends_nearby_set = friends_set.intersection(... |
8bf76abf78f61d045b1d27ed8c60aaf466ed095d | cgxabc/Online-Judge-Programming-Exercise | /Lintcode/NextGreaterElementI.py | 1,527 | 4.03125 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 11 20:05:56 2018
@author: apple
"""
"""
You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1's elements in the corresponding places of nums2.
The Next... |
8761a1abafd6b19d2d83ee04f5a2ffc77d8b5fd8 | osamascience96/Python | /OOP_UDEMY/Lecture4/overloading.py | 347 | 4.0625 | 4 | class Square:
def __init__(self, side):
self.side = side
# overloading the add operator by adding the sides of the 2 squares
def __add__(self, squareObj):
return((4 * self.side) + (4 * squareObj.side))
squareOne = Square(4)
squareTwo = Square(5)
print("Sum of sides of both the squares ... |
648dc4954ae3768fab74fbfe95419f599abfe809 | Kamakepar2029/PythonSSHServerTutorial | /src/shell.py | 2,205 | 3.671875 | 4 | from cmd import Cmd
class Shell(Cmd):
# Message to be output when cmdloop() is called.
intro='Custom SSH Shell'
# Instead of using input(), this will use stdout.write() and stdin.readline(),
# this means we can use any TextIO instead of just sys.stdin and sys.stdout.
use_rawinput=False
# The... |
65e374853478702509c275eabf5b92d2653e74fe | tylerwh/Module8 | /more_fun_with_collections/calculate_half_birthday.py | 428 | 4.0625 | 4 | """
Author: Tyler Hochstetler
The purpose of this program is to calculate the half birthday based upon the most recent birthday.
"""
import datetime
from datetime import timedelta
def half_birthday(date):
"""Accepts a datetime of recent birthday and returns the date 6 months later."""
half_b_day = date + timedel... |
1355e744e9565d6c9559100a7dbf3af5f2a03d6d | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/bob/6b7219e3992444d0af498e570b629c6f.py | 590 | 4.21875 | 4 | def hey(str_in):
"""
Bob the lackadaisical teenager.
"""
# get rid of whitespace and "empty" characters
str_in = str_in.strip()
if str_in.endswith('?'):
# '?' on it's own is not upper
# isupper is true if all letter chars are upper
if str_in.isupper():
return... |
d5c648142cfe12cafc2d0ec632079cc7b057e573 | crazykuma/leetcode | /python3/0083.py | 721 | 3.703125 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
# 在原来的链表上操作,双指针
p1=head
if not head:
return head
p2=head.next
whi... |
f1821d7ca7cc0970556105dc2a944dce942e6e06 | SUMORAN/algorithm-practices | /jianzhioffer/21.IsPopOrder.py | 1,063 | 3.671875 | 4 | # -*- coding:utf-8 -*-
'''
《栈的压入、弹出序列》
题目描述
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。
假设压入栈的所有数字均不相等。
例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,
但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)
'''
'''
解题思路:
按照popV的顺序push后pop,看能不能行得通
'''
class Solution:
def IsPopOrder(self, pushV, popV):
stack = []
... |
2663c3fb4be589a138c40d21410d54a8e95d2eac | sulimanfarzat/python_basics | /string_app/silly.py | 1,099 | 4.125 | 4 | '''
Created on Jan 5, 2020
@author: suliman farzat
'''
import random
from string_app import words
from _ast import If
def silly_string(nouns, verbs, templates):
# Choose a random template.
template = random.choice(templates)
# We'll append strings into this list for output.
output = []
# Keep ... |
ef97e0cf4c5140d9c519efd65534af44b7ee2c28 | DarinZhang/lpthw | /ex13/add13.1.py | 638 | 3.765625 | 4 | # -*- coding: utf-8 -*-
from sys import argv
# 个人信息调查问卷
script, name, age, height, weight, hometown = argv
print "\nPlease verify the personal information you entered:\n"
checkName = "\t Is your name %r? Y(es) or N(o):" % name
raw_input(checkName)
checkAge = "\t Is your age %r? Y(es) or N(o):" % age
raw_input(chec... |
01c233a408f4f20b9f730f9acd4fa219c20d4cad | michaelyorkpa/python-tstp | /obj_test.py | 154 | 3.640625 | 4 | def same(obj1,obj2):
return obj1 is obj2
class Square:
def __init__(self):
pass
sq1=Square()
sq2=sq1
sq3=Square()
print(same(sq1,sq3))
|
f65cda3a2f978540457af379d97ddddfaaa9100b | vikram1045/permuatations | /gen_perm_usinglists.py.py | 311 | 3.765625 | 4 | from itertools import permutations
count=0
print("enter list of numbers:")
l=[int(x) for x in input().split()]
print("")
print("permutations of entered numbers are:")
perm=permutations(l)
for i in perm:
print(i)
count +=1
print("")
print("number of loops repeated are {}".format(count))
|
69237ef4f82d649fdebe90e0f6736aeb11834dce | kruthikapalleda/python | /occurence_nonRepeted.py | 472 | 3.734375 | 4 | def first_non_occurence(str1):
my_dict = {}
for i in range(0,len(str1),1):
if str1[i] in my_dict.keys():
my_dict[str1[i]] = my_dict[str1[i]] + 1
else:
my_dict[str1[i]] = 1
print(my_dict)
for k,v in my_dict.items():
if v == 1:
print(... |
baeffcb13e50f1569e02e57f98ae6de1529760f5 | serdarsenturk/python-algorithm-solutions | /linked-list/main.py | 688 | 3.96875 | 4 | class Node:
def __init(self, value):
self.value = value
self.nextNode = None
class LinkedList:
def __init__(self):
self.head = None
def printList(self):
currentNode = self.head
while currentNode:
print(currentNode.data)
currentNode = cur... |
8aff2567450375205ed74676cfa8632eb92c0156 | mahdi-zafarmand/leetcode_practice | /66.PlusOne.py | 964 | 3.5625 | 4 | class Solution:
# def plusOne(self, digits: List[int]) -> List[int]:
# # recursive implementation
# if digits[-1] != 9:
# new_digits = list(digits)
# new_digits[-1] += 1
# return new_digits
# elif len(digits) == 1:
# return [1, 0]
# els... |
ef6273db92dbfe330123a38a1f1ade7279502be1 | noogler617/Guessing-Game | /game.py | 640 | 4 | 4 |
# g = GuessingGame()
# g.rand_choice gives you the random number
# g.guess() starts the game
import random
class GuessingGame():
def __init__(self):
self.rand_choice = random.randint(0,10)
def reset_random(self):
print('Resetting random number')
self.rand_choice = random.randint(0,10)
... |
788ce128b1e3e7f47c9eb7cfd905002dbe192a4b | Madhav-Somanath/LeetCode | /September/06-ImageOverlap.py | 2,074 | 3.640625 | 4 | """ Two images A and B are given, represented as binary, square matrices of the same size.
(A binary matrix has only 0s and 1s as values.)
We translate one image however we choose (sliding it left, right, up, or down any number of units),
and place it on top of the other image. After, the overlap of this translatio... |
3b11ef3b827876d9782d160cc4071f1355e93a2a | Abresq/Python-1 | /MachineLearning.py | 646 | 3.859375 | 4 | #First program in Python and first Machine learning try
#Is there sun or no
from sklearn import tree
features = [[7,0], [8,1], [9,1], [6,0]] #0 = AM || #1 = PM
labels = [1, 1, 0, 0] #1 = Sun || #0 = No Sun
clf = tree.DecisionTreeClassifier()
cld = clf.fit(features, labels)
hour = raw_input ("Cual es la hora?\n")
m... |
a71d53668641b81fdb67e44ce377a052a9242d7a | AdamZhouSE/pythonHomework | /Code/CodeRecords/2638/60723/251117.py | 742 | 3.640625 | 4 | def average(array,i,j):
aver=0
for item in range(i-1,j):
aver=aver+array[item]
aver=aver/(j-i+1)
return aver
def calculate_s(array,i,j):
aver=average(array,i,j)
total=0
for item in range(i-1,j):
total=total+(array[item]-aver)**2
total=total/(j-i+1)
return total
number... |
c831762395b81138f12f175dd0f8aa8121ba0672 | geraldo1993/CodeAcademyPython | /Tip Calculator /Reassign in a Single Line.py | 586 | 3.984375 | 4 | '''Okay! We've got the three variables we need to perform our calculation, and we know some arithmetic operators that can help us out.
We saw in Lesson 1 that we can reassign variables. For example, we could say spam = 7, then later change our minds and say spam = 3.
Instructions
On line 7, reassign meal to the value... |
ea8e004117229ceaae0265a4d2d6775e8149a761 | Tsunadmi/Python-starter-homework | /005_functions-1/Home _work_3.py | 339 | 3.9375 | 4 | number_1 = int(input('Text the first number: '))
number_2 = int(input('Text the second number: '))
def answer(a, b):
while a != 0 and b != 0:
if a > b:
a = a % b
else:
b = b % a
print(a + b)
def main():
answer(number_1, number_2)
if __name__ == '__mai... |
7e39b5595d47a25f9e626ed1e8b7f698b061960f | MichaelReel/adventofcode-2020 | /Day_02/day_02.py | 1,251 | 3.75 | 4 | #!/env/python3
import re
text_file = open("Day_02/input", "r")
lines = [x for x in text_file.readlines()]
# Part 01
regex = r'^(?P<min>\d+)-(?P<max>\d+)\s(?P<char>[a-z]):\s(?P<pass>[a-z]+)$'
parse_line = re.compile(regex)
passes = 0
fails = 0
for line in lines:
m = parse_line.match(line)
if not m:
p... |
0fe3549664f0c48015a6c6b40311be1230ac5968 | rangerkevin/algorithms-sedgewick-wayne | /src/chapter_2/section_3/quickSort.py | 1,030 | 3.75 | 4 | import random
class Quick:
def __init__(self):
print("Quick sorting: ")
def sort(self, alist):
self.sort_helper(alist, 0, len(alist) - 1)
def sort_helper(self, alist, lo, hi):
if hi <= lo:
return
splitPoint = self.partition(alist, lo, hi)
self.sort_he... |
0440cce395e1fc035acb1fe42913a93fdba7091a | DmitryVlaznev/leetcode | /225-implement-stack-using-queues.py | 2,920 | 4.03125 | 4 | # 225. Implement Stack using Queues
# Easy
# Implement a last-in-first-out (LIFO) stack using only two queues. The
# implemented stack should support all the functions of a normal stack
# (push, top, pop, and empty).
# Implement the MyStack class:
# void push(int x) Pushes element x to the top of the stack.
# int p... |
09f18f833c9d813aa3eefc6e34f5bf732dcb6c9f | w5688414/JobInterviewInAction | /zijietiaodong/KthNode.py | 412 | 3.671875 | 4 | # Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def kthSmallest(root,k):
stack=[]
while(root or stack):
while(root):
stack.append(root)
root=root.left
root=st... |
4f16912cdf9c9e85d8443250dc9a5269e5e467b4 | hectorRperez/ejercicios-programacion-funcional | /ejercicio5_practica.py | 415 | 3.921875 | 4 | """ Ejercicio 5
Escribir una función que reciba una frase y
devuelva un diccionario con las palabras que contiene y su longitud.
diccionario = { palabra : longitud}
"""
def aplicar_funcion(frase):
palabras = frase.split()
longitud = map(len, palabras)
return dict(zip(palabras, longitud))
i... |
5bd6b79102858e5a5313633aec2e56b25314b5ad | ryanSoftwareEngineer/algorithms | /design/353_design_snake_game.py | 4,727 | 4.375 | 4 | '''
https://leetcode.com/problems/design-snake-game/
Design a Snake game that is played on a device with screen size height x width. Play the game online if you are not familiar with the game.
The snake is initially positioned at the top left corner (0, 0) with a length of 1 unit.
You are given an array food where f... |
a289d2621ee016eb30a0f2dcf12fdb8753ef13f9 | scheidguy/ProjectE | /1-50/prob7.py | 461 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 16 13:43:51 2020
@author: schei
"""
def get_nth_prime(n):
primes = [2]
num = 2
while len(primes) < n:
num += 1
prime_flag = True
#Only need to check if divisible by other primes
for prime in primes:
if num % prime ... |
146b4b4bf855c9e87e6f780efa734ba3e6bc1964 | faker-hong/testOne | /python其他学习/装饰器/多重装饰器.py | 422 | 3.75 | 4 | # 先应用最下面的装饰器,然后进入内层函数是一个函数的适合再调用上面的装饰器就成了<b><i>hello-world</i></b>的效果
def block(func):
def function_in():
return "<b>"+func()+"</b>"
return function_in
def italic(func):
def function_in():
return "<i>"+func()+"</i>"
return function_in
@block
@italic
def test():
return "hello-worl... |
69c4409e282cef3b6b01cf0b914b1d8e4acf13e5 | podhmo/individual-sandbox | /daily/20170203/example_json/02dictdiff.py | 522 | 3.734375 | 4 | import json
import datetime
def uppercase(d):
if isinstance(d, dict):
return {k.upper(): uppercase(v) for k, v in d.items()}
elif isinstance(d, (list, tuple)):
return [uppercase(x) for x in d]
else:
return d
person = {"name": "foo", "age": 10, "createdAt": datetime.date(2000, 1, 1... |
0fd24ec31719707e692f852270a4c65a7e7e5c06 | BrennanOrmes/Projects-Python | /Cards NEW/Blackjack.py | 809 | 3.578125 | 4 | #-------------------------------------------------------------------------------
# Name: Blackjack
# Purpose:
#
# Author: cnys
#
# Created: 09/09/2015
# Copyright: (c) cnys 2015
# Licence: <your licence>
#-------------------------------------------------------------------------------
from Deck imp... |
430ecc28ba82822c8e63eaf845d46e4dc9cc946c | amit-talentica/Python-Fundamentals-Pluralsight- | /test_analyzer.py | 1,655 | 3.71875 | 4 | import unittest
import os
def analyze_text(filename):
""" Calculate the numbers of line """
lines = 0
chars = 0
with open(filename, 'r') as f:
for line in f:
lines += 1
chars += len(line)
return lines, chars
class TextAnalysisTests(unittest.TestCase):
""" Test... |
b9004d0bcb1f3fffd630e038093efa100160ff1e | islamfares-web/python1 | /Problem 1 a .py | 355 | 3.8125 | 4 | def f(n):
global N
N += 1
if n==0 or n==1 or n==2:
return 1
else:
return f(n - 1) + f(n - 2) + f(n - 3) + f(n//3)
z=int(input("Enter range of n between zero and ...:"))
for i in range(z):
N=0
print(f(i), end=" ")
N = 0
s=int(input("\nEnter an integer:"))
print(f(s))
... |
6f4e41fc1450b463e15ca9100908697d064c4444 | vv1101/learning | /fizzbuzz.py | 428 | 3.5625 | 4 | fizz = []
buzz = []
fizzbuzz = []
for x in range(1, 101):
n = ''
if x % 3 == 0:
n += 'fizz'
fizz.append(n)
if x % 5 == 0 and x % 3 != 0:
buzz.append('buzz')
if x % 5 == 0:
n += 'buzz'
if n == 'fizzbuzz':
fizzbuzz.append('fizzbuzz')
if x % 5 !... |
8ad8c335a0f019778035853e8171bc3e142c494c | guulyfox/Demonkeyse-Manell | /8-15/another.py | 674 | 4.09375 | 4 | #!/usr/bin/python
num = input("please input a number in 1-100:")
if num.isdigit():
if 1 <= int(num) <= 100:
print(num)
else:
print("please input a number in 1-100")
elif num.isalpha():
print("please input 1-100 number")
else:
print("please don't input specific character")
try:
num = i... |
648e0c47761303c66f1b6866526a3b136f5c6d6b | rakib05r/Python | /Prime2.py | 135 | 4 | 4 | flag=1
n=input("Enter the number")
for i in range(2,n):
if(n%i==0):
print(n," is not prime")
flag=0
break
|
dea6fa90cb82b15753d9d0226a691889c57246af | MaiziXiao/Algorithms | /Leetcode/数组字符串链表/92-medium-Reverse Linked List II.py | 1,308 | 4.03125 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
"""
Reverse a linked list from position m to n. Do it in one-pass.
Note: 1 ≤ m ≤ n ≤ length of list.
Example:
Input: 1->2->3->4->5->NULL, m = 2, n = 4
... |
bbd094cace38971ba0cbbb9ffd5d0ae46d1b559b | VanessaKang/NetworkSecurity | /ServerHTTPS/WebServer.py | 2,128 | 3.5625 | 4 | #import socket module
from socket import *
import ssl
serverSocket = socket(AF_INET, SOCK_STREAM)
#------------------------------------------------
"""
Prepare a sever socket
"""
#Starting from Python 2.7.9, it can be more flexible to use SSLContext.wrap_socket() instead.
##ssl.wrap_socket(serverSocket, keyfile='... |
8b65030175f605c390d3c6e5ddde8e6ea001de77 | mikeodf/Python_Line_Shape_Color | /ch3_prog_4_all_color_names_1.py | 13,667 | 4 | 4 | """ ch3 No.4
Program name: all_color_names_1.py
Objective: Show a palette using web colors that are known to Tkinter/Python.
Keywords: canvas, rectangle, color web color, redundant colors.
============================================================================79
Comment: Python or Tkinter has a large collec... |
73af51e92a12529b455aef34752c92aeb01e754a | tanjo3/HackerRank | /Python/Strings/Alphabet Rangoli.py | 517 | 3.75 | 4 | def print_rangoli(size):
alphabet = "abcdefghijklmnopqrstuvwxyz"
alpha_stack = []
alpha_string = alphabet[size - 1]
width = (size << 2) - 3
for i in range(size):
print("-".join(alpha_string).center(width, "-"))
alpha_stack.append(alpha_string)
alpha_string = alpha_string[0:i... |
45ae950813e415bf89e106217b00f7d89e7de1d2 | lamnguyen9396/nguyenhonglam-fundamental-c4e23 | /Fundamentals/Session2/homework/bai1.py | 380 | 4.21875 | 4 | height=int(input("your height? ="))
print(height, "cm")
weight=int(input("your weight? ="))
print(weight, "kg")
BMI=weight/((height/100)**2)
print("BMI =",BMI)
if BMI<16:
print("you are severely underweight")
elif BMI<18.5:
print("you are underweight")
elif BMI<25:
print("you are normal")
elif BMI<30:
p... |
5cef72d8f338c689a9d72b89c9264c692e46e362 | aeksei/PY110-2021-1 | /map_3.py | 560 | 3.59375 | 4 | from itertools import repeat
def my_round(num):
return round(num, 2)
lambda num: round(num, 2)
if __name__ == '__main__':
my_floats = [
4.356345,
6.0934,
3.245235,
9.77545,
2.164234234,
8.884234235,
4.595235346645
]
print(list(map(my_round, m... |
f61ad7c60b674314c8fdee4a2039f9cb36c34ac7 | Pablo00000/kody | /python/funkcje01.py | 673 | 3.640625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# funkcje01.py
def sumuj(l1, l2):
"""
Funkcja sumuje 2 podane liczby
"""
suma = l1 + l2
print("Suma", suma)
def odejmij(o1, o2):
"""
Funkcja odejmuje 2 podane liczby
"""
roznica = o1 - o2
print("Różnica", roznica)
... |
6f07cd7b6fc5deb6c226ae72ab58a7ca085e0dab | JiyooonPark/python | /python-basics/chapter3/3_3_for.py | 439 | 3.71875 | 4 | # basic for loop
a = [1,2,3,4,5]
for i in a:
print(i)
b = [(1,'one'),(2,'two'),(3,'three')]
for (i,j) in b:
print(j)
c = [90,100,98,85,80]
for i in c:
if i>=95:
print("A+")
elif i>=90:
print("A")
elif i>=80:
print("B+")
else :
print("Pass")
for i in range(0,10... |
f27a7a31daa53db680d15dccecf41df6c6d4753b | anuragull/algorithms | /leetcode/23.Merge_k_sorted_lists.py | 1,208 | 3.984375 | 4 | """
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6
"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = No... |
14ad6ab66629806ae5127e190e98f69901b65adf | ARAVIND1702/eco-official | /main.py | 285 | 3.90625 | 4 | a=input("enter your age:")
while(true):
if a>=100:
print ("invalid data")
elif a<0:
print ("invalid data")
elif:
if a>=18:
print ("You can eligible to vote")
else:
print ("you cannot eligible to vote")
pass |
f3d03f4c4adbe888a0b055ed9321fec36439c84f | panyisheng/network-security-technology | /Project/numberPrime.py | 1,856 | 3.53125 | 4 | '''
Filename: numberPrime.py
Author: Pan Yisheng
Description: generate big prime and compute rsa key pair
'''
import random
from gcd import *
from primality_tester import *
from random import randrange, getrandbits
import time
# Function to test primality
def NumberIsPrime(n):
if (n==2 or n==3):
return True
if (n... |
90e1e421e45bb17dbf29bcbd8bd12330b939b5ba | LeeWoojin-99/Algorithm | /360Page.py | 311 | 3.734375 | 4 | '''
360 Page
안테나
Sort Algorithm Problem
'''
n = int(input())
arr = list(map(int, input().split()))
distance = []
for i in arr:
dist = 0
for j in arr:
dist += abs(i-j)
distance.append((i, dist))
distance.sort(key = lambda x: [x[1], x[0]])
print(distance[0][0])
'''
4
5 1 7 9
''' |
8df9665554185bf2b74e3acea303bace688a9c92 | gp22/How-to-Think-Like-a-Computer-Scientist | /ch15/ch_cl2_q8.py | 4,676 | 4.25 | 4 | # In games, we often put a rectangular “bounding box” around our sprites
# in the game. We can then do collision detection between, say, bombs and
# spaceships, by comparing whether their rectangles overlap anywhere.
# Write a function to determine whether two rectangles collide.
# Hint: this might be quite a tough exe... |
687ddfc59500b4687a2e264a4c9eeb8d0bf447bf | Santos-Jefferson/DataStructuresFromScratch | /zombie_in_matrix.py | 1,817 | 4.03125 | 4 | '''
Given a 2D grid, each cell is either a zombie 1 or a human 0. Zombies can turn adjacent (up/down/left/right) human beings into zombies every hour. Find out how many hours does it take to infect all humans?
Example:
Input:
[[0, 1, 1, 0, 1],
[0, 1, 0, 1, 0],
[0, 0, 0, 0, 1],
[0, 1, 0, 0, 0]]
Output: 2
Explanat... |
6b1fa5264930ae74deb628a3e82702aff11e0ca1 | mtcolvard/covid_development_work | /transformations/grokkingAlgo.py | 3,159 | 3.53125 | 4 | from collections import deque
graph = {}
# graph["start"] = {}
# graph["start"]["a"] = 6
# graph["start"]["b"] = 2
#
# graph['a'] = {}
# graph['a']['fin'] = 1
#
# graph['b'] = {}
# graph['b']['a'] = 3
# graph['b']['fin'] = 5
#
# graph['fin'] = {}
#
# infinity = float("inf")
# costs = {}
# costs["a"] = 6
# costs["b"] = ... |
5ba8da466e8a63dc95e8cbe0ab2170289848580c | burbol/scripts | /Python/HOME/Python_Opt.py | 7,008 | 3.984375 | 4 | # -*- coding: utf-8 -*-
"""
# =====================================================================
#
# Scriptfile Lecture 9
# -------------------------
# Computational Economics
# (c) Juergen Jung, 2012
#
# =====================================================================
"""
import math
from pylab import *
impor... |
d1cf2f35529f30823c37ed92381147657e61adc1 | berserker5000/python-hardWay | /fuctions/21.py | 569 | 3.765625 | 4 | __author__ = 'kud'
def add(a,b):
print "Adding %d + %d" %(a,b)
return a+b
def subtract(a,b):
print "Subtracting %d - %d" %(a,b)
return a-b
def multiply(a,b):
print "Multiplying %d * %d" %(a,b)
return a*b
def devide(a,b):
print "Deviding %d / %d" %(a,b)
return a/b
a = add(30,5)
s = su... |
71dee4ae4836043bca25022bed162fb887119f88 | adechan/School | /Undergrad/Third Year/Artificial Intelligence/Lab03/AIHomework3.py | 8,883 | 3.53125 | 4 | import queue
import math
class State(object):
# python nu suporta mai mult constructori
def __init__(self, capacitate_barca, n1_misionari, m1_canibali,
pozitie_barca, n2_misionari, m2_canibali):
self.capacitate_barca = capacitate_barca
self.n1_misionari = n1_misionari
... |
3c9819c919a0ddc4237ce99747c50175d0201d85 | hanxuema/LeetCodePython | /Problems/Eazy/0349.intersection-of-two-arrays.py | 548 | 3.5625 | 4 | #
# @lc app=leetcode id=349 lang=python
#
# [349] Intersection of Two Arrays
#
# @lc code=start
class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
if len(nums1) == 0 or len(nums2) == 0... |
720d6e6d5f33149ce8351cd8d2ee381d48391888 | pactonal/cse231 | /proj07.py | 6,159 | 3.75 | 4 | ###############################################################################
# Project 7 | csv file reading
# Gets file as input
# Processes file data and displays it
# Asks user to plot data
# If yes, plot
# If no, exit
###############################################################################
import pylab... |
d31fb816a43ead36023cf8cc655b065c685756ce | thanhtd91/proso-apps | /proso/models/prediction.py | 16,703 | 3.53125 | 4 | from math import exp
from proso.time import timeit
import abc
class PredictiveModel(metaclass=abc.ABCMeta):
"""
This class handles the logic behind the predictive models, which is
divided into 3 phases:
* **prepare**: the model loads the necessary data from the environment
* **predict**: the mod... |
909b98fb9825d97f193b88a7f0f9839169809683 | StBogdan/PythonWork | /Leetcode/259.py | 1,354 | 3.828125 | 4 | import unittest
from typing import List
# Method: 3sum, but count moving right down when below limit
# Time: O(n^2)
# Space: O(n)
class Solution:
def threeSumSmaller(self, nums: List[int], target: int) -> int:
if len(nums) < 3:
return 0
snums = sorted(nums)
triples = 0
... |
ec8dab731434fda0888a1a66285b9a622d82f96e | amadjarov/thinkPython | /workspace/Chapter6/ex6_7.py | 235 | 4.1875 | 4 | def is_power(a, b):
if a % b == 0 and a/b % b == 0:
#str(a)
#str(b)
print str(a) + " is power of " + str(b)
else:
print str(a) + " is not power of " + str(b)
is_power(6, 3)
|
91f76f8a26d98ff371bf561e7551e04c095719ca | besemerr/python_projects | /guess_a_number.py | 381 | 3.796875 | 4 | import random
while True:
try:
usernumber = int(input("Guess a number, 1 through 100... "))
while usernumber != random.randrange(1,101):
print(int(input("Try again: ")))
else:
print("Congratulations, You've guessed correctly!")
input(... |
e88240efea460e4429c2efe0ee0525f162b3850a | gigaquads/neurotic | /neurotic/examples/tensorflow_docs/basic_image_classifier.py | 814 | 4.375 | 4 | """
https://www.tensorflow.org/tutorials/quickstart/beginner
"""
import tensorflow as tf
# load and prepare dataset. convert ints to floats
mnist = tf.keras.datasets.mnist
mnist_data = mnist.load_data()
x_train, y_train = mnist_data[0]
x_test, y_test = mnist_data[1]
x_train = x_train.astype(float) / 255.0
x_test ... |
2e93092e43c56802a58a00b3a029555185b06c64 | Deepak1609/HackerRank-10-days-of-Statistics | /Day 4: Binomial Distribution I.py | 570 | 3.53125 | 4 | def fact(n):
return 1 if n == 0 else n*fact(n-1)
def comb(n, x):
return fact(n) / (fact(x) * fact(n-x))
def b(x, n, p):
return comb(n, x) * p**x * (1-p)**(n-x)
s,t=list(map(float, input().split(" ")))
odds=s/t
print(round(sum([b(i, 6, odds / (1 + odds)) for i in range(3, 7)]), 3))
# using math package
... |
db99377aab437cd64b75599678c07585db33021b | jailukanna/Python-Projects-Dojo | /03.Complete Python Developer - Zero to Mastery - AN/02.Python Basics II/truth_falsey.py | 149 | 3.609375 | 4 | username = "john"
password = "123"
# if username and password both exists
if username and password:
print("you have both username and password") |
e6c5ade41da8804bf0889a7c12f319878cf705bb | th3fall3n0n3/my_first_calc_extended | /modules/calc200_900.py | 869,610 | 3.59375 | 4 | def calc(num1, sign, num2):
if num1 == 200 and sign == '+' and num2 == 900:
print('200+900 = 1100')
if num1 == 200 and sign == '+' and num2 == 901:
print('200+901 = 1101')
if num1 == 200 and sign == '+' and num2 == 902:
print('200+902 = 1102')
if num1 == 200 and sign == '+' and n... |
63c3a64797bad70c24a729352a595f5d8ae37bd5 | dBounde13/Hangman | /Topics/For loop/Vowel count/main.py | 171 | 3.8125 | 4 | string = "red yellow fox bite orange goose beeeeeeeeeeep"
vowels = "a", "e", "i", "o", "u"
count = 0
for i in string:
if i in vowels:
count += 1
print(count)
|
87f257140aae9b5834386580645d6d94958c98a6 | SubSage/WAPI | /MainFolder/GenerateMap.py | 5,947 | 3.921875 | 4 | from pull_entities import Watson
from MapGenerator import MapOfLocations
from MapGenerator import HeapOfThings
from Vector2 import Vector2
import random
import wikipedia
#BEFORE WE START:
#Here's a very long explanation of what's about to go down:
#Using Watson, we're going to make several quieries in Wik... |
2d2a1a98da3dc2407049b9b387f1f7ef7797b336 | anvesh2502/Stochastic-Optimization | /optimization.py | 2,083 | 3.546875 | 4 | import time
import random
import math
people=[('Seymour','BOS'),('Franny','DAL'),('Zooey','CAK'),('Walt','MIA'),('Buddy','ORD'),('Les','OMA')]
# LaGuardia airport in New york
destination='LGA'
flights={}
for line in file('schedule.txt') :
origin,dest,depart,arrive,price=line.strip().split(',')
flights.setde... |
335b95fde6e9999f7bd9f0aef759e1a336c85ff7 | ccacoba/cmsc117project | /dmcspy/ode/adams_bashfort/methods.py | 1,830 | 3.5 | 4 | __author__ = 'Imman Narciso'
from time import time
import numpy as np
"""
This Adam's Bashforth method is under the dmcspy.odes
While the Euler, and RK methods makes use of singel step methods, or use only a one previous point to compute the next.
The Adam's Bashforth method gets two initial points x0, and x1... |
1e21b3806f5244865e84329f1613a5d471e1f2b9 | bbabaaba/leetcode | /141_Linked_List_Cycle.py | 875 | 3.6875 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# @param head, a ListNode
# @return a boolean
def hasCycle(self, head):
if head == None:
return False
if head.next == None:
return False
tmp = head.next
if tmp.next == ... |
0c230134e777561af32181f04af70cb876c69704 | hrishikeshtak/Coding_Practises_Solutions | /leetcode/LeetCode-150/Two-Pointers/15-3Sum.py | 1,285 | 3.6875 | 4 | """
15. 3Sum
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k,
and j != k, and nums[i] + nums[j] + nums[k] == 0.
Notice that the solution set must not contain duplicate triplets.
"""
from typing import List
class Solution:
def threeSum(self, nums: List[in... |
9664d0c9ee71e890be21d251f86e1635a74ae268 | mxpr/ios-build-utils | /utils/packager.py | 2,460 | 3.75 | 4 |
import os
import shutil
import subprocess
from tempdirectory import TempDirectory
class Packager:
"""
Packager utility
output: the path to create the final package in
Usage:
Define the package structure by adding files or directories
using `add(path)` and then create the packa... |
0caff115f74a38e0309ca68cf13bfc192a059f19 | amathebest/parser_site | /main/parsing_scripts/classes_and_methods.py | 23,512 | 3.71875 | 4 | from .utils import support_variables as sv
# function that returns True if a symbol is terminal and False otherwise
def isTerminal(element):
isSymbol = False
if element == "(" or element == ")" or element == "*" or element == "+" or element == "." or element == "-" or element == "[" or element == "]" or element... |
20323698d41c564c15fab0a12b429b86719425f6 | JpBongiovanni/PythonFunctionLibrary | /abcdCallStack.py | 779 | 4.15625 | 4 | # The call stack is how Python remembers where to return the execution after each function call. the call stack isn't stored in a variable in your program; rather, Python handles it behind the scenes. when your program calls a function, Python creates a frame object on the top of the call stack. Frame objects store the... |
55a359d4836a31b7c6d074974a6660fc17be2841 | Kontowicz/Daily-coding-problem | /day_110.py | 678 | 3.90625 | 4 | # Given a binary tree, return all paths from the root to leaves.
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
path = []
def getPath(root):
if root == None:
return []
nodePath = []
leftPath = getPath(root.left)
for pa... |
888c859fa2e0b582f1ecc7426be5a0b5a1e4b9a1 | RaamRaam/python-session-5-RaamRaam | /session5.py | 6,089 | 3.703125 | 4 | import random
from operator import itemgetter
def create_deck_using_lambda_zip_map(vals: 'face values as List[String]', suits: 'classes as List[String]') -> 'Deck as List[String]':
'''
creates a deck of cards
Input:
vals: ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'jack', 'queen', 'king', 'a... |
94f098243b739a21631f70727e46fe2ad86fdbad | iFengZhao/Algorithms-1 | /剑指Offer/56-1-数组中只出现一次的两个数字.py | 1,582 | 3.90625 | 4 | '''
题目:一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。要求时间复杂度是O(n),空间复杂度是O(1)。
'''
'''
书上的写法
'''
class Solution:
def find_nums_appear_once(self, data):
if not data or len(data) < 2:
return
result_exclusive_or = 0
for num in data:
result_exclusive_or ^= num
i... |
2b5033eb83c77c3a40579e70701a7059826e0706 | amresh1495/Udemy-course-follow-up-code | /UDEMY_COURSE.PY | 4,103 | 4.59375 | 5 | # Python code follow up on udemy course - The four pillars of object oriented programming in python
# check if an employee has achieved his weekly target -
class Employee:
"""attributes like name, designation etc are included
below to help understand more about the class"""
name = 'Amresh'
design... |
dba9d1e54d2d7b844379321a1145f046f0db978e | mhaig/adventofcode | /2020/day03/day03.py | 2,195 | 3.59375 | 4 | #!/usr/bin/env python
# vim:set fileencoding=utf8: #
import sys
from functools import reduce
class Map(object):
"""Docstring for Map."""
def __init__(self, map_lines):
"""
@todo Document Map.__init__ (along with arguments).
map_string - @todo Document argument map_string.
"""... |
81cef3c4390805ee44b5bcfcf238ed66f278edfe | MohammedAlewi/competitive-programming | /leetcode/graphs/Maximum Depth of N-ary Tree.py | 599 | 3.578125 | 4 | """
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution:
def maxDepth(self, root: 'Node') -> int:
if root==None:return 0
count=self.find_max(root,0)
return count
def find... |
8aa4d1cdf100630328d1f910ec7da929bc9918b0 | celineyuwono/simple-blackjack | /blackjack-main.py | 4,453 | 3.9375 | 4 | __author__ = 'Celine Yuwono, yuwono@live.unc.edu, Onyen = yuwono'
# import random
import random
# implement get_player_score function
def get_player_score():
card1 = deal_card()
card2 = deal_card()
total_score = card1 + card2
print('Your hand of two cards has a total value of ', total_scor... |
71a10a07dfb85da63424881d7f1c8990e9c80bfe | davidgumpert/TDDE31_Big_Data_Analytics | /lab2-sparksql/lab2ex2.py | 1,692 | 3.609375 | 4 | from pyspark import SparkContext
from pyspark.sql import SQLContext, Row
from pyspark.sql import functions as F
sc = SparkContext(appName = "Lab2ex2")
sqlContext = SQLContext(sc)
# Importing needednecessary files
temp_file = sc.textFile("BDA/input/temperature-readings.csv")
temp_lines = temp_file.map(lambda line: lin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.