blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
a6ed1818c3c9fd26128c5e1534679582d9b9e993 | kumarnishkarsh/rishiProgram | /Python/Interactive App.py | 1,697 | 4.25 | 4 | print('INTERACTIVE APP')
print('---------------')
print('Hi,I AM ROBOTHON')
print('I AM A ROBOT IN PYTHON, YOU WILL DEFINITELY HAVE FUN WITH ME.')
y_n = str(input('DO YOU WANT TO TALK WITH ME?'))
y_n = y_n.lower()
if y_n == 'yes':
print('Oh! that is nice of you.')
print('OK, let us first get introdu... |
a5ac755fb77be130a9dcdbd5de510a3e83f4e8df | Ro7nak/python | /basics/regex/app2.py | 1,031 | 3.765625 | 4 | import re
flight_details="Flight Savana Airlines a2138"
if(re.search(r"Airlines",flight_details)!=None):
print("Match Found: Airlines")
else:
print("Match Not Found")
if(re.search(r"a2138$",flight_details)!=None):
print("Match Found: a2138")
else:
print("Match Not Found")
if(re.search(r"^F",flight_d... |
8adbda84552b7a489a41947ca7f39ad34a44c4ab | strawnp/ap-csp-20-21 | /unit3/divisible.py | 232 | 3.90625 | 4 | import cs50
x = cs50.get_int("Enter a number: ")
y = cs50.get_int("Enter another number: ")
remainder = x % y
if remainder == 0:
print(f"{x} is evenly divisible by {y}")
else:
print(f"{x} is not evenly divisible by {y}")
|
9012604259d98cd948590809a44e411dcba8af92 | LindaM14/Programming_Logic_and_Design | /LAB_11/WordBank_Word&Excel.py | 1,182 | 3.65625 | 4 | from openpyxl import Workbook
import requests
import docx
# API URL
word_bank = 'http://api.worldbank.org/v2/country?format=json&per_page=400'
response = requests.get(word_bank).json()
# Entering the page/index of the dictionary
country_info_list = response[1]
# creating the word docx sheet
document = docx.Document... |
1d46918d74b051086b07877e91d1177de0b618ed | VINEETHREDDYSHERI/Python-Deep-Learning | /ICPLab3/src/Question2.py | 677 | 3.5625 | 4 | # Importing the packages
import requests
from bs4 import BeautifulSoup
html = requests.get("https://en.wikipedia.org/wiki/Deep_learning") # Getting the content of the site
bsObj = BeautifulSoup(html.content, "html.parser") # Parsing the html data
print("The Title of the page is: ", bsObj.title.string)
linksData = b... |
4ea079204139d8c5e13d32edb39a76e7efe93bbd | OliviaRW/group23 | /Exam/Migration/data_cleaning.py | 5,434 | 3.984375 | 4 | from dependencies import *
def remove_stopwords(lst):
with open('stopord.txt', 'r') as sw:
#read the stopwords file
stopwords = sw.read().split('\n')
return [word for word in lst if not word in stopwords]
def lemmatize_strings(body_text, language = 'da', remove_stopwords_ = True):
"""... |
8e892b4bb6f8a61828c9597e5ca6070b19cdd29a | NitishShandilya/CodeSamples | /generatePrimeFactors.py | 1,398 | 4.4375 | 4 | """
Given a number n, write an efficient function to print all prime factors of n.
Solution:
Following are the steps to find all prime factors.
1) While n is divisible by 2, print 2 and divide n by 2.
2) After step 1, n must be odd. Now start a loop from i = 3 to square root of n.
While i divides n, print i and di... |
b8fe9077e12e664eafd51abd20cc1ee86c27076a | bainco/bainco.github.io | /course-files/lectures/lecture11-old/old/02_operator_functions.py | 467 | 4.15625 | 4 | from operator import add, mul, sub, truediv, mod, floordiv, pow
# for more info, see the docs: https://docs.python.org/3/library/operator.html
# Challenge:
# Using the functions above (no operators), write a program to
# calculate the hypotenuse of several right triangles with the
# following dimensions, and prints ... |
d961b3286a52dc67b609c3c99db7dcc94e23fb4d | nandansn/pythonlab | /myworkouts/rent-calc.py | 753 | 3.5625 | 4 | def rentCalc(rent=0,years=0,increment=0):
totalRent=0
fromYearOne=1
prevYearRent = 0
for i in range(fromYearOne,years):
if (i == 1):
prevYearRent = prevYearRent + (12 * rent)
print('Rent for the year {} is {}:',i,prevYearRent)
totalRent = prevYearR... |
d10e86a993fc99c3e5d95e46b4a5f122567596f5 | holzschu/Carnets | /Library/lib/python3.7/site-packages/networkx/algorithms/isomorphism/isomorph.py | 6,646 | 3.515625 | 4 | """
Graph isomorphism functions.
"""
import networkx as nx
from networkx.exception import NetworkXError
__author__ = """\n""".join(['Aric Hagberg (hagberg@lanl.gov)',
'Pieter Swart (swart@lanl.gov)',
'Christopher Ellison cellison@cse.ucdavis.edu)'])
# Copyright... |
c60655bae8f75a2a514a945553805d6bed8d01aa | DanieleMagalhaes/Exercicios-Python | /Mundo3/Tuplas/analisaTupla.py | 787 | 3.875 | 4 | print('-'*50)
numeros = (int(input('Digite um número: ')),
int(input('Digite outro número: ')),
int(input('Digite mais um número: ')),
int(input('Digite o último número: ')))
print('-'*50)
print(f'\33[32mOs números digitados foram: \33[m{numeros}')
print(f'\33[32mO número 9 apareceu {numeros.c... |
03eeb65c199d8bb0432123632f337d46e80b1a1a | Liang5757/Collaborators | /utils/Fraction.py | 1,887 | 3.8125 | 4 | # 把所有数当成分数
class Fraction(object):
# 支持 7 "8/6" "1'2/7" 及 "7"和"8"的构造
def __init__(self, molecular, denominator=1):
# 分子
self.molecular = molecular
# 分母
self.denominator = denominator
z = 0
if isinstance(self.molecular, str):
# 如果为带分数则分离整数部分
... |
dc4effd7d74257438e16978270e4dc3fcdb7eb5a | dvgupta90/sept-10th---restaurant-ratings | /ratings.py | 2,101 | 4.125 | 4 | """Restaurant rating lister."""
# put your code here
import sys
import random
filename = sys.argv[1]
my_file = open(filename)
restaurants_dict = {}
for line in my_file:
words_list = (line.rstrip()).split(':')
restaurants_dict[words_list[0]] = int(words_list[1])
while True:
print("Please select o... |
be5040ad3319831792f9c9655cead0b72035db3f | MartyVos/Les8 | /fa8_NS-kaartautomaat.py | 1,685 | 4 | 4 | def inlezen_beginstation(stations):
while 1:
start = input("Geef uw beginstation: ")
if start in stations:
return start
else:
print("Deze trein komt niet in", start)
def inlezen_eindstation(stations, beginstation):
while 1:
eindstation = input("Geef uw e... |
8da648f0c73a75d25cda087ddc68dcc7c0e7ad4c | b4s1cst4rt3r/BWINF-JUNIORAUFGABEN17-18 | /BWINF17-J1-.py | 1,627 | 3.75 | 4 | deko = int(input()) # Sektion Eingabe
anzahl = int(input())
buecher = [] # Erstellen einer leeren Liste
for i in range(0, anzahl): # input in Liste einordnen
buecher.append(int(input())) # im Beispiel erwähnte Typ-Änderung des inputs
buecher.sort() # elemente der liste der Größe nach sortieren
# Sekt... |
79945554a0817a7b844e460669eedb6e66f0efdf | huiqi2100/searchingsorting | /quicksort.py | 401 | 3.859375 | 4 | # quicksort.py
def quicksort(array):
if array == []:
return []
else:
pivot = array[0]
less = []
great = []
for item in array[1:]:
if item < pivot:
less.append(item)
else:
great.append(item)
less = quicksort... |
20f7e310ec1e914d935eb96436ab5ffc659d6368 | stephane-robin/Mathematics | /new LU.py | 4,010 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Nov 20 17:34:28 2014
@author: stef
"""
# FEM METHOD FOR THE EQUATION u''=exp(x)
# Program written Python 3.3
# This program finds the solution of the equation u''=exp(x) using the FEM
# We claim to transform the problem into the resolution of the linear problem
# Au... |
906e47938d25c1caa4d841f1e3b8a38d967bd110 | maturivinay/python_lee | /Lab_Assignment_2/Q_4.py | 912 | 3.5 | 4 | from sklearn.neighbors import KNeighborsClassifier
from sklearn import datasets, metrics
from sklearn.model_selection import train_test_split
# Loading the dataset
irisdataset = datasets.load_wine()
# getting the data and response of the dataset
x = irisdataset.data
y = irisdataset.target
x_train, x_test, y_train, y... |
0e62ac96c52f2b7000114a076da5805b3dd18585 | FriggD/CursoPythonGGuanabara | /Mundo 1/Desafios/Desafio#34.py | 436 | 3.828125 | 4 | #Escreva um programa que pergunte o salário de um funcionário e calcule o valor de seu aumento
# 1. Para salários superiores a R$1250,00, calcule um aumento de 10%
# 2. Para inferiores ou iguais, o aumento é de 15%
#
salario = float(input('Digite seu salário: '))
if salario > 1250:
print ('seu novo salário é: {}'.f... |
3db0f05820f7a293202f51f1e9951bd139289776 | vihangab/Webserver-Python-Flask | /webserver1/1 | 1,389 | 3.75 | 4 | #!/usr/env python
# Author :Vihanga Bare #
import socket
from threading import Thread
from SocketServer import ThreadingMixIn
# New thread created for evry connection #
class RequestThread(Thread):
def __init__(self,ip,port):
Thread.__init__(self)
self.ip = ip
self.port = port
... |
56bd8b77e501f66a82f7ae26dc469a3d5f3cee16 | sabrinaaraujoo/Python | /crime.py | 576 | 3.703125 | 4 | #crime
#entrada
p_a = int(input("Telefonou para a vítima? 1-SIM ou 0-NÃO: \n"))
p_b = int(input("Esteve no local do crime? 1-SIM ou 0-NÃO: \n"))
p_c = int(input("Mora perto da vítima? 1-SIM ou 0-NÃO: \n"))
p_d = int(input("Devia para a vítima? 1-SIM ou 0-NÃO: \n"))
p_e = int(input("Já trabalhou com a vítima? 1-SI... |
95ed3f218561546b17a3aefade90b35428a48463 | JahnaviPC/Python-Workshop | /CentegrateToFarenheit.py | 295 | 4.125 | 4 | Convert centegrade to farenheit
#( f= 9/5*c+32)
c = float(input("Enter the centigrade value to be converted:"))
print("the converted value of centigrade to farenheit is:",(1.8*c)+32)
OUTPUT:
Enter the centigrade value to be converted:0
the converted value of centigrade to farenheit is: 32.0
|
ca232518f118beb13275bf104c7374ad3615a54c | kesfrance/textToHistogram | /textToHistogram.py | 3,734 | 4.25 | 4 | #1/usr/bin/python3
#
#
# by: Francis Kessie
#
#
"""
Process text from input file and implements a histogram creation algorithm.
This program takes input text file and counts all text in file.
symbols and punctuation marks are ignored. The program returns a table
with word size and corresponding word counts a... |
ac338ad0f44846e1cc79b4055b3975cddc3f5fa7 | luoxuele/ds | /python/linkList/linkList.py | 2,592 | 3.921875 | 4 | class Node(object):
def __init__(self, value=None, next=None):
self.value = value
self.next = next
def __str__(self):
"""方便打印调试"""
return '<Node: value = {}, next = {}'.format(self.value, self.next)
__repr__ = __str__
class LinkedList(object):
"""单链表类"""
... |
84de1046a8fd6e65477e34f9379b0bb2dbeef60e | vishalnandanwar/Machine_Learnings | /src/LinearRegression/LinearRegrex.py | 1,993 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu May 30 12:11:04 2019
@author: vnandanw
"""
#import relevant libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#Read the data set from file
FlatData = pd.read_csv('Price.csv')
#Separate features and labels from the data set
X = FlatData.iloc[:... |
a964e061e01b251c191f8415578a862fd5309ae5 | xingzhong/leetcode-python | /36.py | 802 | 3.546875 | 4 | class Solution:
# @param board, a 9x9 2D array
# @return a boolean
def isValidSudoku(self, board):
def test(xs):
t = [False]*9
for x in xs:
if x == '.': continue
elif t[int(x)-1]:
return False
else:
... |
fe267cf7a025dfcd9c8ec382b4be9e679b562de7 | TinouWild/PythonBasique | /intermediaire/erreurs_debutant/get_list_variable.py | 239 | 3.578125 | 4 | liste = range(10)
index = 2
# premiere solution
try:
r = liste[index]
print(r)
except IndexError:
print("L'index {} n'existe pas.".format(index))
# deuxieme solution
r = liste[index] if len(liste) > index else None
print(r)
|
9a2d084f01c7a174ef2a9296337a957275103994 | HenDGS/Aprendendo-Python | /python/Exercicios/4.11.py | 288 | 3.859375 | 4 | pizzas=["Calabresa","Quatro-queijos","pepperoni"]
pizzas_do_amigo=pizzas[0:3]
pizzas.append("portuguesa")
pizzas_do_amigo.append("havaiana")
"""for pizza in pizzas:
print("Gosto de pizza " + pizza)"""
print(pizzas)
print(pizzas_do_amigo)
#print ("\nEu realmente gosto de pizza")
|
70fbaa1c4f067357bd27bae4421ce8b4c2a17c79 | cankutergen/hackerrank | /Missing_Numbers.py | 521 | 3.546875 | 4 | def missingNumbers(arr, brr):
dict_a = {}
dict_b = {}
missing = []
for i in arr:
if i not in dict_a:
dict_a[i] = 1
else:
dict_a[i] += 1
for i in brr:
if i not in dict_b:
dict_b[i] = 1
else:
dict_b[i] += 1
for key... |
97c919d1535403fcba1a543ebb6668f326360968 | sleonardoaugusto/vrum | /core/carro.py | 739 | 3.609375 | 4 | import unittest
from core.direcao import Direcao, Direcoes
from core.motor import Motor
class Carro:
def __init__(self, motor, direcao):
self.motor = motor
self.direcao = direcao
def calcular_velocidade(self):
return self.motor.velocidade
def acelerar(self):
self.motor.ac... |
29e4931cdd6563aa0bb3fbc4211709f6ecdfff65 | m21082/Practice-Work-Apps | /find job material.py | 606 | 3.6875 | 4 | # Find all instances of job name and show what material was ordered and on which date
# Info from CSV populated by material order script
import csv
import os
import sys
import time
from pathlib import Path
from time import gmtime, strftime
job = input (" Enter job name/ref: ")
for file_name in os.listdir... |
c5e08310d57c902cf16efe142f75ceeb928dbae4 | pdhhiep/Computation_using_Python | /r8lib/r8_modp.py | 2,753 | 3.828125 | 4 | #!/usr/bin/env python
def r8_modp ( x, y ):
#*****************************************************************************80
#
## R8_MODP returns the nonnegative remainder of real division.
#
# Discussion:
#
# If
# REM = R8_MODP ( X, Y )
# RMULT = ( X - REM ) / Y
# then
# X = Y * RMULT + REM
# ... |
9a3e11dc97fe7f27a121011d107db72b300f6bd1 | santiago0072002/Python_stuff | /noneexplanationexamples.py | 1,074 | 4.03125 | 4 | # None is the return value of of functions without a return value
# None is an Object, a constant and a singleton.
# Singleton is a creational design pattern, which ensures that only one object of its kind exists and provides a single point of access to it for any other code.
# Singleton has almost the same pros a... |
58c01a4bc6e2c5bce0a25b828ae2d02dd7cca003 | lysevi/concret | /tools/dump2csv.py | 769 | 3.53125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Преобразует дамп к следующему виду:
# сренее значание фитнесса ; номер популяции
import sys
if(len(sys.argv)!=3):
print "usage:\n\t",sys.argv[0],"path_to_source_file dot_count"
sys.exit()
src=file(sys.argv[1])
lines=src.readlines()
cnt=int(sys.argv[2])
pos... |
5c2bbd692883e36a6faab74212abc82e15ea27d2 | RonanD10/Hypergraphs-and-Orthoalgebras | /ps_hasse.py | 1,313 | 3.546875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[3]:
def powerset(s):
PS = []
x = len(s)
for i in range(1 << x):
PS.append([s[j] for j in range(x) if (i & (1 << j))])
PS = sorted(PS, key=len)
for i in range(1,len(s)+1):
PS[i] = i
return PS
print(powerset([1,2,3]))
# In[2]:
from... |
54e27aaec173110fb4d831f5d90b45be9a507f6d | salvador-dali/algorithms_math | /training/05_geometry/07_stars.py | 1,186 | 3.59375 | 4 | # https://www.hackerrank.com/challenges/stars
# for every possible 2 points check the sum of the weights above and below the the line
# (not taking into the account these two points). Then also try different combinations with these
# points it can be 2 points above the line, 2 points below the line, 1 point above, one ... |
0429fe5047f46d2bf97a5cf30079075dcb5c8027 | projetosparalelos/The-Complete-Python-Course-including-Django-Web-Framework | /Python 201/executable_user_files.py | 324 | 4.03125 | 4 | filename = input("What is the filename? ")
content = input("Enter the content: ")
with open(filename, 'w') as file:
file.write(content)
open_file = input("Would you like to read this file? ")
if open_file in ['y', 'n']:
if open_file == 'y':
with open(filename, 'r') as file:
print(file.read... |
95f70691313da9a209a54f60b430d9c77fe0a483 | nirorman/FifteenPuzzle | /printer.py | 2,158 | 3.84375 | 4 | import texttable as tt
class Printer(object):
@staticmethod
def print_board(board):
tab = tt.Texttable()
tab.add_rows(board, header=False)
tab.set_cols_align(['c', 'c', 'c', 'c'])
print tab.draw()
@staticmethod
def print_illegal_move():
print("Sorry, that move ... |
bf71a77c724973143d6b33b4da92bad30844b01c | voidGlitch/Python-Development | /Day3/odd_even.py | 129 | 4.28125 | 4 | num = int(input("enter any number to check whether its odd or even\n"))
if(num % 2 ==0):
print("even")
else:
print("odd") |
057aeb07b23573e0a25a83ccf5ff549542623d79 | GabePZ/538-Riddler-Solutions | /2020-02-21/riddler_express.py | 438 | 3.875 | 4 | def fahrenheit_to_celsius(temp: int) -> int:
return int(round(((temp - 32) * 5)/9))
def same_backwards(fahrenheit_temp: int) -> None:
celsius_temp = fahrenheit_to_celsius(fahrenheit_temp)
if ''.join(reversed(str(celsius_temp))) == str(fahrenheit_temp):
print(f'F: {fahrenheit_temp}, C: {celsius_temp... |
898bd2b2fbc96b6b65e79a44a4b1557fd806170a | dtu-02819-projects-fall2014/02819 | /topicmining.py | 7,362 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Topic Mining of Wikipedia literature using LDA method.
"""
from gensim import corpora, models
#from itertools import chain, izip_longest
#from urllib import urlopen
from operator import itemgetter
#import mongo_db
import csv
import numpy as np
from matplotlib import pyplot as plt
#from matpl... |
f3cf38c25203fc92a5f71331877874f00c18bb94 | CoachMac78/user-signup | /test.py | 307 | 3.609375 | 4 |
def character_check(email):
total_at = 0
email = "amac78@gmail.com"
for char in email:
if char == "@":
total_at += 1
return total_at
#if total_at > 1 or total_at < 1:
# error = "Too many @'s. Not a valid email. Please try again."
character_check("amac78@gmail.... |
52cd8b4c1ec31bd7cd2d109600ad03fcda56690e | Beishenalievv/python-week-sets_2020 | /6/L6-Problem-1: The largest element.py | 119 | 3.5 | 4 | a = input()
b = a.split(",")
list1 = [int(x) for x in b]
list1.sort()
max = len(list1)
max -= 1
print(list1[max])
|
7666d7a271fa60d657ba8c58cbff456788428bea | becdot/pydata-structures | /data_structures.py | 20,039 | 3.953125 | 4 | import random
import math
class Stack(object):
"""First-in, last-out data structure.
Elements can be pushed onto or popped off the stack; can also peek at the top element."""
# error handling?
# implementation with a linked list?
def __init__(self, array):
self.stack = array
d... |
fc5937e580fba89376ce9f6dc4cc2fdfc1a74e6c | xopapop/thermohome | /classes.py | 739 | 3.859375 | 4 | from datetime import datetime
class weather():
def __init__(self, weather_dict):
self.dt = ''
self.temp_k = float()
self.rh = int()
self.description = ''
self.wind_speed = float()
self.wind_angle = float()
# save everything in the weather dict as an attribute... |
0cdbc1c9d038a42c71c65aaf7598e2ca28c99723 | humachine/AlgoLearning | /leetcode/Done/301_RemoveInvalidParentheses.py | 5,427 | 4.09375 | 4 | #https://leetcode.com/problems/remove-invalid-parentheses/
'''
Given a string, remove the minimal number of parentheses required to make the string valid again.
Inp: "()())()"
Out: ["()()()", "(())()"]
Inp: "(a)())()"
Out: ["(a)()()", "(a())()"]
Inp: ")("
Out: [""]
'''
class Solution(object):... |
c7b9860819ad092e57f9e1fed7e668bfc2b6559a | melijov/course_python_essential_training | /string-functions.py | 1,073 | 4.09375 | 4 | def main():
string_functions()
class kitten:
def __init__(self, n):
self._n = n
class bunny:
def __init__(self, n):
self._n = n
def __repr__(self):
return f'repr: the number of bunnies is {self._n}'
def __str__(self):
return f'str: the number of bunnies is {self._n}'... |
450953fcb856801906964cfa573a4f46d2166443 | sgalban/geoquiz | /db_files/country_code_dict.py | 284 | 3.609375 | 4 | import json
from pprint import pprint
data = json.load(open('all.json'))
code_dict = {}
for i in range(len(data)):
code = data[i]["Code"]
name = data[i]["Government"]["Country name"]["conventional short form"]["text"]
code_dict[name] = code
## Example
print(code_dict["Syria"]) |
5bc7e5bd89df06932027f0e237dacac34d221f71 | hanshuo11/my_python | /test/test13.py | 535 | 3.890625 | 4 | #!/user/bin/env python
# -*- coding: utf-8 -*-
# Author:HanShuo
# class Student(object):
# def set_age(self,age):
# self.age=age
# # s=Student()
# # s.set_age(26)
# # print(s.age)
# def set_name(self,name):
# self.name=name
# # 增加set_name函数
# Student.set_name=set_name
#
# s=Student()
# s.set_name("hans... |
ff92463389ba25d5aa6a0df5f4ca6d3a398c94d7 | abhishekthukaram/Course-python | /Recursion/stringreverse.py | 803 | 4.46875 | 4 | """
Reverse a string using recursion
"""
def reverse_string(input):
"""
Return reversed input string
Examples:
reverse_string("abc") returns "cba"
Args:
input(str): string to be reversed
Returns:
a string that is the reverse of input
"""
if input=="":
return in... |
002cb6f70b2343b7a10e3064c21c43b045517f22 | parkerjacks/python-103-small.py | /square2.py | 322 | 4.09375 | 4 | #Create a square of astericks made up of a NxN characters decided by user
#Set it Up
square_length = int(input("Enter a number for the length of your square: "))
square_is_made_of = '*'
count = 0
#Work it Out
while count < square_length:
print (square_is_made_of * square_length)
count = count + 1
#Finis... |
07972b377c0895f67b2d51d3d6f6f1e598ad31e2 | lukexyz/Hadoop-MapReduce | /friends-by-age.py | 704 | 3.625 | 4 | from mrjob.job import MRJob
class MRFriendsByAge(MRJob):
""" MapReduce to find average number of friends by age"""
def mapper(self, _, line):
# break datafile in separate fields
(ID, name, age, numFriends) = line.split(',')
yield age, float(numFriends)
def reducer(self, age, numF... |
f96755033703b349f5ea60530fceda85da27e139 | babuhacker/python_toturial | /hackerrank_last_15/Detect Floating Point Number.py | 135 | 3.546875 | 4 | import re
n = int(input())
pattern = r'^[+-]?[0-9]*\.[0-9]+$'
for i in range(n):
s = input()
print(bool(re.match(pattern, s)))
|
9e26b413223f30d2cb4b67c6f106fb9b054f17d4 | shivambhilarkar/Codevita-Solutions | /coindistribution.py | 2,319 | 4 | 4 | # Problem Statement
# Find the minimum number of coins required to form any value between 1 to N,both inclusive.Cumulative value of coins should not exceed N. Coin denominations are 1 Rupee, 2 Rupee and 5 Rupee.Let’s Understand the problem using the following example. Consider the value of N is 13, then the minimum num... |
98c0bf837ca7d21c988471f6334e4012ff0ffe32 | Ameema-Arif/Scientific-Calculator-using-Python | /Sub.py | 133 | 3.671875 | 4 |
def sub():
A=float(input("1st Value:"))
B=float(input("2nd Value:"))
C=A-B
print(C)
|
7bd9931f8bf36865ed1001dd46e232a74637bbd7 | carrickdb/CodingPractice | /partition_array.py | 1,356 | 3.890625 | 4 | def partition_array(nums):
greatest_left = nums[0]
greatest_right = -1
left_size = -1
for i in range(1, len(nums)):
if greatest_left <= nums[i]:
if left_size < 0:
left_size = i
if greatest_right <= nums[i]:
greatest_right = nums[i]
... |
8db24652f3a1561504649d8154cefb3c4ab94e76 | Anjitha-Sivadas/luminarpythonprograms | /Advance python/EXAM.py | 5,077 | 4.5625 | 5 | # 1 create a child class bus that will inherit
# all of the variables and methods of vehicle class
"""
class Vehicle:
bus_name=""
def no_of_veh(self):
print("one")
class Color:
veh_color=""
def clr(self):
print("color of vehicle:",self.veh_color)
class Bus(Vehicle,Color):
def ... |
00762117dca0fc0bfdbebdf61a7ebc1c42734ecb | shekher1997/Wipro-PBL | /dict.py | 890 | 3.5625 | 4 | # Hands-on Assignment 1
dict1 = {1:'A', 2:'B'}
dict1[3] = 'C'
print(dict1)
print(end="\n")
# Hands-on Assignment 2
dictA = {1:10, 2:20}
dictB = {3:30, 4:40}
dictC = {4:40, 5:50, 6:60}
for keys in dictB:
dictA[keys] = dictB[keys]
for keys in dictC:
dictA[keys] = dictC[keys]
print(dictA)
print(end="\n")
# ... |
da0e0aaea16bfe1f28fb3312a7a0685ad8877cfa | litvinchuck/python-workout | /algorithms/binary_search.py | 1,311 | 4.25 | 4 | """Binary search implementation. Expected performance O(lg(n))"""
def search(array, element):
""" Searches array for an element and returns its index
Args:
array: searched array
element: element to search for
Returns:
int: element index if element is found, -1 otherwise
"""
... |
b141a1d420edda7050204f0eab963e84bd56b369 | tomki1/file-transfer-system | /ftclient.py | 11,902 | 3.75 | 4 | # Author: Kimberly Tom
# Project 2: File Transfer System
# Description: client side code written in Python. This program can request to get a listing from a server's directory or obtain a file from the server's directory.
# This program uses TCP connection to transfer data.
# CS372 Intro To Computer Networks
# La... |
cdc450b1db7c8b7a8e7e35f5e676ea0e4b0be3a4 | gonzalejandro/CC3501 | /Tarea2/characters.py | 3,156 | 3.859375 | 4 |
class Characters:
def __init__(self):
"""
Initializes different class parameters, to be added using the methods
above. Is important to add the different characters in the correct
order, because there are some characters whose initialization depends
on other characters.
... |
1e585bbde1018c005147476b64a0465ad44592ff | TomasCespedes/Artificial_Intelligence | /LightsOutPuzzle/agents/human.py | 913 | 3.5625 | 4 | from LightsOutPuzzle.utils.framework import Player
# Class for the human player
class HumanPlayer(Player):
# Don't need any properties for the Human player
def __init__(self):
pass
# Define the move the player makes
def move(self, game):
"""
This is the human agent. No algori... |
bdb615689dc6cdd39a035fa04b8c54a8dfe6fef9 | Barbuseries/Gestionnaire-de-mots-de-passe | /generation/GenerateurMdp.py | 12,302 | 3.984375 | 4 | # coding: utf-8
import argparse
from random import SystemRandom
import math
import sys
import getpass
# We set a new random system
cryptogen = SystemRandom()
"""
Usage :
newDico() will create a dictionnary of dictionnarys of lists of strings (pretty simple isn't it ? But it is necessary and efficient). Where word... |
477d7a89e499fe95cdb7c4c44894d5ce64b9e55b | htl1126/leetcode | /23.py | 1,143 | 4 | 4 | # ref: https://leetcode.com/discuss/55662/108ms-python-solution-with
# -heapq-and-avoid-changing-heap-size
import heapq
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
# NOTE: this code must be run with Python not Pytho... |
ce2d9a1d82a7af4e6bb25e905d1b008f4a186f36 | igorsobreira/playground | /problems/project_euler/13.py | 231 | 3.515625 | 4 | '''
Work out the first ten digits of the sum of the following one-hundred 50-digit
numbers. (numbers are in 13.in)
'''
with file('13.in') as file_obj:
s = sum( [ int(n) for n in file_obj.readlines() ] )
print str(s)[:10]
|
3ec20c584f97b13cbdae333c154651d1efa56e4c | eli-taylor/Challenge04 | /EliTaylor/CodeChallenge4.py | 4,022 | 4.21875 | 4 | ## Eli's Code Challenge 4 Submission
#- Run script using python 3.*
#- Enter a math expression that uses valid operators +, -, /, *, (, and )
import re
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.i... |
783b71484208447c0d914d9dbf616374ef4b140c | CScorpio/lxc_Project | /webdriver/unittest/assertFunction.py | 608 | 3.796875 | 4 | import unittest
class Test(unittest.TestCase):
def setUp(self):
number=input("Enter a number:")
self.number = int(number)
def testCase(self):
self.assertEqual(self.number, 10, "输入的数字不是10")
'''
try :
self.assertEqual(self.number,10,"输入的数字不是10")
excep... |
d7f94a3c06e7f728e7b9561de25a856cf4f6ef41 | MohamedMuzzamil05/Pysim- | /getcmnt.py | 2,969 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""Parse Python source code from file and get/print source code comments."""
__all__ = ('get_comments', 'get_comment_blocks')
import tokenize
from io import StringIO
def get_comments(source):
"""Parse Python source and yield comment tokens in the order of
appearance.
... |
2f4247305582297ad2ef852757ffa9536aa46ee4 | karthik-balaguru/MyPy | /prob6.py | 485 | 4 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Apr 1 02:31:12 2017
@author: bala635
"""
def sumofsquares(num):
n = 1
sum1 = 0
while (n<=num):
sum1 = sum1 + n**2
n = n+1
return(sum1)
def squareofsum(num):
n = 1
sum2 = 0
while (n<=num):
sum2 = sum2 + n
n = n... |
858e4ad3cef25ba09a26e277a28d54dbe55071ff | hudefeng719/uband-python-s1 | /homeworks/A10518/checkin02/A10518-day6-homework.py | 1,465 | 4.125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# @author: Fanyujie
# 今日的作业
# 有十种菜
# 白菜、萝卜、西红柿、甲鱼、龙虾、生姜、白芍、西柚、牛肉、水饺
#
# 1. 老妈来到了菜市场,从下标 0 开始买菜,遇到偶数的下标就买
# 遇到奇数的下标就不买,买的数量为下标 + 1 斤
# (请写程序模拟整个过程)
# (注意单一职责原则)
# (注意灵活使用 def 函数(代码块))
#
# 【提示】:
# 输出结果可能为
# ‘老妈来到菜市场
# 老妈看到白菜,买了 1 斤
# 老妈继续逛
# 老妈看到x... |
c548dfdd9fea1329909de926c700e96184c490b7 | kuraisle/ABCG_Family_Analysis | /logo_functions.py | 4,430 | 3.578125 | 4 | # The functions for generating protein sequence logos summarising the sequence alignment
# protein_logo draws the sequence logo
# conserved_colours generates colours for the sequence logo
def protein_logo(positions):
"""Draws a sequence logo of the positions requested showing differences between ABCG family members
... |
768fc2170ed8cfb8133e902e955438fb09284676 | shorya361/CP-Codes-DSA | /multithreading.py | 718 | 3.875 | 4 | #PF-Tryout
from threading import Thread
def func1():
result_sum=0
for i in range(10000001):#Write the code to find the sum of numbers from 1 to 10000000
result_sum+=i
print("Sum from func1:",result_sum)
def func2():
result_sum=0
for i in range(5):
p=int(input())
result_sum+=... |
4b9cd9337efa808041791b6b71397ffa6818a45d | splattater/mypythonstuff | /mypythonstuff/myos.py | 335 | 3.515625 | 4 | def get_abs_files(dir_path):
"""Search all files in a given dir and its subdirs."""
import os
if not os.path.isdir(dir_path):
return []
found = []
for root, subdirs, files in os.walk(dir_path, topdown=True):
for file in files:
found.append(os.path.join(root, file))
... |
a6ca48fa6d250c46fc69b9f1864d8e200485fb47 | gunveen-bindra/OOP | /overriding.py | 393 | 4 | 4 | # Method overriding
class employee:
def add(self, salary, incentive):
print('total salary in base class=', salary+incentive)
class department(employee):
temp = 'i m member of dept cls'
def add(self, salary, incentive):
print(self.temp)
print('total salary in derived... |
46dc064a1e708ccda5e29c3e8ad7e13d25236de4 | ConorODonovan/online-courses | /Udemy/Python/Data Structures and Algorithms/LinkedList/class_SingleLinkedList.py | 8,876 | 3.96875 | 4 | class SingleLinkedList:
def __init__(self):
self.start = None
def display_list(self):
if self.start is None:
print("List is empty")
return
else:
print("List is: ")
p = self.start
while p is not None:
... |
4e460b51d9b3d13ecc061600274d3dc5e508346d | RAFAELSPAULA/Exercicios-introdutorio-Python | /Estrutura condicional/Problema_troco_verificado.py | 841 | 4.21875 | 4 | # Fazer um programa para calcular o troco no processo de pagamento de um produto de uma mercearia.
# O programa deve ler o preço unitário do produto, a quantidade de unidades compradas deste produto,
# e o valor em dinheiro dado pelo cliente. Seu programa deve mostrar o valor do troco a ser devolvido
# ao cliente. S... |
da4458be1878bc3fe86bcd014a8c30ed6b3316a7 | junaid238/class_files | /python files/vehicle.py | 1,130 | 4.0625 | 4 | # car speed classifier
class car:
speed = 0
def __init__(self , name , wheels , bhp):
self.name = name
self.wheels = wheels
self.bhp = bhp
print("your " + self.name +" is of "+ self.bhp)
def start(self , start_speed):
# speed = 0
car.speed = car.speed + start_speed
print("your " + self.name +" has st... |
b83098ba67e9b906818d5bb625a4bff62f3e811a | Matteo-lu/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/12-fizzbuzz.py | 469 | 3.953125 | 4 | #!/usr/bin/python3
def fizzbuzz():
"""prints the numbers from 1 to 100 separated by a space"""
for i in range(1, 101):
if (i % 15) == 0:
print("FizzBuzz ", end="")
continue
elif (i % 5) == 0:
print("Buzz ", end="")
continue
elif (i % 3) == ... |
eb3d0cc3a414b0ad8a61b3036475de3723d2e93e | ekhtiar/Python_for_Informatics_Solutions | /Ex_2/Ex_2_2.py | 274 | 3.71875 | 4 | #!/usr/bin/env python
#adjust your shebang line
#Excercise 2.2: Write a program that uses raw_input to prompt a user for their name and then welcomes them.
#take input and store in name variable
name = raw_input("What is your name? \n");
#print name
print("Hello " +name);
|
1d50daa6110cc9553e82232d2fc74e449af86b60 | yangwenwei666/zero | /apps/getMovie/__init__.py | 187 | 3.59375 | 4 | import re
text = "◎片 名 狄仁杰之四大天王/狄仁杰3◎"
a = re.compile(r'[◎](.*?)[◎]',re.S)
result = a.findall(text)
for x in result:
print(x)
print(result)
|
f13cfec666bb5aa96d9361fecd679deac8981b16 | clarkmyfancy/Visual-Sorter | /ListGenerator.py | 354 | 3.71875 | 4 | import random
class Generator:
def __init__(self, maxLength, largestValue):
self.maxLength = maxLength
self.largestValue = largestValue
def generate_random_list(self):
random_list = []
for _ in range(self.maxLength):
random_list.append(random.randint(0, self.largest... |
0b6fb5d2f72a47c1878e744f311245c88e02ebf0 | paniquex/ML_DS_practice | /PRACTICUM/HW_02/get_max_before_zero.py | 332 | 3.65625 | 4 | import numpy as np
def get_max_before_zero(x):
zero_positions = np.where(x == 0)[0]
if (len(zero_positions) == 0) | (zero_positions[0] == (len(x) - 1)):
return None
else:
if (len(x) - 1) == zero_positions[-1]:
zero_positions = zero_positions[:-1]
return np.max(x[zero_po... |
072d50e7f41d002ee657c2554eed353c41845899 | realm10890/LearningOpenCV | /ImgArithmeticAndLogic/imgArithmeticAndLogic.py | 2,332 | 3.671875 | 4 | import cv2
import numpy as np
import matplotlib.pyplot as plt
img1 = cv2.imread('3D-Matplotlib.png')
img2 = cv2.imread('mainsvmimage.png')
img3 = cv2.imread('mainlogo.png')
#Simple Addition of Both Images(not really ideal)
simpleAddition = img1 + img2
cv2.imshow('Simple Addition', simpleAddition)
cv2.waitKey(0)
cv... |
4cad335320a6973ce430bd12ed04034a87cf061d | mjohnkennykumar/csipythonprograms | /basic/listmethods.py | 614 | 4.15625 | 4 | # -*- coding: utf-8 -*-
# vowel list
vowel = ['a', 'e', 'i', 'u']
# inserting element to list at 4th position
vowel.insert(3, 'o')
print('Updated List: ', vowel)
# animal list
animal = ['cat', 'dog', 'rabbit', 'guinea pig']
# 'rabbit' element is removed
animal.remove('rabbit')
#Updated Animal List
print('Updated a... |
92f704d5dd65e5020a266857aeed9e2246e1f7d0 | lindonilsonmaciel/Curso_Python | /Python_Mundo01/desafios/desafio054.py | 501 | 3.953125 | 4 | """Crie um programa que leia o ano de nascimento de sete pessoas.
No final, mostre quantas pessoas ainda não atingiram a maioridade e
quantas já são maiores."""
from datetime import date
ano = 0
atual = date.today().year - 18
maior = 0
menor = 0
for i in range(0,7):
ano = int(input('Digite o ano de nascimento da {}... |
33de6018477d592b7bdddecd9e15783b03b06eee | harrychy8/pig-latin-translator | /jack-ver.py | 587 | 3.546875 | 4 | def piglatintranslate(s):
s = s.split(); ns = ""
for w in s:
i = 0; sf = "yay";p = ""; a = False
if not w.isalpha(): ns += w + " "; a = True
if not w[len(w) - 1].isalpha(): p = w[len(w) - 1]; w = w[:len(w) - 1]
for c in w:
if c in "aeiouAEIOU":
if w[0]... |
243f8dde0b88dbf2490b2c2185363844be10cff3 | zjn0810/pythonL | /algorithm/SortAndSearch/selectSort/selectSort.py | 543 | 3.921875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 7 08:59:13 2021
@author: zhangjn
"""
def selectSort(items):
for fillslot in range(len(items)-1, 0, -1):
posepoint = 0
for location in range(1, fillslot + 1):
if items[location] > items[posepoint]:
p... |
86d6b537f52cc01858e088c68365665e554e61f4 | khdouglass/algorithms | /condensing_sentences.py | 397 | 4.09375 | 4 | def condense_sentences(sentence):
"""Combine words in a sentence if the last letter
matches the next word's first letter.
"""
word_list = sentence.split()
for i in range(len(word_list) - 1):
if word_list[i][-1] == word_list[i + 1][0]:
word_list[i] = str(word_list[i] + word_lis... |
d15682c092fd3fa6c3773b0bfff23445bee248bf | thomasbshop/pytutor | /DateNTime/pytz_usage.py | 941 | 3.765625 | 4 | import datetime
import pytz
country = 'US/Eastern'
tz_to_display = pytz.timezone(country)
local_time = datetime.datetime.now(tz=tz_to_display)
print("The time in {0} is {1}".format(country, local_time))
print("UTC is {0}".format(datetime.datetime.utcnow()))
# for x in sorted(pytz.all_timezones_set):
# print(x)
#... |
b8e2d70b8bc57d2dd16e223619f2dfd1aaad7f9f | Lucas-ns/Python-3-Curso-Em-Video | /PythonExercicios/ex088.py | 603 | 3.625 | 4 | from random import randint
from time import sleep
print('-' * 20)
print('JOGA NA MEGA SENA')
print('-' * 20)
jogos = int(input('Quantos jogos você quer que eu sorteie? '))
print()
print('-=' * 5, f'SORTEANDO {jogos} JOGOS', '=-' * 5)
print()
sorteados = []
lista = []
for j in range(1, jogos+1):
while len(lista) !=... |
b07e57af9c760944c49558b421528400d05e7148 | VictorHeDev/ATBS | /fiveTimes.py | 203 | 3.9375 | 4 | # for loop
print('My name is')
for i in range(5): # index starting from 0
print('Jimmy Five Times('+str(i)+')')
# while loop
print('My name is:')
i = 0
while i < 5:
print('Jimmy Five Times ('+str(i)+')')
i += 1 |
29b4c3c457a55660d571e402a8d9b60ad1c250c8 | TTKSilence/Educative | /GrokkingTheCodeInterview-PatternsForCodingQuestions/11.PatternModifiedBinarySearch/6.SearchInASortedInfiniteArray(med).py | 996 | 3.96875 | 4 | #Given an infinite sorted array (or an array with unknow size),
#find if a given number 'key' is present in the array.
#Write a function to return the index of the 'key' if it is present in the array, otherwise return -1.
def Search(array,key):
if array[0]>key:
return -1
start,end=0,1
size=2
whi... |
50a88a67fffff3c5a46a6533347c3630638e606a | Thandiwe-Khalaki/ZuriTeam | /AutomatedTellerMachine.py | 1,406 | 3.921875 | 4 | import datetime
now = datetime.datetime.now()
print ("Current date and time : ")
print (now.strftime("%Y-%m-%d %H:%M:%S"))
print("WELCOME TO ABC ATM MACHINE")
print("PLEASE CHOOSE THE FOLLOWING OPTIONS")
print("\n1 - Withdraw \t 2 - Deposit \t 3 - Complain \t 4 - Exit ")
selection = int(input("\nEnter your selectio... |
8d1e3fd745ca85f278a2765617c4ea3c7aab1a90 | mxu007/leetcode | /191_Number_of_1_Bits.py | 1,148 | 3.9375 | 4 | # Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).
# Example 1:
# Input: 11
# Output: 3
# Explanation: Integer 11 has binary representation 00000000000000000000000000001011
# Example 2:
# Input: 128
# Output: 1
# Explanation: Integer 128 ha... |
0ff460ee013d9557a2a216ee8cef6b4fff939239 | gop50k/Python3 | /src/c3/func-animal-speed.py | 1,230 | 3.9375 | 4 | # coding: UTF-8
# 動物の最高時速を辞書型で定義
animal_speed_dict = {
'チーター': 110, 'トナカイ': 80,
'シマウマ': 60, 'ライオン': 58,
'キリン ': 50, 'ラクダ ': 30,
'新幹線 ': 300, '飛行機 ': 1000,
}
# 東京から各都市への距離を辞書型で定義
distance_dict = {
'静岡': 183.7,
'名古屋': 350.6,
'大阪': 507.5,
'福岡': 1000,
}
# 時間を計算する関数
def calc_time(dist, ... |
f99281f898f92a757e040fa27972beb2f79fbe1b | branko-malaver-vojvodic/Python | /recurs_duplicate_elem.py | 209 | 3.734375 | 4 | #Recurssivity to have a list with all the original elements duplicated
def recDup(lst):
if lst == []:
return lst
else:
A = lst[0:1]
B = lst[1:]
return (A*2) + recDup(B)
|
e488f8d8c495f446d7486e5f39098802ad13bc42 | Dr-Ex/Cowbell | /Frontend/cloud_save.py | 5,217 | 4 | 4 | """
Created on Fri Jul 28 11:22:34 2017
@author: Lysenthia and dr-ex
"""
import sqlite3
class DropTablesError(Exception):
""" Somebody tried to drop tables us """
def create_database(db, cursor):
""" Creates the initial database """
cursor.execute('''CREATE TABLE users(
ID INTEGER PRIMARY KEY A... |
b0f45dcfa2ac2dbef3f3708902da28b908e6be27 | ravi4all/PythonWeekendFeb | /07-GameDevelopment/03-FramesPerSecond.py | 1,203 | 3.53125 | 4 | import pygame
pygame.init()
red = (255,0,0)
speed = [2,2]
width = 900
height = 500
screen = pygame.display.set_mode((width,height))
rect_x = 0
rect_y = 0
move_x = 10
move_y = 10
lead_x = 0
lead_y = 0
clock = pygame.time.Clock()
FPS = 30
game = False
while not game:
for e... |
76ef400dfebf36e0a872bea8779516add0fdb2ac | lucasportella/learning-python | /python-codes/m2_curso_em_video_estruturas_de_controle/ex058.2.py | 354 | 3.75 | 4 | from random import randint
computador = randint(0,10)
print('Pensei num número de 0 a 10. Adivinhe.')
acertou = False
palpites = 0
print(computador)
while acertou == False:
jogador = int(input('Qual é seu palpite? '))
palpites += 1
if jogador == computador:
acertou = True
print('Você acertou com {} ... |
b84e68fc6db423213365c6303df30f88e3b5b3c2 | Lucas-Urbano/Python-for-Everybody | /Definite_loops_with_strings.py | 154 | 3.828125 | 4 | #A DEFINITE LOOPS WITH STRINGS
for i in['Lucas Urbano', 'ama a Jesus Cristo', 'sua glória durará para todo sempre']:
print('#DEUS:', i)
print('Aleluia a Jesus') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.