blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
3cf9bff69257647e4f88d841d4c6deac068ec686 | lakshmihere/games | /hangman/hangman.py | 5,228 | 4.15625 | 4 | import random
import sys
import time
# Pictorial representation of various stages of the game
HANGMAN = ['''
+---+
|
|
|
===''', '''
+---+
O |
|
|
===''', '''
+---+
O |
| |
|
===''', '''
+---+
O |
/| |
|
===''', '''
+---+
O ... |
6ac625ac08f1c4db6387c6a9e9aa3dfcfeb89929 | thleo/Work-Smart | /list-tasking.py | 952 | 3.75 | 4 | """
https://medium.com/technology-invention-and-more/how-to-build-a-simple-neural-network-in-9-lines-of-python-code-cc8f23647ca1#.w2d03bdnd
http://searchsoa.techtarget.com/definition/object-oriented-programming
http://stackoverflow.com/questions/4841436/what-exactly-does-do-in-python
https://www.analyticsvidhya.com... |
203b97ebd3e695183c7992ef628d0339adc40321 | 23o847519/Python-Crash-Course-2nd-edition | /chapter_08/tryityourself86.py | 595 | 4.46875 | 4 | # 8-6. City Names: Write a function called city_country()
# that takes in the name of a city and its country. The
# function should return a string formatted like this:
# "Santiago, Chile" Call your function with at least
# three city-country pairs, and print the values that
# are returned.
print("\nEx 8.6 City Names\... |
5f58e9cf3fa5befbf9c2683736f624042c70a69a | s29zhu/euler-project | /51.py | 1,447 | 3.765625 | 4 | #!include /usr/bin/python
from math import sqrt, floor
from itertools import *
def isPrime(num):
if num < 2:
return False
for i in range(1, int(floor(sqrt(num))) + 1):
if not num % i and i != 1:
return False
return True
# This function returns the digits' index(es)
def pattern(num):
index = {}
i = 0
for... |
c06be9b01fdc02478a77d59a77b936890f671782 | kirillsakh/applied-machine-learning | /Assignments/linear-regression-qr-householder/main.py | 1,527 | 3.546875 | 4 | from sklearn import datasets
from sklearn.model_selection import train_test_split
from gradient_descent import LinearRegression as LinRegGD
from QR_decomposition import LinearRegression as LinRegQR
from sklearn import linear_model
import numpy as np
import matplotlib.pyplot as plt
def main():
X, y = datasets.load_bo... |
45478cfb207cbfdf651576603cd4f562a2471c52 | awilkinson88/SoftwareDesign | /chap11/homophone.py | 1,090 | 4.09375 | 4 | ##Author: Anne Wilkinson
def make_dict():
"""Creates a dictionary from a text file"""
d = {}
fin = open ('words.txt')
for line in fin:
word = line.strip()
d[word] = word
return d
def is_homophone(word1,word2):
"""Checks if two words are pronounced the same"""
pdi = read_dictionary()
if word1 not in pdi or... |
1baae3052fc09bf68fe6adff07f513431ca0cbe5 | shashanka2a/LeetCode | /isPowerOfTwo.py | 310 | 4 | 4 | """
Given an integer, write a function to determine if it is a power of two.
Example 1:
Input: 1
Output: true
Example 2:
Input: 16
Output: true
"""
def isPowerOfTwo(self, n):
if n<0:
return False
s = bin(n).replace('0b','')
if s.count('1')!=1:
return False
return True
|
5f7c4ce4b97634500f531f95c919eb3185755f52 | timpark0807/self-taught-swe | /Algorithms/Leetcode/322 - Coin Change.py | 471 | 3.765625 | 4 | def coin_change(coins, amount):
"""
change = 1
coin = [1, 2, 5]
[0, 0, 0, 0, 0, 0, 0]
0 1 2 3 4 5 6
"""
table = [float('inf')] * (amount + 1)
table[0] = 0
for change in range(1, len(table)):
for coin in coins:
if coin <= change:
... |
df6958cf52af6258c133b5c2ec559545c5c4916f | andrewtzeva/vigenere-decrypt | /utils.py | 971 | 3.71875 | 4 | from collections import Counter
import string
def letter_to_index(letter):
letter = letter.lower()
if not letter.isalpha():
return -1
return string.ascii_lowercase.index(letter)
def index_to_letter(index):
letters_dict = dict(enumerate(string.ascii_lowercase))
return letters_dict[index]... |
6ef0145ce8e6713f6ecd94be07df28238bb98e12 | keerthana0110/Python | /palindrome.py | 151 | 4.21875 | 4 | string=raw_input("enter a string")
if (string==string[::-1]):
print("the string is palindrome")
else:
print("the string is not a palindrome")
|
ab20a9a3dccd64f51d64be1d7fded4e6d0737872 | ZewuJiang/datamining_01 | /logic_circuit.py | 2,483 | 3.890625 | 4 | # python & data structure
# class and subclass
class logic_gate:
def __init__(self, n):
self.label = n
self.output = None
def get_label(self):
return self.label
def get_output(self):
self.output = self.perform_gate_logic()
return self.output
class binary_gate(logic_gate):
def __init_... |
d9fa5dcea603fc498c90066e2c8b044c29318e2f | ivan-yosifov88/python_oop_june_2021 | /polymorphism_and_abstraction/wild_farm/animals/birds.py | 907 | 3.6875 | 4 | from wild_farm.animals.animal import Bird
class Owl(Bird):
WEIGHT_INCREASE = 0.25
SOUND = "Hoot Hoot"
FOOD_EAT = ['Meat']
def make_sound(self):
return Owl.SOUND
def feed(self, food):
if food.__class__.__name__ not in Owl.FOOD_EAT:
return f"{self.__class__.__name__} do... |
2942cfb25b86c488b8b4c07345f25cf36922196c | xiaotiankeyi/PythonBase | /python_Base/list/list_base.py | 3,431 | 4.125 | 4 | '''
列表:
定义:[]内可以有多个任意类型的值,逗号分隔
概念:
1、列表里每个元素都是可变的
2、列表中的元素是有序的,也就是说每个元素都有一个位置
3、列表可以容纳任何对象
常用操作:
>索引
>切片
>追加
>删除
>长度
>循环
>包含
'''
def list_collection():
# ___创建列表___
name_list... |
fe594105b256bbc4f7f6fbe934d8328de2277db0 | nahaza/pythonTraining | /ua/univer/HW04/ch06ProgTrain01.py | 405 | 4.4375 | 4 | # 1. File Display
# Assume a file containing a series of integers is named numbers.txt
# and exists on the computer’s disk. Write a program that displays all of the numbers in the file.
def main():
numInFile = open('number_list.txt', 'r')
for numbers in numInFile:
numbers = int(numbers.rstrip('\n'))
... |
5a18dd1c0f7d2bf5ec2184ea179befe5cbc6b1d0 | taylorreece/code_competitions | /google-code-jam/2021/0 - qualification/2 - cj/solution.py | 472 | 3.578125 | 4 | #!/usr/bin/env python3
num_problems = int(input())
def solve(X, Y, mystring):
cjs = 0
jcs = 0
for i in range(len(mystring)-1):
if mystring[i:i+2] == 'CJ':
cjs += 1
if mystring[i:i+2] == 'JC':
jcs += 1
return X * cjs + Y * jcs
for i in range(num_problems):
X... |
2916abc0b7f4e9e976e1e1cdb51b37914dcab599 | Priyanka-Kothmire/LIST | /reverse_name.py | 237 | 3.875 | 4 | places=input("enter the name")
# places=["delhi", "gujrat", "rajasthan", "punjab", "kerala"]
a=[ ]
length=len(places)
print(length)
i=1
while i<=len(places):
a.append(places[-i])
a=places[-i]
i=i+1
print(places)
print(a)
|
51f03cca3aba06d2f79a8a444ebaadba5416614e | limingrui9/python | /gaofushuai.py | 306 | 3.8125 | 4 | high = int(input("请输入你的身高"))
money = int(input("请输入你的身价"))
face = int(input("请输入你颜值分"))
if high>180 and money>1 and face>90:
print("就可以是高富帅")
elif high<180 and money>1 and face>90:
print("就可以是富帅")
else:
print("啦啦啦")
|
9f0a38d00b6b8491e21ef11b591cb8ce4a33367a | dwrank/datasciencefromscratch | /exploredata.py | 3,714 | 3.578125 | 4 | #!/usr/bin/env python
from __future__ import division
import math
import random
import numpy as np
from matplotlib import pyplot as plt
from scipy.stats import norm
from pprint import pprint
from collections import Counter
from utils import correlation
def bucketize(point, bucket_size):
'''floor th... |
e3c60795af86e302f6aa773f1405240719a92653 | gouransh111/Tkinter-tutorials | /tk10.py | 741 | 3.65625 | 4 | from tkinter import*
import tkinter.messagebox as tmsg
root = Tk()
def getdollar():
print(f"we have credited {myslider2.get()} to your account")
tmsg.showinfo("help",f"we have credited {myslider2.get()} to your account")
root.geometry("455x233")
root.title("Slide tutrial")
#It is randomly a vertical sli... |
fadb5e7e179f5f74b22c47956cdae1e03b862095 | hwy801207/pycookbook | /c6.py | 318 | 3.796875 | 4 | #!/usr/bin/env python3
from collections import defaultdict
d = defaultdict(list)
d['a'].append(1);
d['a'].append(2);
d['a'].append(2);
d['b'].append(4);
print(d)
print("-"*20)
d = defaultdict(set)
d['a'].add(1)
d['a'].add(2)
d['a'].add(2)
d['b'].add(4)
print(d)
d = defaultdict(list)
d['a']
print("-"*20)
print(d)
|
d251855ad5f79b207b6a8d4d2ef1b069444c3202 | plmssr/BST | /exam/exam3.py | 749 | 3.9375 | 4 | def print_space(space):
# base case
if (space == 0):
return
print("^", end="")
# recursively calling print_space()
print_space(space - 1)
# function to print asterisks
def print_asterisk(asterisk):
# base case
if(asterisk == 0):
return
print("#", end="")
# recu... |
717604e90b3d324e94e4ea046be63dc2c3c8ee23 | lakshyarawal/pythonPractice | /Strings/leftmost_repeating_char.py | 1,429 | 4.0625 | 4 | """ Left Most Character that repeats: """
import sys
"""Implementation: Adding occurrences in the count array and then iterating string to see which one has 2 or more """
def leftmost_repeat_char(str_in) -> int:
count = [0] * 256
for i in range(len(str_in)):
count[ord(str_in[i])] += 1
for i in r... |
3fc308b640be745f40093020bfeb175b8fb343dc | reshmapalani/pythonprogram | /user1.py | 147 | 4.0625 | 4 | x=int(input("enter the value of x:"))
y=int(input("enter the value of y:"))
print("x=","x")
print("y=","y")
print("x+y=","x+y")
print("x-y","x-y") |
52d04f87a2fd386c56a5b83a65407460c6c0cd22 | IsaamUddin1996/Python_full_tutorial | /calculator.py | 139 | 3.78125 | 4 | print("hi")
print("Enter ur first no:")
var = input()
print("Enter ur 2nd no:")
var1 = input()
print("you add this:",int(var) + int (var1)) |
c13050810804bafadedfbb3d4b13bf1a45d23286 | alisharifi2000/ChangeArabicCharacterToPersianCharacter | /unicode_map_v3_GUI.py | 13,283 | 3.953125 | 4 | #update:
#add two options for users.
#change english number to persian number.
#change persian number to english number.
import pandas as pd
from pandas import ExcelWriter
from pandas import ExcelFile
import os
import tkinter.filedialog
from tkinter import *
import io
import xlsxwriter
global df
global df1
global pe... |
d3a5514f58aae3ade18927a5750c6c0236cdbab4 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/word-count/71f12dfa83e44a729c13e4dd0435f832.py | 341 | 3.546875 | 4 | class Phrase:
def __init__(self, phrase):
wordlist = [Phrase._sanitze(word) for word in phrase.split()]
self._words = {word: wordlist.count(word) for word in wordlist if word}
def _sanitze(word):
return ''.join([c.lower() for c in word if c.isalnum()])
def word_count(self):
... |
7feb9157bff078d684b5c4794b6eafa641b1d13a | EmmaKibore/passlocker | /run.py | 3,005 | 4.28125 | 4 | from user import User
from credentials import Credentials
import random
# def ca_user(user_name, password):
# """
# Function to create a new user
# """
# new_user = User(user_name, password)
# return new_user
def ca_account(account_name, user_name, password):
"""
Function to create a new ... |
e2afe282b2a043b2b0cde35dac7aeb6f0e9ffc32 | guoheng/ProjectEulerPy | /p062.py | 1,288 | 3.75 | 4 |
#The cube, 41063625 (345^3), can be permuted to produce two other cubes: 56623104 (384^3) and 66430125 (405^3). In fact, 41063625 is the smallest cube which has exactly three permutations of its digits which are also cube.
#
#Find the smallest cube for which exactly five permutations of its digits are cube.
import lo... |
faa9b75db098dfcbeaf101554e922f64986031d7 | aishraghavan/hacker_rank | /utopian-tree.py | 1,598 | 4.1875 | 4 | #!/bin/python
"""
https://www.hackerrank.com/challenges/utopian-tree
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... |
5ad4c841705f45d9483b5cdbafa7cd734ba92a8f | elfen05/pythonElena | /sofiaSinReturn.py | 271 | 3.984375 | 4 | def divisible():
for i in range (0,101):
if i%2==0 or i%3==0 or i%5==0:
resultado=print (i,"/t Numero divisible")
i+=1
else:
resultado= print (i,"/t Numero primo")
i+=1
# return resultado
divisible() |
320c8cc8f7683cbda0b4b5c3671bd2e29d5138e3 | tejasgondaliya5/advance-python-for-me | /inheritansOOP.py | 1,043 | 3.796875 | 4 | # inheritance concepet of oop
'''
-inheritance is concept of parent and child relation
- inheritance meaans new class deriving a old class
- 1)super class : old class is called super class, parent class, base class
- 2)sub class : new class is called sub class, child class, derived class
- type of inheritance... |
e0471c187c823818e67636fca13b6b2e650ea0fe | bcui6611/anomaly-detection-1 | /usageExample.py | 2,260 | 3.609375 | 4 | from strangeness import Strangeness
import argparse
def check_negative_float(value):
ivalue = float(value)
if ivalue < 0:
raise argparse.ArgumentTypeError("%s is an invalid positive int value" % value)
return ivalue
def check_negative_int(value):
ivalue = int(value)
if ivalue < 1:
... |
78d1fa3a181b65cd20baff458d4737ab8ea98956 | okq550/PythonExamples | /AlgoExpert/Sorting/BubbleSort.py | 972 | 3.890625 | 4 | # # Solution 1
# # Best: O(n) Time | O(1) Space.
# # Avg: O(n^2) Time | O(1) Space.
# # Worst: O(n^2) Time | O(1) Space.
# def bubbleSort(array):
# swapsCounter = 0
# i = 0
# while i < len(array) - 1:
# if array[i] > array[i + 1]:
# swapsCounter += 1
# tmp = array[i + 1]
# array[i + 1] = array[i]
# arr... |
1cb60cb983990b5c35178bb7302b608de43272b2 | sirisatwika/263698 | /in_notin_string.py | 300 | 3.765625 | 4 | alphabet = "abcdefghijklmnopqrstuvwxyz"
print("f" in alphabet)
print("F" in alphabet)
print("1" in alphabet)
print("ghi" in alphabet)
print("Xyz" in alphabet)
print("f" not in alphabet)
print("F" not in alphabet)
print("1" not in alphabet)
print("ghi" not in alphabet)
print("Xyz" not in alphabet)
|
30aa9896ab148f23ef0698f04198070af6796127 | canonicalmg/code-katas | /src/first_last.py | 158 | 3.984375 | 4 | """Function removes the first adn last character of a string."""
def remove_char(s):
"""Remove the first and last character of s."""
return s[1:-1]
|
8541885539a06176c0b96166d2c8568c6b2563cb | dwipam/code | /practice/@ | 268 | 3.75 | 4 | def binary(a,li,hi):
if hi>=li:
mid = (li+hi)/2
if a[mid]==mid:
return mid
elif a[mid] > mid:
return binary(a,li,mid-1)
else:
return binary(a,mid+1,hi)
return -1
print(binary([0,2,3,4],0,3))
|
6ac8e296bddf2029abe69ed1de301069ef505a71 | hyonzin/exercism-python | /bob/bob.py | 694 | 3.9375 | 4 | import re
def hey(phrase):
is_question = False
is_yelling = False
is_addressing_without_saying = False
answer = ''
phrase = re.sub(r'[\s]','',phrase.strip())
if phrase.isupper():
is_yelling = True
if len(phrase) is 0:
is_addressing_without_saying = True
elif phrase[len(... |
03ef2849826b0746702b2da6d4b5ab27f0970bfd | albin143/ICTAK | /python/pr1.py | 80 | 3.5 | 4 | prefix=input("enter a string")
sufix=("ack")
for i in prefix:
print(i+sufix) |
063f3b89d29e1082297c179556dac0c3eeb25ed9 | guyleaf/python | /homework/015. 印圖形/test15.py | 2,057 | 4.125 | 4 | """
015. 印圖形
請使用 while loop或for loop,
請使用 function。
第一個輸入意義為選擇三種圖形:
1 三角形方尖方面向右邊
2 三角形方尖方面向左邊
3 菱形
第二個輸入意義為畫幾行
(奇數,範圍為 3,5,7,9,....,21)
input
1 (第一種圖形,三角形尖方面向右邊)
9 (共 9 行)
--------------------------
output
*
**
***
****
*****
****
***
**
*
---------------------------
input
2 (第二種圖形,三角形尖方面向左邊)
5 (共 5 行)
---------------... |
7e379ed54bcb2007eea8e7169ccac633ac6fc0c2 | mxgsa/python-test | /basic/base.py | 2,523 | 4.125 | 4 | # -----hello World------------
print 'Hello World!';
print '---------split---------------';
# -----测试字符串-------------
str = 'Hello World!';
print str; # 输出完整字符串
print str[0]; # 输出字符串中的第一个字符
print str[2:5]; # 输出字符串中第三个至第五个之间的字符串
print str[2:]; # 输出从第三个字符开始的字符串
print str * 2; # 输出字... |
41fd8fa44e8819af4ad17c8ccb16e85176d68995 | leandrotartarini/python_exercises | /secondWorld/ex070.py | 597 | 3.796875 | 4 | total = totHun = smallest = cont = 0
cheap = ''
while True:
product = str(input('Type the name of the product: '))
price = float(input('Price $: '))
cont += 1
if cont == 1 or price < smallest:
smallest = price
cheap = product
total += price
if price > 1000:
totHun += 1
resp = ' '
while resp ... |
b72db20008211daf8c6ed396b9474c72ec0ad9b4 | missgreenwood/codecracker | /arrays_and_strings/is_permutation.py | 1,473 | 3.859375 | 4 | import unittest
# Given two strings, write a method to decide if one is a permutation of the
# other.
def normalize(s: str) -> str:
return s.lower()
def is_perm_1(s1: str, s2: str) -> bool:
s1 = normalize(s1)
s2 = normalize(s2)
if len(s1) != len(s2):
return False
s1 = ''.join(sorted(s1))
... |
3274e1c608d79da9478075defbcb97225e1beb3c | BenRauzi/159.172 | /Assignment 1/snake.py | 11,735 | 3.828125 | 4 | """
Snake Game template, using classes.
Derived from:
Sample Python/Pygame Programs
Simpson College Computer Science
http://programarcadegames.com/
http://simpson.edu/computer-science/
"""
import pygame
import random
# --- Globals ---
# Colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GR... |
66a2b0f435cf3e0338578774f5d41dbd6af3b3ec | dollarkid1/pythonProjectSemicolon | /chp6/words_counts.py | 364 | 3.796875 | 4 | text = ('i am douglas humble a software engineer '
'i love who i am and am douglas humble a software engineer')
word_count = {}
for word in text.split():
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
print(f'{"WORD":<12}COUNT')
for word, count in sorted(wor... |
78df5410bc7843822e2b60212c1e110345f5eb9a | kalrashivam/python_algorithms | /move_all_zeroes_to_the_end.py | 554 | 4.15625 | 4 | # Function to move all the zeroes to the end of the array recieved.
def pushZerosToEnd(arr, n):
# To count all the non zero elements
count = 0
for i in range(n):
if arr[i]!= 0:
arr[count] = arr[i]
count += 1
while count<n:
arr[count] = 0
count += 1
# In... |
536ee6d0932a23527435bf198a2ad25b7a67b846 | hwulfmeyer/NaiveBayesClassifier | /filehandling.py | 2,133 | 4.15625 | 4 | """
This file is for the methods concerning everything from file reading to file writing
"""
import re
import random
def read_data_names(filepath: str):
"""
function to read class names & attributes
:param filepath: the relative path to the file containing the specifications of the attribute_values
:... |
954185e62430588a8fb9b3b4fdf95a0187575584 | ShrijanaSapkota/pythonProject-nepalmap | /main.py | 1,027 | 3.734375 | 4 | import turtle
import pandas
screen = turtle.Screen()
screen.title("Nepal Zone Game")
image = "nepal_divisions_blank.gif"
screen.addshape(image)
turtle.shape(image)
data = pandas.read_csv("data.csv")
all_zones=data.zone.to_list()
guess_zones =[]
while len(guess_zones)<14:
answer_zone = screen.textinput(title=f"{len... |
160027dcc3d719f06269ad1c16efd5c3b3426eea | klknet/geeks4geeks | /algorithm/bitwise/non_repeating_ele.py | 887 | 4.15625 | 4 | """
Find the two non-repeating elements in an array of repeating elements.
All the bits that are set in Xor will be set in one non-repeating element(x or y) and not in others. So if we take any
bit of xor and divide the elements of the array in two sets - one set of elements with same bit set and another set with
same ... |
08b1c4a94429644efb7e4edda6a978ad6a43b8db | JorG96/DataStructures | /hasPathWithGivenSum.py | 1,521 | 3.921875 | 4 | '''
Given a binary tree t and an integer s, determine whether there is a root to leaf path in t such that the sum of vertex values equals s.
Example
For
t = {
"value": 4,
"left": {
"value": 1,
"left": {
"value": -2,
"left": null,
"right": {
... |
58bb4098e925d8f75aefc7397c4511fe9ff22b06 | lb8ovn/PickemBot | /pickembot.py | 2,406 | 3.609375 | 4 | import tensorflow as tf
import pandas as pd
from sklearn.model_selection import train_test_split
#First we gotta find the data and prep it for the neural net
data = pd.read_csv('Whatever data we find')
normalized_columns = ['Columns']
data[normalized_columns] = data[normalized_columns].apply(lambda x: (x - x.min()) / ... |
81e53d567af5063008bc8b7c3bf5e4092d2d8550 | sbkaji/python-programs | /assignment/5.py | 386 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Feb 20 23:52:27 2020
@author: Subarna Basnet
"""
"""5.Write a Python program to get the maximum and minimum value in a dictionary"""
data = {'A':2015, 'B':2002, 'C': 3900}
m = max(data.keys(), key=(lambda k: data[k]))
mi = min(data.keys(), key=(lambda k: data[k... |
5d601c94d92f989536469cc65dd08f36e7279237 | wenyaowu/leetcode | /algorithm/countAndSay/countAndSay.py | 796 | 3.9375 | 4 | # Count and Say
"""
The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n, generate the nth sequence.
Note: The sequence of integers w... |
a0b44a6c4e662a68474422f0340501212125b3ac | swarnanjali/python-programes | /binary.py | 125 | 3.59375 | 4 | nber1=str(input())
for i in range(0,len(nber1)):
if nber1[i]!='0' and nber1[i]!='1':
print("no")
else:
print("yes")
|
b00dc0338aee80ab170197c28067eaa0b835d43a | qnn122/ml-for-bci | /tools/SSVEP_BCIGame/client_simulation.py | 1,020 | 3.6875 | 4 | """
Send message to the sever and recieve data back
Acts like a client
Python version: 2.5
Dependencies: sever.py
"""
import socket
import sys
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect the socket to the port where there server is listening
server_add... |
f60b288162835e8fbe48d2c3f6cd0a433d138f18 | declo32/town-crier | /old-ones/Announcement-Feed/files/web-scraper.py | 2,355 | 3.609375 | 4 | #!/usr/bin/python
import requests
import itertools
from bs4 import BeautifulSoup
import utils
print("Finding most recent announcements")
# Gets the "Announcements Archive" page of the SHS website
url = "http://www.scituate.k12.ma.us/index.php/about-shs/daily-announcements-archive"
archive_request = requests.get(u... |
e32357b3e26ec260e7be752dd8f2136196edcd01 | streetbikeford/HowToPython | /The Inline If Statement.py | 271 | 4.21875 | 4 | ## A typical if statement will look something like this
a, b = 25, 35
if a >= b:
print(True)
else:
print(False)
## You could also write this statement as
print(True if a>=b else False)
## Both will run exactly the same, the inline If is just easier on the eyes. |
97b61b984b05740f9ba96560cbecd106998ce823 | haiwenzhu/leetcode | /roman_to_integer.py | 724 | 3.609375 | 4 | class Solution:
"""
@see https://oj.leetcode.com/problems/roman-to-integer/
"""
# @return an integer
def romanToInt(self, s):
chart = dict(I=1, V=5, X=10, L=50, C=100, D=500, M=1000)
if s == "":
return 0
n = chart[s[-1]]
for i in range(2, len(s... |
5a9939e6e4900de77b2a706de0c588db50306e12 | kidrr/kidrrstore | /random_stringgen.py | 449 | 3.96875 | 4 | # Generates custom number of strings with randon chars and numbers
# test branch
import random, string
def random_chars(a):
chars = string.letters + string.digits
s = [random.choice(chars) for i in range(a)]
output = (''.join(s) + '\n')
return output
how_many = input("How many strings: ")
how_long = in... |
3eb762717f1cba5696b8457c670c5c59c0c316af | ribhuswatgov/GFG-RECURSION | /tcs_recursion_fibonacci_mixed_Series.py | 636 | 3.90625 | 4 | def fib(n):
if n%2==0:
c = prime(n/2)
return c
else:
if n == 1:
return 1
if n == 3:
return 1
return fib(n-2) + fib(n-4)
def prime(n):
f=2
s = 1
while s!=n:
result = isPrime(f)
if result is True:
... |
9963f58af892ed7ceb5bd02f68f6803325446464 | akarshsomani/social-network | /BFS.py | 577 | 3.890625 | 4 | #BFS in networkx network
import networkx as nx
def BFS(G,start):
neigh=[]
queue=[]
queue.append(s)
record=[]
record.append(s)
while(queue != []):
current=queue.pop(0)
#print(current)
neigh=list(G.neighbors(current))
neigh.sort()
#print(neigh)
for... |
c79b1d7bd0773c914d52780ad9326736eb860140 | samloop/GitFit | /HealthBasedGoal.py | 767 | 3.5 | 4 | from Goal import Goal
from cardio import Cardio
from stretch import Stretch
class HealthBasedGoal(Goal):
def __init__(self):
super(HealthBasedGoal, self).__init__()
print("In HealthBasedGoal Class")
num = input("What intensity level are you feeling today on a scale of 1-3?")
if ... |
fcbb2f6523027d88cc45cedd0b7cd9775038de45 | cjgarcia/diplomado_python | /s4/d3_dicts_2.py | 796 | 3.78125 | 4 | # Dict con los datos del estudiante
estudiante = {
"nombre": "Crecencio",
"apellido": "Garcia",
"presente": True,
"codigo": 11515
}
"""
De esta forma podemos definir que esta func solo recibe keywrds como arg
Esta caracteristica es muy conveniente para func que trabajan con muchos args
"""
def... |
0a7782ba62658d2fb5884c322723532ba5912390 | fabricST/Learn_python3 | /Home_Work_3/H_W3_P6.py | 2,652 | 4.25 | 4 | # Пишем функцию, которая попросит ввести число. Пока он не введёт правильно, просите его ввести.
# Функция возвращает введённое число.
def number():
while True:
b = input("Enter 0nly the number 3: ")
if b == "3":
print("correct")
return b
break
else:
... |
dbea0d4173e6bd6d7822d80bca3d00c6232989dc | justinwlin/Python-Data-Structure | /Homework/HW2/jwl488_hw2_q5.py | 654 | 3.84375 | 4 | def split_parity(lst):
switch1 = 0
switch2 = 0
for i in lst: #O(n)
if i % 2 == 1: #if odd...
lst[switch1], lst[switch2] = lst[switch2], lst[switch1]
switch1 = switch1 + 1
switch2 = switch2 + 1
if i % 2 == 0: #if even
switch2 = switch2 + 1
r... |
3b80188e5bbb080d23abaabee83a275289694d59 | PremDh/replit_problems2020 | /2p1excelcolumn.py | 209 | 3.78125 | 4 | def excel_column_to_number(column):
lgth = len(column) - 1
pos = 0
while lgth >= 0:
for char in column:
ch = ord(char) - ord('A') + 1
pos += (26 ** lgth) * ch
lgth -= 1
return pos |
252be6bcff7a94a6512a1b7f6286216165b92e52 | seeinger/OpenCollegePythonWebProject | /session4_20200118/session4_practice.py | 1,293 | 3.53125 | 4 | class Car:
def __init__(self,manufactor,model,color):
self.manufactor = manufactor
self.model = model
self.color = color
self.left_oil = 1000
def advance(self):
self.left_oil -= 50
print(self.manufactor,self.model,self.color,'차량 전진중입니다! 현재 기름양 : ', self.left_oil)... |
a8e5af7ccb3c42510baa2e4225c3af4547f7114a | marcoaugustoandrade/python-lista-3 | /07_media_idade.py | 226 | 3.71875 | 4 | idade = None
idades = 0
contador = 0
while idade != 0:
idade = int(input('Informe a idade: '))
idades += idade
if idade != 0:
contador += 1
print("A média de idade do grupo é %i." % (idades / contador))
|
140eac52095de2d5f6e1f71d2275d818b7e39a3e | alexnro/Codewars-Katas | /Python/8kyu/gonnaSurvive.py | 334 | 3.65625 | 4 | def hero(bullets, dragons):
if bullets >= dragons*2:
return True
else:
return False
if __name__ == "__main__":
assert hero(10, 5) == True
assert hero(7, 4) == False
assert hero(4, 5) == False
assert hero(100, 40) == True
assert hero(1500, 751) == False
assert hero(... |
e41368f1308dc48e4e4848fd4eedd2b19a43eea8 | potato16/pythonl | /python101/map2ascii.py | 267 | 4.15625 | 4 | ''' convert string by change these string ascii code character to 2'''
strencode = input('Enter code text here: ')
strdecode=''
for char in strencode:
c=char
if char.isalpha():
c = chr((ord(char)+2-97)%26+97)
strdecode +=c
print('String decode to: ',strdecode)
|
4a6c6564a7410d1c6c84a83dbea800cab257207e | brian-yu/tetris-scheduler-simulator | /cluster_manager.py | 4,445 | 3.75 | 4 | """
- Do you have any guidance on how I should begin implementing the scheduler? Are there any existing frameworks that I can build on top of?
- You can just implement the key idea of the scheduler at first. Just try as simple as you can and use your most familiar programming language. For example, if you need to imp... |
07fb31d2e1d90d8f42d0d06df528a89d7b55a152 | josesanchez19/ticbach2 | /python/jercicios4-2.py | 175 | 3.515625 | 4 | def ejercicio_4():
x=input("Dime un numero entero")
suma=0
while x>10:
suma=suma+x%10
x=x/10
print "la suma es",suma + x
ejercicio_4()
|
d17086c49de00f4617613589493ddb8a8d25b4fc | naohashizume/python-rest-api | /top_navbar_view.py | 1,217 | 3.59375 | 4 | # top_navbar_view.py
#
# Top Navigation Bar View
#
# Author: Nao Hashizume, Matt Harrison Set 2B
import tkinter as tk
class TopNavbarView(tk.Frame):
""" Top Navigation Bar """
TEMP_PAGE = 1
PRES_PAGE = 2
def __init__(self, parent, temp_page_callback, pres_page_callback):
""" Initialize the... |
d17d9430bf2833798cf63cfaaf8afc27aa2b17ee | mindovermiles262/codecademy-python | /10 Advanced Topics in Python/03_the_in_operator.py | 491 | 4.40625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 6 17:47:14 2017
@author: mindovermiles262
Codecademy Python
For each key in my_dict: print out the key , then a space, then the value
stored by that key.
(You should use print a, b rather than print a + " " + b.)
"""
mmy_dict = {
"Name":... |
95c39fc46a1c876355a704ace1d690d79b96eeaa | eladshamailov/Codewars-solutions | /count_letters_in_string.py | 457 | 4 | 4 | '''
In this kata, you've to count lowercase letters in a given string and return the letter count in a hash with
'letter' as key and count as 'value'.
The key must be 'symbol' instead of string in Ruby and 'char' instead of string in Crystal.
'''
def letter_count(s):
letter_dict = {}
for c in s:
if c... |
c9525e65e727637a1f0bb8ff9c0feaac785801a4 | kantal/WPC | /ISSUE-42/SOLUTION-6/noliftpen.py | 5,160 | 4.03125 | 4 | #!/usr/bin/env python3
#-*- coding:utf-8 -*-
'''
2014-02-09 by kantal59
License: GPL
OLIMEX WPC#42: No-Lift-Pen Drawings
We all know this game where you draw figure on paper without lifting up your pen and
without going through same segment twice.
Write code which enters N segme... |
7a34cbac61786ecb6bf7b9b07a19cb28adc5aedc | EdoardoGiussani/AdventCalendar | /day9/day9.1.py | 705 | 3.5 | 4 | def GetLines():
file = open("day9/entries.txt")
entries = file.readlines()
for i in range(len(entries)):
entries[i] = int(entries[i])
return entries
def IsValid(num, preamble):
for i in range(len(preamble)):
for s in range(i + 1, len(preamble)):
if preamble[i] + preamble... |
80a7f8fd6bda5fac2514a076ed8f9aa8e28abda6 | jty-cu/LeetCode | /Algorithms/021-Merge Two Sorted Lists.py | 1,710 | 4.09375 | 4 | ## 题目类型:链表
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
## 双指针
## 时间复杂度:O(m+... |
09c04b954a7bc80a1961a08c92a85b345eae1a9f | zipsa/ProjectHistory | /dna_motif_algorithms-py/dna_motif_finder_enum.py | 1,402 | 3.890625 | 4 | '''
A brute force algorithm for motif finding.
Given a collection of strings Dna and an integer d, a k-mer is a (k,d)-motif if it appears in every string from Dna with at most d mismatches.
Implanted Motif Problem: Find all (k, d)-motifs in a collection of strings.
Input: A collection of strings Dna, and integers k a... |
b0abcacd2520f6d2068d770687a6bbb2584fd495 | rarezhang/leetcode | /hash_table/575.DistributeCandies.py | 1,904 | 4.40625 | 4 | """
575. Distribute Candies
Given an integer array with even length, where different numbers in this array represent different kinds of candies. Each number means one candy of the corresponding kind. You need to distribute these candies equally in number to brother and sister. Return the maximum number of kinds of can... |
3e70679b77ac8b5610d5cf62c8a66322190edc0e | poorvarathore05/python_ds_syntax | /26_vowel_count/vowel_count.py | 466 | 4.0625 | 4 | def vowel_count(phrase):
"""Return frequency map of vowels, case-insensitive.
>>> vowel_count('rithm school')
{'i': 1, 'o': 2}
>>> vowel_count('HOW ARE YOU? i am great!')
{'o': 2, 'a': 3, 'e': 2, 'u': 1, 'i': 1}
{'o': 1, 'a': 3, 'e': 2, 'u': 1, 'i': 1}
"""
vowel = ... |
558657bde2724cb4062df0dd340ace8f4041df34 | talots/Programmeerimise-kursus | /Float Median From Text File.py | 586 | 4.09375 | 4 | # Opens and reads the file, then splits the numbers
numbers_file = open("numbers.txt").read().split()
# Makes numbers in list float
float_list = [float(numbers) for numbers in numbers_file]
# Returns the number of items in this list
lenght = len(float_list)
# Two variables, both are 0 at the beginning
summarize = 0... |
674f5cf589cc5fd7b7f520d74c7a951ad3b8a9ac | MarkTheHopeful/timetable | /src/date_converter.py | 1,657 | 4.03125 | 4 | from datetime import date
from src.timetable_exceptions import InvalidCalendarDateException
# List of days of the week
dayOfWeekList = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
daysInAWeek = len(dayOfWeekList)
# Grabs the current day of the week from datetime
todayNum = date.today(... |
00965cdf12d5eefe0b8425ee91fb3c01177a5983 | RishabhBhatnagar/Algorithms | /python/huffman_coding.py | 1,699 | 3.703125 | 4 | class Node():
def __init__(self, data = "", frequency = 0):
self.right_child = None
self.left_child = None
self.data = data
self.frequency = frequency
import collections
string = input("Enter a string : ")
frequencies = dict(collections.Counter(string))
leaves = []
for i in frequen... |
5a30b8d8f8cf1d88fcd068ee8c027f3c5a4a6b00 | JenS616/FinalProject17 | /FinalProject17.py | 20,491 | 3.90625 | 4 | ################################ ROOMS #########################################
class Room(object):
def __init__(self, name):
self.name = name
def dire(self, north, south, east, west): #directions (what's north/south/etc. of the room)
self.north = north
self.south = south
self... |
3a0249d61500d7a7575477fda2faf7f73993d6b8 | jpladuguie/Other | /EightQueens.py | 2,118 | 3.96875 | 4 |
# Prints the chess board with correct formatting
def printBoard(board):
for i in range (0, len(board)):
print(' ', end='')
for j in range(0, len(board)):
print(str(board[i][j]) + ' | ', end='')
print('')
print(' ')
# Returns true if a queen can be placed in the given positi... |
d9690b2328fd8920c1f6a85e64ec8566c59c5b76 | 08zhangyi/Some-thing-interesting-for-me | /Python密码学编程/ch23/primeNum.py | 1,501 | 3.59375 | 4 | import math, random
def isPrimeTrialDiv(num):
if num < 2:
return False
for i in range(2, int(math.sqrt(num)) + 1):
if num % i == 0:
return False
return True
def primeSieve(sieveSize):
sieve = [True] * sieveSize
sieve[0] = False
sieve[1] = False
for i in range... |
660341ca309dec2f8d02cfe985ea2184c3cef21a | adrian/adventofcode | /python/2020/day7.py | 2,584 | 3.671875 | 4 | #!/usr/bin/env python3
from utils import read_input_raw
import os
import re
class Node:
def __init__(self, name):
self.name = name
self.edges = []
def add_edge(self, target_node, weight):
self.edges.append(Edge(weight, target_node))
class Edge:
def __init__(self, weight, node... |
3f40f9c098aef86aa79667b2d1e90661f9c90fbc | s20168/ASD | /Quicksort.py | 583 | 3.5625 | 4 | import time
def quick_sort(A, p, r):
if p < r:
q = partition(A, p, r)
quick_sort(A, p, q - 1)
quick_sort(A, q + 1, r)
def partition(A, p, r):
pivot = A[r]
smaller = p
for i in range(p, r):
if A[i] <= pivot:
A[smaller], A[i] = A[i], A[smaller]
... |
0252bf3cb28853b8b999b779432028a29cc2a077 | mrudula-pb/Python_Code | /Udacity/Project2/LinkedList_GetSize.py | 2,074 | 4.3125 | 4 | class Node:
def __init__(self, value, next = None):
self.next = next
self.value = value
class LinkedList:
def __init__(self):
self.head = None
def to_list(self):
out = []
node = self.head
while node:
out.append(node.value)
node = nod... |
cf4265f51a14f38f99806cf1d168af6da4317a9b | Gmai/ArtificialNeuralNetworks | /iris-solution2.py | 1,892 | 3.625 | 4 |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('iris-data.csv')
X = dataset.iloc[:, 0:4].values
y = dataset.iloc[:, 4:5].values
# Part 1 - Data Preprocessing
# Encoding categorical data
from sklearn.preprocessing import LabelEncoder, OneHotEncode... |
b8fdb33a4c58d442db8cea4436c0bc4f2c6c42f0 | PedroVitor1995/Algoritmo-ADS-2016.1 | /atividade_e/lista2questao4.py | 293 | 3.765625 | 4 | def main():
primeira_nota = float(input('Nota 1: '))
segunda_nota = float(input('Nota 2: '))
media = (primeira_nota + segunda_nota) / 2
if media < 7.0:
print 'REPROVADO.'
elif media < 10.0:
print 'APROVADO'
else:
print 'APROVADO COM DISTINCAO'
if __name__ == '__main__':
main() |
43ecdf765fa20c04d6b257e9df19833c4adb73c8 | whylearn0508/homework2021 | /homework1.py | 2,290 | 3.859375 | 4 | """
1.计算求2+4+6+8+...+100的和
2.统计不同英雄的成绩
3.车型抱怨的数据统计
"""
print('homework 1:')
ret = 0
for i in range(2, 102, 2):
ret += i
print('2+4+6+8+...+100的和是:{0}'.format(ret))
# 作业2
print('\nhomework 2:')
import pandas as pd
data = {
'语文': [68, 95, 98, 90, 80],
'数学': [65, 76, 86, 88, 90],
'英语': [30, 98, 88, 77, ... |
11ff983fb56770438e7a8eb6a47f87eacd98d105 | atounsi/PCML-Project1 | /Labs/ex04/split_data.py | 743 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""Exercise 3.
Split the dataset based on the given ratio.
"""
import numpy as np
def split_data(x, y, ratio, seed=1):
"""split the dataset based on the split ratio."""
# set seed
np.random.seed(seed)
# ***************************************************
# INSERT YOUR CODE... |
c253e07100db85adab6e90ade53f381c7d8915e7 | ahjashish/PythonCourse | /day12/modules/util/utility.py | 518 | 3.65625 | 4 | def mult(n1, n2):
return n1 * n2
def divide(n1, n2):
if n2 == 0:
raise ZeroDivisionError("You have passed 0 as the param, cannot divide by zero")
try:
return n1 / n2
except TypeError:
raise ValueError("Don't pass a string buddy")
print(__name__)
def add(n1, n2, op='add'):
... |
9e1159b16971c34460bd920c1edca6ce48d570ad | ArnoldYSYeung/word-trends | /articles.py | 12,441 | 3.515625 | 4 | """
Toolkit for pre-processing and analysis an 'Article'-format Pandas dataframe.
Name: Arnold YS Yeung
Date: 2020-12-11
"""
import pandas as pd
import html
from collections import defaultdict
from datetime import datetime, timedelta
import matplotlib.pyplot as plt
import json
import os
from utils import *
clas... |
7a4feb642f9ec55d6bc8c5161b0b5d85098e3d90 | Tarun-Arora/Information-Technology-Workshop | /Python-Assignments/Assignment1/Q18.py | 284 | 3.734375 | 4 | inp=[[1,2,3], [4,5,6], [10,11,12], [7,8,9]]
max=0;maxSum=0
for i in range(len(inp)):
sum=0
for j in inp[i]:
sum+=j
if(sum>maxSum):
maxSum=sum
max=i
print("The Original List is:\n",inp,sep='')
print("The List with maximum sum is:\n",inp[max],sep='') |
85caf026233fb2bda294cf3c246ae57b5071bddf | dandanes7/typingdojo | /hands.py | 2,833 | 3.59375 | 4 | left_thumb = (121,106)
right_thumb = (162,106)
left_index = (81,30)
left_middle = (57,14)
left_ring = (33,22)
left_pinky = (10,44)
right_index = (203,30)
right_middle = (227,14)
right_ring = (250,22)
right_pinky = (274,44)
# Each combination of fingers is mapped to a list that contains:
# - a list of tuples that repr... |
f753b66d3bc3013374c57923796643febf5201cb | joynewton1996/Daily_Program | /hacker_Rank/May22_Answer.py | 590 | 4.0625 | 4 | def solution(string):
bracket = {"{": "}", "[": "]", "(": ")"}
element = []
count = len(string)/2
if len(string) % 2 != 0:
print("odd")
return 0
for char in string:
if char in bracket.keys():
element.append(char)
elif char in bracket.values():
... |
68645766659dbcf46d206fdde71462ede7adbaed | chengxxi/SWEA | /D4/1486.py | 1,542 | 3.53125 | 4 | # 1486. 장훈이의 높은 선반
def dfs(s, h): # staff / height of tower
if h >= shelf:
towers.append(h)
if s == staff: # len(heights)
if h >= shelf:
towers.append(h)
return
dfs(s+1, h + heights[s])
dfs(s+1, h)
for test_case in range(1, int(input())+1):
staff, shelf = map(... |
6825c7f316e9df5f18bf51dffc83c5f9eb4078ef | teodorklaus/PyStudy | /src/Week1/da1.HW.4.2(File2).py | 189 | 4.03125 | 4 | num1 = int(input())
num2 = int(input())
num3 = int(input())
#max(num1,num2,num3)
#min(num1,num2,num3)
print ("max: " + str(max(num1,num2,num3)))
print ("max: " + str(min(num1,num2,num3))) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.