blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
cf068a97cb76212547139f991aecc8d07ec3dba5 | Tran-Phillip/new-comic-releases | /dashboard/comic_app/tools/extract_comic_titles.py | 3,027 | 3.875 | 4 | # first party
import re
import requests
# third party
from bs4 import BeautifulSoup
# tools
from comic_app.tools.extract_images import extract_images
def extract_image_comics():
'''
This function uses beautiful soup to extract all the images and comic titles
from the image comic new releases website.
... |
73dcd1eda19657ab400efbae70058947f651b1e0 | Mkurtz424/n00bc0d3r | /Projects/CodingBat/Warmup-2/Warmup-2 array_front9 Mike.py | 196 | 3.5 | 4 | def array_front9(nums):
x = 0
tally = 0
while x <= 3 and x <= len(nums)-1:
if nums[x] == 9:
tally = tally + 1
x = x + 1
if tally > 0:
return True
else:
return False |
aad3bccbc2ff3d5a5715e3ed9309597647aa01f3 | b72uno/courses | /lthw/python/ex13.py | 456 | 3.578125 | 4 | # importing modules aka libraries
from sys import argv
raw_input("Gimme something ")
# argv = argument variable
# take whatever is in argv, unpack it and assign to all vars in order
script, first, second, third = argv
print "The script is called", script
print "Your first varialbe is:", first
print "Your second var... |
7737d8356b911d56c7d285e728c94b705c7500f7 | 2damnhot/MH8811-G1901998F | /02/02.py | 225 | 4.0625 | 4 | #program 1
ask_name = input('What is your name?')
print('Hello,',ask_name + '!')
#program 2
question = input('What temperature do you want in Celsius?')
Celsius = float(question)
Fahrenheit = Celsius*1.8+32
print(Fahrenheit) |
ddaf5109df7ab9cf059da71119f68cce0157ed06 | basselrr/CEBD-1100_BASSEL | /Hello_world.py | 178 | 3.859375 | 4 | n1=input(" enter the first number integer")
n2=input(" enter the second number integer")
f1=int(n1)
print("-------")
print(" the sum of the two numberis"+int(n1)+int(n2))
|
2268e29da31190430b1e04f2ece5daa6b40572d3 | graceliu2006/LearnToCode | /python/aa.py | 744 | 3.59375 | 4 | class Pagination:
def __init__(self,input_list,n=10):
self.content=input_list
self.pagesize=int(n)
self.page_no=0
def nextpage(self):
if self.page_no*self.pagesize<len(self.content):
self.page_no+=1
def last(self):
self.page_no=max(len(self.conte... |
c058e43ff6b8f5207cc19376e0ad2c7d433e2165 | ggoboogy/algorithm | /programmers/2.py | 267 | 3.5625 | 4 | def solution(arr):
sum = 0
correct_sum = 0
answer = True
for i in range(1, len(arr)+1):
sum ^= arr[i-1]
correct_sum ^= i
if sum == correct_sum:
answer = True
else:
answer = False
return answer
|
3871c9bf7d445f65369ae3a8c3c806ab3ba12af7 | mmxm0/IP_Listas_SI1 | /fatorial.py | 339 | 4.1875 | 4 | '''
Faça um programa que calcule o fatorial de um número inteiro fornecido pelo usuário.
Ex.: 5!=5.4.3.2.1=120
'''
numeroFatorial = int(input("Informe o numero que deseja o fatorial: "))
x = 1
resultado = 1
while (x <= numeroFatorial):
resultado = resultado*x
x +=1
print("%d ! é = %i"%(numeroFatoria... |
767a4253ff40532f97d430642a542c08d85323e7 | j-poddar/greyatom-python-for-data-science | /Student-Management-System/code.py | 1,139 | 3.890625 | 4 | # --------------
#Step 1
class_1 = ['Geoffrey Hinton','Andrew Ng','Sebastian Raschka','Yoshua Bengio']
class_2 = ['Hilary Mason','Carla Gentry','Corinna Cortes']
print(class_1)
print(class_2)
new_class = class_1 + class_2
print(new_class)
new_class.append('Peter Warden')
print(new_class)
new_class.remove('Ca... |
2af43d79257ea497732e0822a4a4886be540b736 | shin2261/TestRepo | /praIfElif.py | 862 | 3.765625 | 4 | # if True:
# print('Conditional was True')
# language = 'Jave'
# if language == 'Python':
# print('Language is Python')
# elif language == 'Jave':
# print('Language is Jave')
# else:
# print('No match')
# user = 'Admin'
# logged_in = True
# if user == 'Admin' and logged_in:
# print('Admin Page')... |
6f4a86ecbe76fd1840272d71c61837dcbef4001a | weichen-liao/Leetcode | /test1.py | 508 | 3.609375 | 4 |
def efficientJanitor(weight):
# Write your code here
weight = sorted(weight)
n = 0
left = 0
right = len(weight)-1
while len(weight)>1:
# if
if weight[-1] + weight[0] > 3.0:
n += 1
weight = weight[:-1]
else:
weight[-1] = weight[-1] + ... |
519c11ddbb479679d04fbfbe83ac2f9ee0ad0147 | starcraftman/OddThings | /number_sticks/number_sticks.py | 8,184 | 3.921875 | 4 | #!/usr/bin/env python
"""
Problem Statement:
Given a formula of the form A + B = C, where A, B, C are natural numbers.
Compute any possible combinations where the equation MIGHT be valid.
Rules on modifying the equation:
1) Each number is created by segments like an LCD display or match sticks.
2) ... |
c362bb7ae2bc24d5415c80e2bab50faa581a5793 | Srimathesukumar/guvi | /primeno.py | 251 | 3.71875 | 4 | # guvi
''' Prime number between two interval '''
N,Q=input().split()
N=int(N)
Q=int(Q)
for num in range(N,Q+1):
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num,end=" ")
|
011cb0ac6bfab57c88ce8f98cfc0fd7f06dd3833 | michael153/leetcode | /138/138.py | 844 | 3.515625 | 4 | """
# Definition for a Node.
class Node(object):
def __init__(self, val, next, random):
self.val = val
self.next = next
self.random = random
"""
class Solution(object):
def copyRandomList(self, head):
"""
:type head: Node
:rtype: Node
"""
mp = {}
... |
c7bfe2665964a047e7d9e46d520920b082640c46 | TravisLeeWolf/ATBS | /Chapter_2/questionNine.py | 252 | 3.875 | 4 | print('Typing 1 prints Hello')
print('Typing 2 prints Howdy')
print('Anything else prints Greetings!')
print()
print('Type something')
spam = input()
if spam == '1':
print('Hello')
elif spam == '2':
print('Howdy')
else:
print('Greetings!') |
97be56e7b7a296abc17967a7401be994d09f7986 | kiminh/offer_code | /04_FindInPartiallySortedMatrix.py | 1,607 | 3.671875 | 4 | # -*- coding:utf-8 -*-
class Solution(object):
# array 二维列表
def FindNumberOfN(self, target, array):
# write code here
if not array or not target:
return False
m = len(array)
n = len(array[0])
i = m - 1
j = 0
while i >= 0 and j < n:
... |
5750b146e360f4586b1806af2184713bf9e28f6e | burrizozo/aoc2020 | /day12.sln.py | 1,943 | 3.546875 | 4 | import math
file1 = open("day12.input.txt", 'r')
lines = file1.readlines()
def part1():
curWayPointEW = 0
curWayPointNS = 0
curAngle = 0
for line in lines:
curEW, curNS, curAngle = executeInstructionP1(line.rstrip(), curEW, curNS, curAngle)
print(abs(curNS) + abs(curEW))
def executeInstructionP... |
b98f472deccc9f4b47bfc9b0184a20e881036fe0 | thdguswn/pyalgostudy | /8958.py | 106 | 3.5 | 4 | n=int(input())
quiz=[]
for i in range(n):
a=input()
quiz.append(a)
print(quiz)
|
abeebb2375c0654ef25106cbd65881d200643ab4 | scott-gordon72/python_crash_course | /chapter_3/every_function.py | 298 | 3.84375 | 4 | chess_pieces = ['king', 'queen', 'rook', 'bishop', 'knight', 'pawn']
print(f"There are {len(chess_pieces)} distinct chess pieces on the chess board")
print(f"Sorted pieces: {sorted(chess_pieces)}")
print(f"Reverse sorted pieces: {sorted(chess_pieces, reverse=True)}")
print(chess_pieces[0].title()) |
10bf24f07343bfa757fc2b44d4f407e37a05e87e | ahmedvuqarsoy/Object-Oriented-Programming-with-Python | /TV Controller.py | 2,536 | 3.71875 | 4 | import random
import time
class Controller():
def __init__(self, sit="OFF", volume= 0, channel_list = ["NatGeo"], current_channel="NatGeo"):
self.sit = sit
self.volume = volume
self.channel_list = channel_list
self.current_channel = current_channel
def open(self):
if(self.sit == "ON"):
print("TV is al... |
a19400a7589286d02dfb57d1d890b3672dfc231d | caiocezarccas/Curso-Python | /ex03.py | 294 | 3.921875 | 4 | print('Olá seja bem-vindo(a)')
nome = input('Qual o seu nome? ')
print('É uma prazer em te conhecer {}!'.format(nome))
n1 = int(input('{}, digite um número: '.format(nome)))
n2 = int(input('Digite outro número: '))
s = n1 + n2
print('A soma entre {} e {} é: {}!'.format(n1, n2, s))
|
85f587854f6e595a22e0e3ff968d66add1fb9aca | marcinpgit/Python_exercises | /Exercises_1/rozdz4zad1.py | 274 | 3.78125 | 4 | print ("Program liczy za użytkownika.\n")
x = int(input("Wprowadź liczbę początkową: "))
y = int(input ("Wprowadź liczbę końcową: "))
y += 1
for i in range (x,y,1):
print (i, end = " ")
print ("\n\nTwoja liczba początkowa, końcowa to :", {x,y -1}) |
95502664b94fbf792a54930878027ffdddb4e6e6 | whitneysattler/python-gui | /DisplayAngles.py | 2,739 | 3.5625 | 4 | from tkinter import *
from Point import Point
import math
class TriAngles:
def __init__(self):
window = Tk()
window.title("Triangle Angles")
self.canvas = Canvas(window, width = 300, height = 200, bg = "white")
self.canvas.pack()
self.p1 = Point(40, 40)
self.p2 = Po... |
2cb52af7bf2ced7bbd3acd8357fbcb42e5591cb5 | Chansazm/Project_22_Tech_Series_Solutions | /decode.py | 956 | 3.9375 | 4 | def firstLetterWord(str):
result = ""
# Traverse the string.
v = True
for i in range(len(str)):
# If it is space, set v as true.
if (str[i] == ' '):
v = True
# Else check if v is true or not.
# If true, copy character in output
... |
1bdadf4b911e1e48a12bf68bb0ca0a57e86d979f | DhruvAwasthi/ModelsCollection | /DNN on MNIST /mnist_classifcation.py | 72,074 | 3.578125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
# Import the TensorFlow and output the verion
get_ipython().system('pip install tensorflow==1.14.0')
import tensorflow as tf
print("\n\nTensorFlow version:", tf.__version__)
# In[2]:
n_inputs = 28 * 28
n_hidden1 = 300
n_hidden2 = 100
n_outputs = 10
# In[3]:
tf.... |
f633cfa61b18bbe1cc74fb13075618b7bf594031 | KarlParkinson/practice | /algs/minCostPath.py | 669 | 3.78125 | 4 | def minCostPath(cost, m, n):
minMatrix = makeMatrix(m,n)
minMatrix[0][0] = cost[0][0]
for j in range(1,n+1):
minMatrix[0][j] = minMatrix[0][j-1] + cost[0][j]
for i in range(1,m+1):
minMatrix[i][0] = minMatrix[i-1][0] + cost[i][0]
for i in range(1,m+1):
for j in range(1,n+1):... |
9632f5ed5d01d2d88195a4ad5832282c3bca2b0f | enhanzhao/WebScraper | /user_feedback.py | 2,801 | 3.5 | 4 | # this is the start of user feedback
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
username = "370scraper2020@gmail.com"
password = "ILoveScrapers"
def send_mail(to_emails=None):
# to make sure to_emails is of type 'list'
assert isinstance(to_em... |
a69ef89f34eecc2d03bda3cc3945c85964a71740 | bihailantian/PythonPractice | /demo1/FilteredWords2.py | 906 | 3.71875 | 4 | #!/usr/bin/env python3
# -*- encoding:utf-8 -*-
'''
敏感词文本文件 filtered_words.txt,里面的内容为以下内容,当用户输入敏感词语时,则打印出 Freedom,
否则打印出 Human Rights。
'''
path = "..\\file\\filtered_words.txt"
def readFileContent(path):
word_list = []
with open(path,'r',encoding='utf-8') as f:
for line in f:
word_list.a... |
ca2a6a420b09b32c9f8d2b20b960319dc54196c4 | ldsantos0911/Personal-Work | /Project Euler/Problem6.py | 189 | 3.5625 | 4 | def sumSq():
total = 0
for i in range(1, 101):
total += i ** 2
return total
def sqSum():
total = 0
for i in range(1, 101):
total += i
return total ** 2
print(sqSum() - sumSq())
|
7e0e5bec6de99a22740ee8f00d52c9a19d9dc8c0 | matsushimen/iroiro | /brace_openner.py | 601 | 3.75 | 4 | import re
import sys
txt = input()
def blace_opener(text):
start = text.find("{")
end = text.find("}")
upper = text[:start]
inside = text[start+1:end]
bottom = text[end+1:]
inside_list = re.split(",",inside)
output_list = []
for word in inside_list:
output_list += [upper + wo... |
a0e08d2f60d8ac2bd77c38e8afdc9c0fea924cd1 | 3dmikec/python | /tic-tac-toe.py | 5,365 | 4.1875 | 4 | '''
PLAY A GAME OF TIC TAC TOE
'''
import random
# Print out a board, set up as a list, where each index 1-9 corresponds with a number on a number pad.
def display_board(board):
print('\n ',board[7],' | ',board[8],' | ',board[9])
print('-----------------')
print(' ',board[4],' | ',board[... |
40047ef7749802f2753a2f37e9b6127575238819 | awwkl/cs50 | /Week_6/readability.py | 995 | 4.03125 | 4 | def main():
text = input("Text: ") # get input text
index = get_index(text) # calculate index
print_grade(index) # print "Grade X" based on index
def get_index(text):
words = 1 # start at 1 because it counts by spaces e.g. "Dogs. Cats."
letters = sentences = 0
for cha... |
f6fb2b673e791e09f97733eba22ff6625868d6a7 | benjamn/project-euler | /2.py | 186 | 3.65625 | 4 | #!/usr/bin/env python
from util import bound, fibs
def answer(max):
evens = (i for i in fibs() if i % 2 == 0)
return sum(i for i in bound(evens, max))
print answer(10**6)
|
533c712813e98d7e526cabb38a6c3f384dd54d5d | cansley/PythonProjects | /MyFirstPython/words.py | 679 | 3.875 | 4 | """Module Level Documentation
Usage:
How to use this...
"""
__author__ = 'cxa70'
from urllib.request import urlopen
def fetch_words():
'''Retrieves a list of words from a URL.
Args:
url: The URL of a UTF-8 text document.
Returns:
A list of strings containing the words from the docu... |
80d890f4f177de0f2b586ace6c23b83c39862df0 | lydiaWangui/training101 | /classesAndObjects2.py | 551 | 3.71875 | 4 | class Card:
balance = 0
# constructor defines things that should run every time you call the classi
def __init__(self,bal):
self.balance=bal
def withdraw(self,amount):
if self.balance >= amount:
self.balance -= amount + (0.2*amount)
return self.printReceipt(sel... |
e7eef527a27a82606a9ddc44824067f7640454b9 | kemepley/Project_1 | /cleaning.py | 1,927 | 3.96875 | 4 |
import pandas as pd
# A function that allows us to drop rows based on values we think are suspect
def drop_rows(df, colname, val):
return df[df[colname] != val]
# A function to take columns with years (yr_built, yr_renovated) and bin them by decade
def bin_by_decade(df, colname):
bins = pd.IntervalIndex.fro... |
e181e33c52b7fff34845aa9cccaad5daa1731059 | darloboyko/py_courses | /homeworks/home_work_5/ListFibonacci.py | 358 | 4.28125 | 4 | #Напишите программу, которая выведет все числа Фибоначчи до заданного числа
#Например, пользователь вводит 100
#Ответ: 1 1 2 3 5 8 13 21 34 55 89
x = int(input("Enter x: "))
a = b = 1
print(a, b, end=" ")
while a + b <= x:
a,b = b,a+b
print(b, end=" ")
|
94c409329b266bad34976e37eaee8e6fd6769107 | georgiosdoumas/Manning-liveProject | /ClassMethods.py | 3,418 | 3.625 | 4 | class Connection:
initial_port = 55000
conn_limit = 10
conn_count = 0
def __init__(self, some_host):
self.host = some_host
if Connection.conn_count < Connection.conn_limit:
# self.port = Connection.initial_port + self.conn_count # I think that I get the same results with :
... |
01b28fae61869dabd1c88727da2700c422cdfe4b | ngocthuong2561992/pythoncoban | /renhanh.py | 281 | 4 | 4 | a = 5
if a - 1 < 0 :
print('a nho hon 1')
elif a - 2 < 0 :
print('a nho hon 2')
elif a - 3 <0 :
print('a nho hon 3')
else :
print ('Neu khong thoa thi boi vao day')
k= 0
while k < 3 :
print('value of k is', k)
k += 1
else :
print('k is not less 3 anymore')
|
3bd40a509226c1faf5fbff48ad8d4fdb28f7622b | basu-sanjana1619/python_projects | /rhymes.py | 1,138 | 4.3125 | 4 | #This program will read through a file and will extracts the email address along with the nursery rhyme name
#from it and will print out
dic = {}
doc = open("rhymes.txt")
for line in doc:
name = ""
if line.startswith("Nursery rhymes"):
#splitting the line to get the rhyme name and sender's email.
get_index = line.... |
f084a8f4f81eec665c4c73376404fda1caa4da92 | spanickroon/Information-networks-Security-basics | /vigenere_and_caesar_codes/caesar_code.py | 1,900 | 3.8125 | 4 | import string
def read_file(file_path: str) -> str:
text = None
with open(file_path, 'r') as rf:
text = rf.read()
return text
def write_file(file_path: str, text: str) -> None:
with open(file_path, 'w') as wf:
wf.write(text)
def define_alphabet(letter: str) -> tuple:
ENG_ALPH =... |
a094af4ae37cf53cc6301a154a88cbcf7c2a1eb9 | VitaliySid/Geekbrains.Python | /lesson4/task7.py | 748 | 3.890625 | 4 | # 7. Реализовать генератор с помощью функции с ключевым словом yield, создающим очередное значение.
# При вызове функции должен создаваться объект-генератор.
# Функция должна вызываться следующим образом: for el in fact(n).
# Функция отвечает за получение факториала числа,
# а в цикле необходимо выводить только первые ... |
ae2c00ec7dd69e8355dfaa6e06d54701250fbca0 | ArneVogel/aoc18 | /day1/frequency.py | 1,083 | 3.796875 | 4 | import sys
def parse_line(line):
operator = line[0]
operand = int(line[1:])
return (operator, operand)
def do_operation(operation, frequency):
if operation[0] == "+":
frequency += operation[1]
if operation[0] == "-":
frequency -= operation[1]
return frequency
def main():
f... |
4d35471e9dbe10bee6c38d6090323a62c5bd9b06 | teer-max/Gait-Analysis-ML | /cluster.py | 778 | 3.53125 | 4 | #This script is to Cluster the Data.
# It acts on an array of data and outputs
# clusters of the data under some function.
# The parameters for these clusters are
# Window, Stepsize, starts, stops, etc.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
def read_data(data):
df = pd.read_csv(da... |
13d725b94cae9a14d12457d32373549f46b4ac43 | iamslash/learntocode | /leetcode2/SortArraybyIncreasingFrequency/a.py | 287 | 3.671875 | 4 | # -*- coding: utf-8 -*-
# Copyright (C) 2020 by iamslash
# sort, hash map
# O(NlgN) O(N)
class Solution:
def frequencySort(self, nums: List[int]) -> List[int]:
cntMap = collections.Counter(nums)
ans = sorted(nums, key = lambda a: (cntMap[a],-a))
return ans
|
1e07b776c7521d856b90b1fd4b46a0a19918d45e | iankigen/data_stuctures_and_algorithms | /algorithms/sorting_algorithms/merge_sort.py | 1,501 | 4.25 | 4 | """
Merge sort is a recursive algorithm that continually splits a list in half. If the list is empty or has one item, it is
sorted by definition (the base case). If the list has more than one item, we split the list and recursively invoke a
merge sort on both halves. Once the two halves are sorted, the fundamental oper... |
f08667683cd8e3116968acb0315120bcd19dc79f | LBJ-Max/basepython | /字符串/test1.py | 516 | 4.59375 | 5 | # 字符串
hello_str = "hello world"
# 1.判断符串是否以指定的字符串开始
print(hello_str.startswith("hello"))
# 2.判断字符串结尾
print(hello_str.endswith("world"))
# 3.查找指定的字符串,索引,index也可以
print(hello_str.find("wor"))
print(hello_str.find("agb")) # 找不到输出-1 ,index找不到会报错
print(hello_str.index("wor"))
# 4.替换字符串,replace会返回新的字符串,不会修改原来的字符串
new_str ... |
c4673556c5836e19d7ec72f0ab929b47fb42c66e | Skeletrox/self-expansion | /caesarpher.py | 925 | 4.25 | 4 | #!usr/bin/env python3
'''
This program runs in Python 3.x. Any users of Python 2.x must upgrade before using this.
This uses the Mersenne Twister random number generator, which is completely deterministic and thus unsuitable for cryptography.
As this program is just an example, I'm really not hitting industry standards... |
610a38aee4d610040539da8d0816488e287c276c | AlexWufan/leetcode-python | /243. Shortest Word Distance.py | 517 | 3.6875 | 4 | class Solution(object):
def shortestDistance(self, words, word1, word2):
"""
:type words: List[str]
:type word1: str
:type word2: str
:rtype: int
"""
p = q = -1
distance = float('inf')
for i in range(len(words)):
if words[i] == word... |
e8dfd337df921dd390721a5976c176f597d77494 | zsmountain/lintcode | /python/569_add_digits.py | 818 | 4.03125 | 4 | '''
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
Have you met this question in a real interview?
Example
Example 1:
Input:
num=38
Output:
2
Explanation:
The process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return 2.
Example 2:
Input:
num=9... |
80cc87e74ee5b18d3a36737ad79f2ed62bf24ce8 | blake-lowe/ENGR133PyTeamProject | /fastblur.py | 3,263 | 3.734375 | 4 | '''
===============================================================================
ENGR 133 Program Description
This function takes an image array, a size number and a blur value and returns an array that contains a blurred image
Assignment Information
Assignment: Python Group Project
Author: Marcus L... |
3ceaeba695c4d44d211f3bfb071719c223734893 | badandworse/leetcodeAns | /剑指offer/chapter4/33.py | 729 | 3.515625 | 4 | # -*- coding:utf-8 -*-
class Solution:
def VerifySquenceOfBST(self, sequence):
# write code here
if not sequence:
return False
return self.isOK(sequence)
def isOK(self,sequence):
if not sequence:
return True
root=sequence[-1]
i=0
... |
443b0556fcda4cadc81048f8d6c861a72fd58c78 | ksommerh94/CS521_InformationStructuresWithPython | /ksommer@bu_edu_hw_4/ksommer@bu_edu_hw_4_6.py | 432 | 4 | 4 | '''
Karen Sommer
CS 521 Spring 2021
Assignment 4
Problem 6 pages 476-479
'''
# If you had 2 lists , one of first names and one of last names ['Jane','John','Jack'] and ['Doe','Deer','Black']
# Use zip to create a dictionary witht he keys as the first names and values as last names.
first_names=['Jane','John','Ja... |
f541af8b770bc87282ad06a0ad341c6abf0c50bf | qiujiamin/pypro | /python/fileios/testnone.py | 436 | 3.984375 | 4 | #! /usr/bin/env/python
# -*- coding:utf-8 -*-
# info = {
# 'name':'班长',
# 'id':'100',
# 'sex':'f',
# 'address':'GGHH'
# }
# age = info.get('age')
# print(age)
# age= info.get('age',18)
# print(age)
# def f(a,b):
# if b ==0:
# print(a)
# else:
# f(b,a%b)
#
# if __name__ == '__mai... |
3e8f82ef9052ee5c45bd6dcb8265b9854a5f958b | jbanerje/Beginners_Python_Coding | /loop_list.py | 306 | 3.953125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jul 16 16:33:47 2017
@author: jagan
"""
list1 = ['apple','orange','banana','grapes','kiwi']
list2 = []
for item in list1:
if (item =='orange'):
print ("I found it!")
list2.append(item)
print(list2)
#else:
#print("couldn't find") |
3106dc0a6e0abe4e48af97fb667b24ba05b6e3ba | relsqui/protocards | /protocards/tests/test_standard.py | 2,565 | 3.609375 | 4 | #!/usr/bin/python
import unittest
import random
from .. import standard
class TestStandard(unittest.TestCase):
def test_suit(self):
suit = standard.Suit("FOO")
self.assertEqual(suit.name, "FOO")
self.assertEqual(suit.plural, "FOOs")
self.assertEqual(suit.short, "f")
def test... |
4edff49f9e6fddcf84088153eed5694e0f217397 | fsMateus/exerciciosPython | /fase3/exercicio51.py | 275 | 3.765625 | 4 | s = ''
cont = 1
soma = 0
n = int(input('Digite o número de termos: '))
for i in range(1, n+1):
if i == 1:
s += '{}/{}'.format(i, cont)
else:
s += ' + {}/{}'.format(i, cont)
cont += 2
soma += i/cont
print('S = {}\nS = {:.2f}'.format(s, soma)) |
11db6aaa2dc3f5454c6dde9b2b6e0c19c29c200e | Dewansh237/Alarm-Clock | /college project.py | 2,232 | 3.53125 | 4 | import sys
import turtle
import winsound as ws
import time
#Alarm Clock Screen
md = turtle.Screen()
md.setup(width=400, height=300)
md.bgcolor("white")
md.title("ALARM CLOCK")
md.tracer(0)
#Pen 1
p1 = turtle.Turtle()
p1.speed(0)
p1.penup
p1.hideturtle()
#Pen 2
p2=turtle.Turtle()
p2.speed(0)... |
ff257ba460e7fc20da3c6065e3f7cdb1acdb7c91 | colecarroll/py_ds_algo | /binarySearchTree/findClosestValueInBst.py | 1,643 | 3.765625 | 4 | # Write a function that takes in a Binary Search Tree(BST) and a target integer value and returns the
# closest valeu to that target value contained in the BST.
# Assume there is only one closest value.
# Each BST has an integer value property called 'value', a 'left' child node, and a 'right' child node. Child nodes... |
fc8b5432b97b37dba1115b9d37d9893e280c64f7 | bal13/python_udemy_masterclass | /ProgramFlow/truefalse.py | 378 | 4.15625 | 4 | # day = "Friday"
# temperature = 30
# raining = False
#
# if (day == "Saturday" and temperature > 27) or not raining:
# print("Go swimming")
# else:
# print("Learn Python")
if 0:
print("True")
else:
print("False")
name = input("Please input a name: ")
#if name:
if name != "":
print("Hello, {}".for... |
90cce1e6e6f129a713e63622537eb3c9276ebbff | shreyareddy-mahareddy/Data_Interesting_Analytics | /Iris_Visualizations.py | 2,178 | 3.671875 | 4 |
# coding: utf-8
# In[2]:
# Import libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')
# In[11]:
# Import the dataset using pandas as a mxn matrix
# Note - The working directory has been set as the location where the csv is locate... |
dd8ee89d6eda71c672bf06e5308a8107db087a9a | Alvaro-Carrizosa-Munoz/Ataque-Cifrado-Afin | /Codigo.py | 1,147 | 4.09375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#LAS DEFINICIONES DE MCM,MCD,INV_MULT NO LAS INCLUYO EN EL CÓDIGO, VALE CUALQUIER FUNCION QUE REALICE ESA TAREA
diccionario = "ABCDEFGHIJKLMN3OPQRSTUVWXYZ"
print("Creado por Carlos Andres Iborra Alvarez")
texto = raw_input("Introduzca el texto a descifrar mediante un at... |
e5c61e2757dfdb12c9d280a21f2f6067a4635769 | italou/interactive-python-2014 | /week5-memory_game.py | 4,414 | 3.5625 | 4 | """
Week 5 Mini-project
Descprition: Implementation of the Memory card game
Author: Itamar M. B. Loureno
Date: 2014-10-23
"""
# imports
import simplegui
import random
# global variables
state = 0 # card choice state
deck = [] # deck of 16 cards
exposed = [] # list of exposed cards
turned_card1 = -1 # pre... |
d44d665acc8642db648c3b37c2c59400ee6af327 | brahmajirao/PyDataStructures | /src/LinkedLists/DoublyLinkedList.py | 5,481 | 4 | 4 | class Node:
"""" Class creates Node for doubly linked list."""
def __init__(self, data = None, next = None, prev = None):
self.data = data
self.next = next
self.prev = prev
def set_data(self, data):
self.data = data
def set_previous(self, prev):
self.prev = pre... |
66cb30d07f7bb7944977713d44abce375ed59633 | neel-t/math4575-hw8 | /pr.py | 1,121 | 3.859375 | 4 | import math
from fast_power import fast_power
def is_prime(num):
for n in range(2, int((num**1) / 2) + 1):
if num % n == 0:
return False
return True
def get_prime_factors(n):
prime_factors = set()
while (n % 2 == 0):
prime_factors.add(2)
n = math.floor(n /... |
8fc494ff9a48770815c07fdc8401f601dde9985c | sanemiliano/Artificial-Intelligence-Projects | /Inteligencia Artificial 1/Tarea 2 Programacion en Python/T2e2.py | 417 | 3.703125 | 4 | import random
numbers = []
b = 5
cont = 0
while b <= 1000:
numbers.append(b)
b += 5
cont += 1
Matrix = [[0 for x in range(4)] for y in range(2)]
numbers2 = [1 for x in range(10)]
print("Columnas: 2")
print("Filas: 4")
print("Elementos en V: 5")
numbers3 = [[0 for x in range(4)] for y in range(5)]
f... |
8a45a29430818b505f51ffaaf9ec74bb4c86963e | Waka-Entertain/Let-code-everyday | /Python/zigzag_conversion.py | 1,207 | 3.5 | 4 | class Solution:
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if numRows == 1:
return s
converted = ['' for i in range(numRows)]
T = numRows*2-2
length = len(s)
cursor = 0
while ... |
9619ba259a8e0604364958de9410cc31d3bdc252 | LoppA/django-pizza | /pyexamples/loops.py | 493 | 4 | 4 | a, b = 1, 2
pedidos = [
{
'nome': 'Mario',
'sabor': 'portuguesa'
},
{
'nome': 'Marco',
'sabor': 'presunto'
}
]
for pedido in pedidos:
print('Nome: {0}\nSabor: {1}' .format(pedido['nome'],pedido['sabor']))
#printa na ordem q ta
for pedido in pedidos:
pr... |
3a678747a4c1cd0996f87adcbecba4d4e4aa94f0 | aynulislam/python_basic_covid_19 | /day7 part1.py | 459 | 4.21875 | 4 | #1 split() method takes string and gives us list
message = input(" enter your message please: ")
print(message.split())
#2 strip() method gives us spacess
message = input(" enter your message please: ")
print(message.strip())
#3
message = input("enter your input please :")
words = message.split(" ")
emojis = {
... |
a6bcb1987e8bf14dfb7e850f62a853d2f27854d5 | hwang787/Random-forest-simulator | /util.py | 6,658 | 3.828125 | 4 | from scipy import stats
import numpy as np
import time
# This method computes entropy for information gain
def entropy(class_y):
# Input:
# class_y : list of class labels (0's and 1's)
# TODO: Compute the entropy for a list of classes
#
# Example:
# entropy([0,0... |
cdb827c16ef385592bbe53cd231ad22e4e0c67dc | d04943016/ColorScience | /ReaderWriter/Reader/tagline.py | 5,909 | 3.890625 | 4 | #!/usr/bin/env python3
# Copyright (c) 2018 Wei-Kai Lee. All rights reserved
# coding=utf-8
# -*- coding: utf8 -*-
"""
my_tagline is a module to process tag line. (read/write)
1. readTagColNum(tagTokens, tagstrList):
is a function to judge whether the tag in tagTokens is in tagstrList
and retrun th... |
069d4e4fbde91267a88edffcfba64b43f0727038 | duck213/prog_statistics | /hyp_testing.py | 739 | 3.625 | 4 | import numpy as np
import scipy as sp
from scipy import stats
# 1. Binomial Hypothesis Testing
np.random.seed(seed=0)
random_ber = np.random.binomial(n=1,p=0.5,size=50)
n_ber = np.count_nonzero(random_ber)
# Hypothesis Testing
binom_test = sp.stats.binom_test(n_ber,50)
print('Binomial Testing:',binom_test)
# 2. Po... |
5de2e005634cc6400d070f0506f87615ca42363f | TamimEhsan/CSE218_Numerical_Methods | /Week 03/1805022/main.py | 772 | 3.828125 | 4 | import math
def f(x):
return x/(1-x) * (6/(2+x))**0.5-0.05
def find_Root_By_Bisection_Method(lower,upper,ERROR,MAX_ITERATION):
iteration = 0
prev_solution = 0
for iteration in range(MAX_ITERATION):
mid = (lower+upper)/2
if iteration!=1:
error = math.fabs((mid-prev_solution)... |
63b648c46a683b592c4fb1a8096003bcf08bb5f9 | Jiaqingzhu29/Jiaqingzhu29 | /feibonacii.py | 216 | 3.890625 | 4 |
n=int(input("需要第几项\n"))
a=0
b=1
i=2
if n==1:
print(a)
elif n==2:
print(b)
else:
while(i<n):
result=a+b
a=b
b=result
i+=1
print(result)
|
5925f823d31fb90a9120741733ff20ade7f3371a | samanthaworthington/Practicals | /prac_02/files.py | 444 | 3.78125 | 4 |
name_file = open("name.txt", 'w')
name = str(input("Enter your name: "))
print("{}".format(name), file=name_file)
name_file.close(
name_file = open("name.txt", 'w')
name1 = str(input("Enter you name: "))
print("Your name is {}".format(name1), file=name_file)
name_file.close(
number_file = open("numbers.txt", "r")... |
8e827df9cc4bed5c6cd9e9fd717a5635c475ef5a | jsomers/project-euler | /15.py | 793 | 3.765625 | 4 | # How many paths are there from the top left corner of a 20 x 20 grid to the bottom right corner?
# This needs to be iterative, it's taking way way too long
from time import time
start = time()
# very fast, based on the central binomial coefficient
def mul(x, y):
return x*y
def fact(n):
facts = []
for i in range... |
014d789d335212734e86f187144e5933c9e7a4eb | lpylyp/python.course | /Lection2/funt.ex5.py | 674 | 4.0625 | 4 | # Написати функцію (len_of_args), яка приймає ключові та позиційні аргументи ( вертає довжину
# позиційних елементів - len(args) ) . Також написати функцію rand_of_el, яка двічі викликає функцію
# len_of_args і вертає різницю результатів. Викликати функцію rand_of_el і надрукувати результат.
def len_of_args(*a... |
5689075ceebbaeaf42e66e32e69b5bccda6c3685 | andreplacet/solyd_treinamentos | /expressoes_regulares.py | 1,061 | 4.1875 | 4 | import re
string_teste = 'Python é uma linguagem, bonita, simples e muito poderosa' \
'o Python é muito utilizado para analise de dados, segurança da informação,' \
'desenvovilmento WEB e mobile entre outras possibilidades do Python.'
padrao = re.search(r'Python', string_teste) # RAW ST... |
dedcb2b64d11f5292ae2cbe2b32feed56ae88315 | SSITB/Machine_Learning | /BitTiger_DS501/DS501_PyAlgo_factorial.py | 753 | 3.71875 | 4 | def factorial(n):
if n == 0:
return 1
if n == 1:
return 1
return n * factorial(n-1)
def combination(n, k):
return factorial(n) / (factorial(n-k) * factorial(k))
memo = {}
def factorial_memo(n):
if n in memo:
return memo[n]
if n == 0:
memo[0] = 1
return... |
9f85138ac2e4d043af9d6b3795cc5ad4bb45648f | rafaelperazzo/programacao-web | /moodledata/vpl_data/40/usersdata/136/22022/submittedfiles/funcoes.py | 2,815 | 3.671875 | 4 | #ARQUIVO COM SUAS FUNCOES
from __future__ import division
#Na função seguinte, calcula-se o valor absoluto da seguinte forma - se o x tiver valor menor que zero, ou seja,
#negativo, o valor absoluto é igual a esse valor negativo de x multiplicado por "-1". A função retorna o valor absoluto
#(módulo) de x.
def calcula_... |
3c474cb00e72fc3f9f1f3f0fd717ac39b419ebb5 | nenad1002/CDM-trait-semantic-analysis | /noise_manager.py | 2,262 | 3.890625 | 4 | class NoiseManager:
'''Noise manager is a class which deals with noise among features and it tries to throw away traits
which might be too noisy for additional processing. This means that all traits are still candidates
for classification process, but the noisy traits will never be included if our features ... |
f230316cc8b000af91cae98687ffac5f970d6e68 | saikumarpochireddygari/Interview_Prep | /Reorder_Linked_List.py | 859 | 3.859375 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reorderList(self, head: ListNode) -> None:
"""
Do not return anything, modify head in-place instead.
"""
if not head or head.next is None... |
f2c567ab6b86d5292c6f69ea876d28da1a5256ec | divanescu/python_stuff | /coursera/webd/testing_assn42.py | 1,058 | 3.640625 | 4 | # Note - this code must run in Python 2.x and you must download
# http://www.pythonlearn.com/code/BeautifulSoup.py
# Into the same folder as this program
import urllib
from BeautifulSoup import *
url = raw_input('Enter - ')
count = int(raw_input("Count: "))
position = int(raw_input("Position: "))
for i in range(cou... |
17861f8850a000d632ab35326841418b5d757791 | mridulrb/Basic-Python-Examples-for-Beginners | /Programs/Python/Files12.py | 251 | 3.640625 | 4 | myfile=open("first.txt","r")
size=0
tsize=0
str1=" "
while str1:
str1=myfile.readline()
tsize=tsize+len(str1)
size=size+len(str1.strip())
print "Size with all the characters",size
print "Total size of file",tsize
myfile.close()
|
5884b7c5898074d2dc12e3be42a11765dfe74040 | hanglearning/alpha_beta_pruning | /alpha_beta_pruning.py | 6,371 | 3.71875 | 4 | # alpha, beta value ref - https://www.youtube.com/watch?v=xBXHtz4Gbdo
# another ref - https://www.youtube.com/watch?v=zp3VMe0Jpf8
import sys
# get user input
user_input_numbers = sys.argv[2].split(' ')
# used to store the nodes to be pruned. Note: may not be the terminal nodes
prune_list = []
# we treat MIN and MAX ... |
c51602f301be28781a39101686e95055d51253e4 | AdadaBdada/Leetcode | /242.Valid_Anagram.py | 769 | 3.765625 | 4 | # 242. Valid Anagram
# Python 3
class Solutions:
# dictionary
def isAnagram1(self, s: str, t: str) -> bool:
# edge case
if len(s) != len(t):
return False
dic = {}
for i in s:
dic[i] = dic.get(i, 0) + 1
for j in t:
dic[j] = dic.get... |
dcf3fe1f721282b22b6cbd49cab2fca9f11df0f0 | alex-shef/geekbrains_algorithms | /lesson4/les_4_task_2_1.py | 7,633 | 4 | 4 | """
Решето Эратосфена.
Функция самостоятельно расширяет массив при необходимости.
Не придумал только, как использовать этот метод сразу в расширенной части(без
повторного прохода).
"""
import timeit
import cProfile
def eratosthenes(n): # n - номер простого числа, которое нужно получить
size = n * 3 # начальны... |
0156b4c1a78fce442cfd934e9781a90305ddf4a4 | borntoshine1/py_course_nechaeva_olga | /homework/hw13/task13_8.py | 873 | 3.671875 | 4 | def two_sum(numbers, target):
i = 1
j = 0
while i < len(numbers):
if numbers[i]+numbers[j] == target:
return [j, i]
if i==len(numbers)-1:
j+=1
i=j
i+=1
print(two_sum([1,2,3,1,2], 4))
print(two_sum([2,2,3,1,3], 4))
print(two_sum([3,2,1... |
c526c24375968a974f0cc3db2cd7d4936aafda57 | edneyefs/curso_python_fundamentos | /13DESAFIO050.py | 345 | 3.921875 | 4 | #programa que lê seis números e mostra a soma somente dos pares
soma = 0
cont = 0
for c in range(1, 7):
n = int(input('Digite o {}º valor: '.format(c)))
#condição para o número ser par ou mutiplo de dois
if n%2 == 0:
soma += n
cont += 1
print('Você informou {} pares e a soma deles é {}.'.for... |
4a4c803bd9d01912842d12ae6cb3d5c3117c38cc | chinasilva/MY_LEET_CODE | /43.字符串相乘.py | 2,020 | 3.90625 | 4 | #
# @lc app=leetcode.cn id=43 lang=python3
#
# [43] 字符串相乘
#
# https://leetcode-cn.com/problems/multiply-strings/description/
#
# algorithms
# Medium (38.72%)
# Total Accepted: 16.4K
# Total Submissions: 42.2K
# Testcase Example: '"2"\n"3"'
#
# 给定两个以字符串形式表示的非负整数 num1 和 num2,返回 num1 和 num2 的乘积,它们的乘积也表示为字符串形式。
#
# 示例... |
352995fc9653e83111180dcaba567b53ea0f649f | liyingliincsvw/test | /project C.py | 1,643 | 3.546875 | 4 | # -*- coding: utf-8 -*-
from sklearn.cluster import KMeans
from sklearn import preprocessing
import pandas as pd
import numpy as np
data = pd.read_csv('CarPrice_Assignment.csv', encoding='gbk')
#print(df1)
d = pd.read_excel('Data_Dictionary_carprices.xlsx')
df = pd.DataFrame(data)
aa = []
aa = list(df.col... |
5b594af0a934521dca4d5d77c24632d991027d32 | sandaar/homework_3 | /letters_frequency.py | 1,174 | 3.828125 | 4 | from string import punctuation
from collections import Counter
import argparse
from ascii_graph import Pyasciigraph
def load_file(filename):
with open(filename, 'r') as f:
text = f.read().lower()
return text
def get_words(text):
return [w.strip(punctuation) for w in text.split() if w.strip(punc... |
b9c28d32b00a88dca3146340c0666c4df4a05ac0 | deepcpatel/data_structures_and_algorithms | /Trees/remove_half_nodes.py | 1,984 | 4.25 | 4 | # Link: https://practice.geeksforgeeks.org/problems/remove-half-nodes/1
'''
Given A binary Tree. Your task is to remove all the half nodes (which has only one child).
Example 1:
Input:
7
/ \
7 8
/
2
Output: 2 7 8
Example 2:
Input:
2
/ \
7 5
... |
bab37444773f461e226a6a69ce50727a7a70ebc9 | WuYunjin/Two-step-python | /Two-Step/betaAlasso_grad_2step.py | 3,704 | 3.671875 | 4 | import numpy as np
from pdinv import pdinv
def betaAlasso_grad_2step(x,y,var_noise,lam):
"""
% Aim:
% to find the solution of adaptive Lasso with the given lambda
% Inputs:
% x is p*n, and y is 1*n. var_noise is the variance of the noise.
% Outputs:
% beta_al contains t... |
c437e2b2397e99a209a6b2273117a443d198e277 | gschen/where2go-python-test | /1906101041刘仕豪/第九周练习题/3.py | 802 | 4.125 | 4 | '''
3、 输入三个整数x,y,z,请把这三个数由小到大输出。
'''
# x = int(input("请输入正整数x:"))
# y = int(input("请输入正整数y:"))
# z = int(input("请输入正整数z:"))
# if y>x and y>z and z>x:
# x1 = y
# y1 = z
# z1 = x
# elif y>x and y>z and x>z:
# x1 = y
# y1 = x
# z1 = z
# elif x>z and z>y:
# y1 = z
# z1 = y
# x1 = x
# eli... |
8c1f7304fdb24437cbb0ae47b22c4b6d6e3f060d | josephappeah/CSWORK | /CS260/3/problem1.py | 262 | 3.71875 | 4 | #!/usr/bin/python
#Sunny Shah
#CS260 Week 3
#problem 1
import sys
def fib(x):
if x == 0:
return 1
elif x == 1:
return 1
else:
return fib(x-1) + fib(x -2)
def main (argv = sys.argv):
print fib(int(sys.argv[1]))
if __name__ == "__main__":
main()
|
17c87c8999867723851f7e9bb4a37c24cd792ee4 | Akshay2903/An-Adventure-Games-OOPS- | /turtlerace/turtle_race.py | 658 | 3.5 | 4 | from turtle import Turtle
from random import randint
akshay =Turtle()
akshay.color('black')
akshay.shape('turtle')
akshay.penup()
akshay.goto(-160,100)
akshay.pendown()
vasu =Turtle()
vasu.color('green')
vasu.shape('turtle')
vasu.penup()
vasu.goto(-160,70)
vasu.pendown()
ashu =Turtle()
ashu.color('blue')
ashu.shape(... |
5b5cf052d18c01ee15fd0c4882d99d49f2353eea | tnetennba999/Puzzle-Simulation | /Coin_flip_puzzle_simulator.py | 2,006 | 3.71875 | 4 | '''
coin filp simulation
question: there are 100 coins lay flat on a table. 10 of them are head, remaining 90 are tails.
You could not feel/see which coin is head/tail.
Split 2 piles of coin so that each pile has the same number of head coin.
'''
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
i... |
461a793b484528908c74c1ebf5d5d903cbdaeb5a | zhiymatt/Leetcode | /Python/64.minimum-path-sum.132135318.ac.python3.py | 1,226 | 3.71875 | 4 | #
# [64] Minimum Path Sum
#
# https://leetcode.com/problems/minimum-path-sum/description/
#
# algorithms
# Medium (40.77%)
# Total Accepted: 146.5K
# Total Submissions: 359.4K
# Testcase Example: '[[1,3,1],[1,5,1],[4,2,1]]'
#
# Given a m x n grid filled with non-negative numbers, find a path from top
# left to bott... |
68f45f75482accaede859a47f1b12df68ad902e0 | ManuDeBuck/NeuralNetwork | /lib/perceptron.py | 1,077 | 3.65625 | 4 | import random
class Perceptron:
"""
Implementation of a single Perceptron.
"""
def __init__(self, amount_inputs, activation, learning_rate):
self.weights = [random.uniform(-1, 1) for _ in range(amount_inputs)]
self.weights.append(random.uniform(-1, 1)) # Add bias value in weights
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.