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 |
|---|---|---|---|---|---|---|
e44d65ae78f334d92f7fbbeb3d792c820d8151e7 | Nidheesh-Mishra/AI | /AI_2.py | 498 | 3.75 | 4 | a=[]
b=[]
c=[]
n1 = int(input("Enter number of elements of first list : "))
print("Enter the Elements")
for i in range(0, n1):
element1 = int(input())
a.append(element1)
if(a[i]>0):
c.append(a[i])
n2 = int(input("Enter number of elements of second list : "))
print("Enter the Elements")
... |
b9c5c888f08b637ee212294b9d41be2c4309abea | jaysc/adventofcode2018 | /13/1.py | 2,969 | 3.75 | 4 | class Cart(object):
# up, right, down, left = 0,1,2,3
def __init__(self, x:int, y:int, direction:int):
self.x = x;
self.y = y;
self.d = direction;
self.nextIntersect = 1;
self.explode = False;
def move(self, grid:dict):
if self.d == 0:
self.y -= 1... |
f1d08014e3c7f0b095f689460323d807f7e3e60c | maomao-yt/paiza_date_set | /17_show_calendar.py | 1,772 | 3.640625 | 4 | y, m = map(int, input().split())
# 基準日
year, month, day = 1800, 1, 1
# 曜日は0,1,2,3,4,5,6で管理。0を日曜日とする
day_cnt = 3 # 基準日は水曜日
def is_leap(year):
if year % 400 == 0 or (year % 100 != 0 and year % 4 == 0):
return True
# 最終日を求める
def last_day(year, month):
if month == 2:
# 閏年かどうか
if is_leap... |
d9610828c3426a3e358ee664c18d89690489f63c | natolambert/ProjectEuler | /001_100/p004Palindromic.py | 651 | 4.25 | 4 | '''
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 * 99.
Find the largest palindrome made from the product of two 3-digit numbers.
'''
from itertools import combinations
def is_palindrome(n):
return str(n) == str(n)[::-1]
def larg... |
bdab8086f8efa5b8efaf7fe68e065d341b002c84 | oyesilpinar/Projects-for-Python | /ProjeDosylarım/Ahmetimla.py | 211 | 3.734375 | 4 | girdi=input("")
x=girdi.split(" ")
liste1=[]
liste2=[]
for i in x:
if(i[0].isupper()):
liste1.append(i)
else:
liste2.append(i)
liste3=liste1+liste2
for i in liste3:
print(i,end=" ")
|
b8b7a4b119d624f8f68dfe6741230645bc10ae12 | hellool/py-euler | /python/p25_1000_digit_Fib.py | 1,349 | 4.21875 | 4 | #1000-digit Fibonacci number
#
#Problem 25
#The Fibonacci sequence is defined by the recurrence relation:
#
#Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.
#Hence the first 12 terms will be:
#
#F1 = 1
#F2 = 1
#F3 = 2
#F4 = 3
#F5 = 5
#F6 = 8
#F7 = 13
#F8 = 21
#F9 = 34
#F10 = 55
#F11 = 89
#F12 = 144
#The 12th term, F12, i... |
c93f41a6f8837a17f048774083af95930f25370d | rhaeguard/algorithms-and-interview-questions-python | /search_algorithms/element_searching/binary_search.py | 808 | 3.875 | 4 | """
Binary search
"""
def binary(arr, searched):
low = 0
high = len(arr)
while low <= high:
mid = (high + low) // 2
if arr[mid] > searched:
high = mid-1
elif arr[mid] < searched:
low = mid+1
else:
return True
return False
# task is ... |
8ab2a9b663071fbacb8631e008dc9c033a263af6 | dufufeisdu/AI_Trading_Learn_Packages | /learn/Leecode_py/dynamic/least_cut.py | 836 | 3.546875 | 4 | # !!! least cut is not the max subarray cut
# for example:
# bbbbab max subarray cut=> bbbb_a_b is 2
# bbbbab least cut => bbb_bab is 1
# Solution(mine O(n!)):
def least_cut(s):
if len(s) < 2:
return 0
if s == s[::-1]:
return 0
min_cut = len(s)
for idx in range(1, len(s)):... |
54fd88947f244596a9bea285f0fe38cc3c029c71 | angelahyoon/LeetCodeSolutions | /firstUniqueCharInAString.py | 351 | 3.5625 | 4 | # First Unique Character in a String
def firstUniqChar(self, s: str) -> int:
# assume the string contains only lowercase letters
dict = {}
for i in s:
dict[i] = dict.get(i, 0) + 1
for i in range(len(s)):
if (dict[s[i]] == 1):
retu... |
e976b2b06fc1ab1492dcdca996e0cacb03f7ecd4 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/223/users/4479/codes/1646_2450.py | 147 | 4.03125 | 4 | n1 = input ("Digite o nome: ")
n2 = input ("Digite o outro nome: ")
if(n1.upper() < n2.upper()):
print(n1)
print(n2)
else:
print(n2)
print(n1) |
0fe55a15e534b865a6716c1f3617ac8a16088c9f | puentesarrin/pymongolab | /pymongolab/collection.py | 12,877 | 3.578125 | 4 | # -*- coding: utf-8 *-*
from bson.objectid import ObjectId
from collections import OrderedDict
from pymongolab import cursor, helpers
class Collection(object):
"""For instance this class, you needs an instance of
:class:`pymongolab.database.Database` and the name of your collection.
Example usage:
.... |
e560a80d6bbef6d243ae15bd8359e7004592bf6b | yWolfBR/Python-CursoEmVideo | /Mundo 3/Exercicios/Desafio089.py | 1,148 | 3.6875 | 4 | a = list()
temp = []
while True:
temp.append(str(input('Nome: ').strip().capitalize()))
temp.append(float(input('Nota 1: ')))
temp.append(float(input('Nota 2: ')))
a.append(temp[:])
temp.clear()
while True:
c = str(input('Quer continuar? [S/N]: ')).strip().upper()[0]
if c in 'SN'... |
5229d4acf9c5668bd777276633034fb13c3374af | obbijuan/python | /sets.py | 799 | 4.1875 | 4 | # Los sets solo permiten un conjunto de elementos unicos
# y los elementos repetidos son eliminados automaticamente.
# Los conjuntos son utiles cuando se requiere buscar puntos
# en comun entre los datos.
a = { 1, 2, 2, 3, 3, 4, 5, 6 }
print type(a)
print a
b = { 2, 3, 3, 6, 7}
print '-----------------------'
print ... |
15a95546b40f6881c08f6354f9bd3fe862fb87ed | Linda-Kirk/cp1404practicals | /prac_05/word_occurrences.py | 651 | 4 | 4 | """
CP1404/CP5632 Practical
Word Occurrences
"""
user_string = input('Text: ')
words = user_string.split()
print(words)
words_dictionary = {}
for word in words:
count_of_word = words_dictionary.get(word, 0)
if count_of_word is None:
words_dictionary[word] = 1
else:
words_dictionary[word] = ... |
3a2faf8e5de5ce4b7bcdeafb24fd8a80e3570a29 | eabrash/Emi-Programs | /Twitterstream.py | 2,237 | 3.5 | 4 | import oauth2 as oauth
import urllib2 as urllib
import time
# This code is VERY minimally modified by me from the template originally
# provided in Bill Howe's Coursera course on Data Science. You can find the
# original at: https://github.com/uwescience/datasci_course_materials.
# Also, this will not work as written... |
f852ca0085efef1e084588e7d303156963fcaf6f | b1ueskydragon/PythonGround | /graffiti/primes.py | 305 | 4.125 | 4 | def is_prime(num):
if num < 2 or (num is not 2 and num % 2 is 0):
return False
for _ in range(3, num, 2):
if num % _ is 0:
return False
else:
continue
return True
def primes(num):
return [i for i in reversed(range(num + 1)) if is_prime(i)] |
65bb5d7b69fc904627cf7bce50a6539c01af2993 | jacquelineawatts/learning_vid_roulette | /nodes.py | 1,679 | 3.578125 | 4 | class KATree(object):
"""Khan Academy API topic tree."""
def __init__(self, head):
self.head = head
def __repr__(self):
return "<TREE HEAD: {}>".format(self.head.slug)
class AbstractNode(object):
"""Inheritance class for methods used by Topic and Video node classes."""
def find_... |
671d30f39d6593a675a81f4a69ff21c6ae8b2515 | jarvis-1805/DSAwithPYTHON | /Trees/Binary Trees/Minimum_and_Maximum_in_the_Binary_Tree.py | 3,257 | 3.859375 | 4 | '''
Minimum and Maximum in the Binary Tree
For a given a Binary Tree of type integer, find and return the minimum and the maximum data values.
Return the output as an object of Pair class, which is already created.
Note:
All the node data will be unique and hence there will always exist a minimum and maximum node dat... |
c93e3d92ff46b0858926298d6d6676ca1a527118 | Octaith/euler | /euler098.py | 2,845 | 4.0625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
By replacing each of the letters in the word CARE with 1, 2, 9, and 6 respectively, we form a square number: 1296 = 36^2. What is remarkable is that, by using the same digital substitutions, the anagram, RACE, also forms a square number: 9216 = 96^2. We shall call CARE ... |
d898b522f09e5ea6fe9e538980ed93edda47ee2b | kdolic/IowaStateUniversity | /MIS 407 - Python Programming/IA05/ia05.py | 2,238 | 3.671875 | 4 | from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def home():
# Show the loan input form:
return render_template("loan-form.html")
@app.route('/compute', methods=['POST'])
def compute():
# For a POST request, request.form is a dictionary that contains the posted
... |
17f5eb89c60cc69933bf17e897758b594499d0f6 | AVogelsanger/Python | /PythonCode/TextAnalyzer.py | 634 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 8 15:09:13 2019
@author: 748418
"""
with open("Lutador.txt") as f:
texto = f.read()
print(texto)
print(list(texto))
class TextAnalyzer:
def count_str(self, texto, counter=0):
for txt in texto:
if txt.isalpha():
... |
bb20639b3a306e22346d8aa1d3cbc2c12a2c2e53 | marwanharuna/python_ex1 | /functionExample3.py | 552 | 4.03125 | 4 | #WAP to check factorian and prime number with seperate file.
import functions
print("**********FACTORIAL AND PRIME NUMBERS**********")
print("1.FACTORIAL \n 2.PRIME NUMBER")
option = int(input("Enter Option:"))
num = int(input("Enter Value To Check:"))
if option == 1:
result = functions.factorial(num)
pri... |
82aa604f1d09d69b8b145ebec365e4b14b40ca1d | VKSi/2019_10_GB_Course_Py_Essential | /les_4/les_4_task_4.py | 724 | 3.59375 | 4 | # Vasilii Sitdikov
# GeekBrains Courses. Python Essential
# Lesson 4 task 4
# October 2019
# task: 4) Представлен список чисел. Определить элементы списка, не имеющие повторений.
# Сформировать итоговый массив чисел, соответствующих требованию. Элементы вывести в
# порядке их следования в исходном списке.
... |
c42524b57cfc2c0167466456bca1347d04b4a7d0 | PeterSigurdson/Python | /August-3-2018-classwork/untitled-2.py | 240 | 4 | 4 | # keep track of intermediate results with an
# accumulator variable
product = 1
for i in range(1,11):
product = product * i
print("intermediate value is ", product)
print("final value is ". product)
|
f3075dedc10c68a6cf9b52012a5bed17144e2e80 | saisudheer123/sudheer3python | /saivowel.py | 214 | 3.96875 | 4 | inp=raw_input()
if(inp>='a' and inp<='z') or (inp>='A' and inp<='Z'):
if inp in ['a','e','i','o','u','A','E','I','O','U']:
print("Vowel")
else:
print("Consonant")
else:
print("invalid")
|
305506ef8e5aa3363323ac45a1bc5c9597e9dc46 | satelite54/BUSAN_IT_ACADEMY | /python/practice1_4.py | 206 | 3.734375 | 4 | a = float(input("물체의 무게를 입력하시오(킬로그램): "))
b = float(input("물체의 속도를 입력하시오(미터/초): "))
print(0.5 * a * b*b , "(줄)의 애너지를 가지고 있다.") |
2c82d1c47d3c999f6d619e9b81eb7f0aeac9c581 | nikhiltripathi1/Python-Programs | /Basics/phoneBook_query.py | 335 | 3.5 | 4 | #program to find contact in a phone
ph_book={}
qurrey=[]
n=int(input())
for i in range(n):
name=input()
name=name.split(' ')
ph_book[name[0]]=name[1]
try:
q=input()
qurrey.append(q)
except EOFError:
pass
for m in qurrey:
if m in ph_book:
print(m,"=",ph_book[m])
else:
prin... |
e20e49c5e4b2f9d5b0716f13633dbe0dc3fcde94 | FlorenceKim/PythonLearning | /if_예제.py | 763 | 3.703125 | 4 | money = 5000
card = False
if money >=4000 or card:
print(" Take Texi")
else:
print("you cannot take taxi")
a = [1,9,23,46]
if 23 in a:
print("당첨!")
else:
print("꽝")
num = 98
if num%2 == 0:
print("짝수")
else:
print("홀수")
a = "f,70"
b = "m,45"
mf, num = a.split(",")
isodd=int(num... |
eb66056a364e7abe5f625d7b8cd78030c93e86ec | SOFIAshyn/BaseProgramming_course_Basic_Python | /lab_3/imperative.py | 114 | 3.671875 | 4 | lst = [1, 2, 3, -1, -2]
new_lst = []
for el in lst:
if el % 2 ==0:
new_lst.append(el)
print(new_lst)
|
8659f0eb98bb2929cc6e5c181b6c0e748c4a56d3 | gcbsh/alibaba | /demo02.py | 2,350 | 3.546875 | 4 | #判断
# a = 1
# b = 2
# if a > b:
# print("a>b")
# else :
# print("b更大")
# age = int(input("请输入你的年龄:"))
# if age > 60:
# print("退休")
# elif age > 30:
# print("好好上班")
# elif age > 20:
# print ("找个好工作")
# else:
# print("好好读书")
# chengjilist = {}
# studentllist = ["张三","李四","麻五","赵六","田七","王八","皮九... |
bb76a4d641ec363680b448a35ef91a5619e775d4 | Roy789/matrix_multiplication- | /matrix_multiplication.py | 701 | 3.75 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 29 09:29:47 2018
@author: rishabhshetty
"""
import numpy as np
## Getting the size of theoutput matrix
def get_size(mat_1,mat_2):
multiplied_matrix = np.zeros((len(mat_1),len(mat_2[0])))
return(multiplied_matrix)
## Multip... |
ddce0aef6da51744603f90f60f4126d916a92b94 | andrewcampi/Maze-Pathfinding | /testmouse.py | 924 | 4.0625 | 4 | # Andrew Campi
# testmouse.py
# This file creates a maze object based on the user's inputs, then solves the maze and prints the solution.
from mousestack import Mouse
#from mouserecursion import Mouse
from maze import Maze
mouse = Mouse()
maze = Maze()
f_name = input( "Enter the name of the maze file (\"none\" if... |
2e810d07c683c96910537a115c937b8f2cd96656 | Rubenssio/HTI-2-Practical-1-Ruben-Petrosyan | /Final_Project/laptops.py | 9,544 | 4.15625 | 4 | import csv
import os
from classes import LaptopWithSpecs
def laptops(path_to_file):
"""Gets a path to a csv file and yields each line as a LaptopWithSpecs type.
Parameters
----------
path_to_file : str
The full path to the file.
Yields
------
LaptopWithSpecs
Next line fr... |
fbd63bb88618ced2cc7bb43b3818a6c8a7f5810a | Zhaeong/School | /CSC148/assignment 1/operand.py | 2,644 | 4 | 4 | class InvalidNumeralStringError(Exception):
'''Raise exception if Operand string does not conform to specifications.'''
pass
class Operand:
'''A string in the form of DDDDDDDDDbXX where every D represents a
digit, and XX represents the base of a positive integer up to and
including base 16. Digits... |
52dc5c0de66bab44fd4f7afb7850b5b4f6b8b318 | ng3rdstmadgke/CodeKata | /leap_year.py | 425 | 3.5625 | 4 | __author__ = 'midorikawa.keita'
import sys
# -*- coding: utf-8 -*-
def leap_year(n):
flg=False
if n%4==0:
flg=True
if n%100==0:
flg=False
if n%400==0:
flg=True
return flg
if __name__ == "__main__":
input_year=int(sys.stdin.readline())
if leap_year(input_year)==True... |
7bd4fab1bda32e27d7bf9c6d2b1bba9f31655150 | VictorXjoeY/Notebook | /Number Theory/euler_phi_pollard_rho.py | 2,603 | 3.53125 | 4 | from random import randint
from math import gcd
# O(N) - Returns the prime numbers up to n.
def linear_sieve(n):
# mp[i] stores the minimum prime number which divides i. i is prime if it's not 0 and mp[i] == i.
mp = [0 for i in range(n + 1)]
p = []
for i in range(2, n + 1):
if mp[i] == 0: # i is prime if we hav... |
d20ff1747e25fe1f35181d1e380782d59ac85368 | m-hollow/deeper_dungeons | /old_files (archive)/old_battle_potion_code.py | 3,302 | 3.71875 | 4 | def use_potion_battle(player, potion_mods):
"""player accesses potion inventory and uses one during a battle; adjusts HP or fight_mods accordingly"""
response = ''
current_max = len(player.elixirs)
active = True
while active:
clear_screen()
print('{}\'s ELIXIRS'.format(player.info['Name']))
print()
#... |
f75361b77478325b0fc7501709d419558885a225 | feiyu4581/Leetcode | /leetcode 1-50/leetcode_19.py | 1,279 | 3.859375 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
@classmethod
def generate_node(cls, vals):
root, current = None, None
for val in vals:
node = cls(val)
if not root:
root ... |
ffd081f23f66f417e88e3d291b905785be4ac25d | mikeiya/Card-generator-and-authenticator | /api/credit_auth/card_functions.py | 4,180 | 3.890625 | 4 | """
The different validation functions...
and a function for generating card numbers
a better card_iin and card_mii method would use
REGEX to match the start of the card_number
and find the matching key-value pair in mii_list and
nii_list respectively
generate_card funcion not fully tested or revised
"""
from random ... |
7c38204011e82ce31b55b354fcd6fdb366d15f62 | mepragati/Python-Assignment | /Day 6/Assignment 1.py | 126 | 4.09375 | 4 | List1 = [1,2,3,4,5,7,8]
List2 = ["a","b","c","d","e"]
print({List1[item] : index for item, index in enumerate(List2)})
|
669055dfb0de59ad5670a18ff72a8be2645900a6 | amandamurray2021/Programming-Semester-One | /labs/Week03/absolute.py | 246 | 3.984375 | 4 | # absolute.py
# Lab 3.2
# This program takes in a number and gives its absolute value
# Author: Amanda Murray
number = float (input ("enter a number:"))
absolutevalue = abs (number)
print ('the absolute value of {} is {}'.format(number, absolutevalue)) |
45157060912f03603691148a743d857b146abaa6 | pouspous2000/ProjetProgra | /Classe/classes.py | 21,910 | 3.75 | 4 | # -*- coding: utf-8 -*-
#Auteur : Cécile Bonnet - Clémentine Sacré
#bonjour clem
#test 2
import random
import json
from datetime import date
import csv
import os
def aleatoire(questions, nbr_questions):
"""
Renvoie x questions aléatoirement provenant de préférence d'un dictionnaire ou d'une
liste, où x ... |
464dce8e0a6d6818b5fb59fb64e2849d328b94cd | lakshmikantdeshpande/Python-Courses | /Python-Tutorial/strings_and_dictionary/strings.py | 545 | 4.09375 | 4 | sachin = 'hey there %s, how\'s your %s?'
verb = ('betty', 'foot')
print(sachin % verb) # like C i.e. printf("%d", marks)
print(sachin.find('there'))
temp = ['1', '2', '3']
dash = '-'
print(dash.join(temp))
print(sachin.upper())
print(sachin.lower())
print(sachin.capitalize())
print(sachin.replace('your', 'my'))
#... |
2f649df6c3a4459d3025fc99b9ec42f5c1f67f3d | sarthak-srivastava/k | /passwordlockerforwindows.py | 405 | 3.609375 | 4 | #! python3
password = {'#put your email address#':'#put your password#'}
import pyperclip,sys
if len(sys.argv)<2:
print('run the program again with email')
sys.exit()
account=sys.argv[1]
if account in password:
pyperclip.copy(password[account])
print('The password for '+account+' is copied to the clipbo... |
dada4c5dcb90bfe30aedcd4c7dc4687dec9e22d6 | jaisinha/Error-in-basic-pl-help | /Astrology star.py | 347 | 4.15625 | 4 | n=int(input("The number of columns and rows to be inputed"))
bool=input("Enter a true(1) or false(0)")
if(bool==0):
for i in range(1,n+1):
for j in range(1,i+1):
print("*",end=" ")
print()
else:
for i in range(n,0,-1):
for j in range(1,i+1):
... |
a0b0b4c5c549c61d8d7897c0e868a7acbf1afd25 | Ahsanhabib1080/CodeForces | /problems/B/HonestCoach.py | 792 | 3.59375 | 4 | __author__ = 'Devesh Bajpai'
'''
https://codeforces.com/problemset/problem/1360/B
Solution: Sort the numbers in strength list so that the neighbors are the numerically closest numbers. Now we need
to find the smallest difference of neighbors. One of that pair would be list A's max and other would be list B's min.
''... |
9635887c9e3a8d00d21d088a3c98d9382fd06423 | dheerosaur/leetcode-practice | /python/989.add-to-array-form-of-integer.py | 1,888 | 3.703125 | 4 | #
# @lc app=leetcode id=989 lang=python3
# [algorithms] - Easy
#
# [989] Add to Array-Form of Integer
# https://leetcode.com/problems/add-to-array-form-of-integer/description/
#
# For a non-negative integer X, the array-form of X is an array of its digits
# in left to right order. For example, if X = 1231, then the ar... |
1edf52c386f8670e8bbb0021c124c5ffc35995f8 | 4dHacker/SchachComputer | /Pawn.py | 521 | 3.5 | 4 | from Board import Figure
class Pawn(Figure):
def __repr__(self):
return "P" if self.white else "p"
def __init__(self, white):
Figure.__init__(self)
self.empty = False
self.white = white
def get_moves(self, board, x, y):
moves=[]
if board[y+1][x]==0:
... |
17937b1f5862db7e2e7994d42f892ea80c38fd0f | devqueue/live-stream | /functions.py | 377 | 3.5625 | 4 | # function with no arguments and no return
A =10
def sayhello():
print("hello")
# interest loans
def emi(principal, rate, time=10):
global rate1, time1
rate1 = rate/100
time1 = time*12
emi = principal*(1+rate1*time1)
return emi
# person 1 , 10000 at 3% 12 months
person_1 = emi(1000, 0.3... |
4573cab79288407b37f65d97fe86d14e3cb4bd83 | LetMeR00t/SA4BG | /python3/sixNimmt/game.py | 1,954 | 3.78125 | 4 | ## IMPORTS ##
from base.game import Game
from sixNimmt.equipments import SixNimmtEquipments
## CLASS ##
class SixNimmt(Game):
"""
Here, we define the class for the 6 Nimmt! game
"""
def __init__(self, name="6 Nimmt!", equipments=SixNimmtEquipments(), winConditions=[], history=None):
"""
Default constr... |
9bff5856c7dab511dd501849fdd3c334d2007671 | nullx5/Learning-the-Syntax-python | /ejemplo_excepciones_2.py | 310 | 3.5625 | 4 |
try:
a = 10
a = al + 1
print("El valor de a es:", a)
except NameError:
print("Error en el nombre de alguna variable")
except:
print("Error genérico")
else:
print("Bloque try ejecutado sin problemas")
finally:
print("Bloque finally ejecutado")
print("Seguimos con el programa") |
8d8c0123025ad3c3c2042183fa815658269736c4 | nanax/my_python_tests | /test4.py | 2,543 | 4.28125 | 4 | """Given two dates, calculate days between the dates.Assumes inputs are valid dates in Gregorian calendar. """
"""This is another solution to the Udacity Intro to Computer Science class lesson 2 problem set(optonal 2) problem 2(Days Old),included in lesson 2.5"""
def is_leap(year, month, day):
if year%4==0:
... |
02a7f53df414b6671baad93733a0bff4c64bdae3 | lord63/ascii_art | /examples/bar_example.py | 1,448 | 3.515625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from ascii_art import Bar
def example_one():
data = {
"cats": 6,
"ferrets": 15,
"dogs": 2,
"koalas": 0
}
b = Bar(data)
print(b.render())
def example_two():
data = {
"ferrets": 20,
"cats": 12,
"... |
d8604e9a9e1e48de146601ac919159a8b0fe1bb9 | leonardoFiedler/deep-learning-course | /breast cancer/breast_cancer_simples.py | 2,368 | 3.515625 | 4 | import pandas as pd
import keras
from keras.models import Sequential
from keras.layers import Dense #Denso significa que todos os neuronios estao interligados aos neuronios da proxima camada.
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix, accuracy_score
previsores = ... |
592527293b3adc57af6e45c3ea8fe20544c5f1d5 | TheMostKnown/Mozi_ciphres | /Simple_and_Afin_ciphers.py | 4,513 | 3.5625 | 4 | import math
def simple_encode(phrase, alphabet, key):
ans = ''
for i in range(len(phrase)):
if alphabet.find(phrase[i]) != -1:
ans += key[alphabet.find(phrase[i])]
else:
ans += phrase[i]
return ans
def simple_decode(phrase, alphabet, key):
ans = ''
for i i... |
2782b12caf90e559498ca95d30fe5f74eea600d1 | Addikins/CIS164 | /Unit9/Unit9Regex2.py | 317 | 3.53125 | 4 | import re
websitestring = "Cochise College has multiple websites to include http://www.cochise.edu and http://my.cochise.edu which are important to know!"
website_regex = re.compile(r'http://\w*.\w+.\w+')
website_found = website_regex.search(websitestring)
print("First website found: " + website_found.group())
|
26fca43051279e3ccce1a0759cdefdd0afbdb4f2 | anuragrana/Python-Scripts | /tweets_scrapper.py | 3,796 | 3.5 | 4 | # script to scrap tweets by a twitter user.
# Author - ThePythonDjango.Com
# dependencies - BeautifulSoup, requests
from bs4 import BeautifulSoup
import requests
import sys
import json
def usage():
msg = """
Please use the below command to use the script.
python script_name.py twitter_username
"""
... |
a25575463b7b959128f55dd6b93e3a08c0891b32 | sunilkumarmax/ArtificialIntelligence | /Week2/driver_3_alt.py | 17,969 | 4.125 | 4 | """
This is Week2 Project 1 Assignment for AI eDX course
"""
import copy
from math import sqrt
import resource
import sys
import time
import traceback
class IndexLevelHolder():
"""Acts as a class to store the index and level"""
def __init__(self, index, level):
self.index = index
self.level = l... |
ea87b9dfb10ebc86d0a7ff4782975a91344755e0 | matushinn/sql-practice | /sample02.py | 261 | 3.65625 | 4 | import sqlite3
def main():
conn = sqlite3.connect("users.sqlite")
cursor = conn.cursor()
sql = "INSERT INTO users (name,age) VALUES ('Tom',43)"
cursor.execute(sql)
conn.commit()
conn.close()
if __name__ == "__main__":
main()
|
d6a20e9cf5439c6294d4edeee3f06040cddf3272 | felipe-ssouza/lista_de_exercicios_python | /estrutura_sequencial_8.py | 314 | 3.984375 | 4 | # Faca um Programa que pergunte quanto voce ganha por hora e o numero de horas trabalhadas no mes. Calcule e mostre o total do seu salario no referido mes.
hora = int(input('Quanto voce ganha por hora?: '))
numero = int(input('Numero de horas trabalhadas no mes?: '))
print("Total de salario: ", (numero*hora))
|
ffbb442cd33a2d7a22c833182332e2c95a54e42a | wtsi-hgi/openstack_report | /backend/utils.py | 386 | 3.5 | 4 |
import asyncio
# Runs in a separate thread. On every iteration, it runs the couroutine in a blocking way. There is no event loop. To Answer: What if the coroutine fails? Do coroutines return an exception?
def run_blocking_tasks(coroutine, *args):
while True:
coroutine_object = coroutine(*args) #Example:... |
282ca29bcb51dacb4bef17bb224bda9e859a029b | iftekherhossain/30-Days-of-Code | /day 28.py | 485 | 3.546875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
if __name__ == '__main__':
N = int(input())
fnames = []
eids = []
for N_itr in range(N):
firstNameEmailID = input().split()
firstName = firstNameEmailID[0]
emailID = firstNameEmailID[1]
if str(e... |
7d0d8c08d958220be78aa1bc648881fe3d0c35c6 | ckobayashi714/CPSC-471-FTP | /server/serv.py | 5,471 | 3.703125 | 4 | import socket
import os.path
import sys
import subprocess
import commands
# Command line checks
if len(sys.argv) != 2:
print ('ERROR:To Run: python3 ' + sys.argv[0] + ' <Port Number> ')
listenPort = sys.argv[1]
# Check for valid port
while True:
try:
if (listenPort.isdigit() == False):
raise... |
895886759c746e5498e26f00bdffa824df09af51 | nyetes/sem5-artificial-intelligence | /lab4/2.py | 157 | 3.71875 | 4 | # list1=[1,2,3,4,5,6]
# for i in list1:
# if i%2==0
#
#
# print(list1)
num=[1,2,3,4,5,6]
for i in range(0,len(num)):
if num[i]%2==0
num[i]=0
print(num) |
56b591eb577fa3f8d1fd2187ae550327bd2a11e6 | mikuc96/Python | /Basic algorithm & Data Structures/Algorithms/cw8_1.py | 947 | 4.0625 | 4 | # -*- coding: utf-8 -*-
# Zbadać problem szukania rozwiązań równania liniowego postaci a * x + b * y + c = 0.
# Podać specyfikację problemu. Podać algorytm rozwiązania w postaci listy kroków,
# schematu blokowego, drzewa. Podać implementację algorytmu
# w Pythonie w postaci funkcji solve1(), która rozwiązania wypis... |
8cb74f3ee41b97703ff28bd95af75784de539bca | icejoywoo/toys | /algorithm/leetcode/17_letter_combinations_of_phone_number.py | 1,050 | 3.65625 | 4 | #!/usr/bin/env python2.7
# encoding: utf-8
"""
@brief:
@author: icejoywoo
@date: 24/03/2017
"""
class Solution(object):
mapping = {
'1': '',
'2': 'abc',
'3': 'def',
'4': 'ghi',
'5': 'jkl',
'6': 'mno',
'7': 'pqrs',
'8': 'tuv',
'... |
091309eb7f3141974998f90f5ff667635c1c06c2 | jbraun8/LineRendezvous | /agent.py | 1,350 | 3.71875 | 4 | # Agent Object
# Has the followng properties:
#
# self.StartPos == starting position of agent
# -2, 0, or 2
#
# self.Direction == how do they define forward
# 1 -> move right on number line
# -1 -> move left on number line
#
# self.History == list of their movements
# In GENERIC form (always starts with 1)
#
# sel... |
6cff98aa8c8e5b8a2751fb99cbd06ea3e4cbeac3 | joelgrus/posterization-pyladies | /posterization.py | 7,006 | 3.59375 | 4 | from __future__ import division
from matplotlib.image import imread
import matplotlib.pyplot as plt
import numpy as np
import random
def rescale_pixel(rgb_pixel):
"""given a rgb pixel (red, green, blue), where each color
is a number between 0 and 255, return the rescaled pixel
with values between 0.0 and 1... |
6384649469b6e12ae6be81e081bf4f999e09c1bf | yojimat/100_plus_Python_Programming_Exercises | /day_7_desafio_100_ex_python.py | 4,497 | 4.125 | 4 | ########################################
print("\nQuestão 18:")
print("A website requires the users to input username and password to register.")
print("Write a program to check the validity of password input by users.")
print("Following are the criteria for checking the password:")
print("At least 1 letter between [a-... |
242afd15e41a6467c6ce0c08074f6fe6b879489c | astraszab/Gradient-Boosting-Machine | /gradient_boosting.py | 5,157 | 3.53125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
from sklearn.tree import DecisionTreeRegressor
class LS_Boost:
"""Gradient Boosting for regression optimizing MSE.
Keyword argumetns:
num_trees -- number of boosting stages (positive int, default 100)
max_... |
33c2e2978274d53d339733b837a2f7e83286694f | aaka2409/Python-Simple-Programs | /potência.py | 122 | 3.515625 | 4 | n = int(input())
total = 0
for i in range(n):
num = input()
total += int(num[0:-1:+1]) ** int(num[-1])
print(total) |
fd4753401e700962add1009be77a7e3d245e2629 | SunshineHai/PythonTest | /DataStructure/双向链表.py | 4,046 | 3.859375 | 4 |
class ListNode(object):
# 1.定义构造器
def __init__(self, val = 0):
self.prev = None # 前指针
self.val = val # 存放值
self.next = None # 后指针
class MyLinkedList(object):
# 1.构造器: 初始化头结点
def __init__(self):
self.size = 0 # 节点个数
# 头结点 和 尾节点
self.head, self.... |
d6f04faed10bdbb22f6f02cbe872eac46fc39ffe | dheerajalim/impactanalytics_question | /ProductSum.py | 389 | 3.5625 | 4 | def ProductSum(arr):
n = len(arr)
count = 0
for i in range(n):
if isinstance(arr[i],list):
if i %2 == 0:
count = count + 2 * (ProductSum(arr[i]))
elif i%2 == 1:
count = count + 3 * (ProductSum(arr[i]))
conti... |
d1c1b04ed677ef3ee2d8ae3ce4bd4003571de99c | cstin854/littlevox | /littlevox/outline/simple_search.py | 807 | 3.6875 | 4 | """
Important function of note here is "get_matches". Takes three arguments, two required, one optional.
"""
import difflib
def get_matches(query, query_set, num_matches=20):
"""
Takes query (string) and query_set (list of objects that can be converted to strings) and returns the best
(num_matches) number... |
88c991064fe1503d799d55b5de645ae6267ca8e0 | DincerDogan/Data-Science-Learning-Path | /Data Scientist Career Path/3. Python Fundamentals/5. Python List/5. Challenge (Advanced)/1. every 3 number.py | 173 | 3.640625 | 4 | #Write your function here
def every_three_nums(start):
return list(range(start, 101, 3))
#Uncomment the line below when your function is done
print(every_three_nums(91)) |
40a7ca47ff416c547169ce8f9847af794e03cb5d | loanchip/fast_ner | /fast_ner/utils/entity_handling.py | 8,175 | 4.03125 | 4 | import pandas as pd
import pickle
from os import walk
from . string_handling import string_cleaning
def insert_entity(dict_, entity):
"""Inserts a new entity value into a dictionary.
Finds the appropriate dictionary in the nested dictionary
structure and inserts the new entity value.
Args:
... |
3e3e1dabe1d83cfefb6a600e15bbe1c6101a5dfd | NickGalindo/EDA-LevelUp | /LevelUp/structures/queue.py | 2,189 | 4.125 | 4 | from typing import Any
#Node for queue class
class _Node:
def __init__(self, val: Any=None, next: Any=None):
"""
Constructor for Node class
:param val: the value of the Node
:param next: the next node in the list
"""
self.val = val
self.next = next
def _... |
de81a1ec60dd0d297aa619bbf67f40abb9e28f94 | Abishek8344/abishekxetri | /leap.py | 484 | 3.921875 | 4 |
'''year=int(input("enter the years"))
if year%4==0:
print("leap year")
else:
print("not a leap year")
'''
a= input("enter first value")
b= input("enter second value")
c= input("enter third value")
d= input("enter fourth value")
if a==b ==c ==d:
print("it is square")
elif a==b and c==d:
print ("... |
41d94d9ab5f68a744c2a577e879c6e8bbe7f40b8 | adiggo/leetcode_py | /count_primes_204.py | 1,443 | 3.578125 | 4 | class Solution:
# @param {integer} n
# @return {integer}
def countPrimes(self, n):
# this is how we define prime
# PRIME integer is the positive integer must be larger than 1
# two step:
# whether a number is prime
# coutn how many less than n
if n <= 1:
... |
26b0400fda1a51cb9f2575490a22fa42528cef7a | Littlemansmg/pyClass | /Week 4 Assn/Project 11/11-3.py | 1,020 | 3.5625 | 4 | # created by Scott "LittlemanSMG" Goes on DD/MM/YYYY
import datetime
import logging as logger
def get_value(invest, interest, years):
total = 0.0
for i in range(years):
total += round(invest * 12, 2)
total += round(total * (interest / 100), 2)
return round(total, 2)
def get_investmen... |
ca4e60272dcd4838f38f9c595631716f4ae188c6 | Gowtham-cit/Python | /Guvi/duplicate.py | 205 | 3.71875 | 4 | from collections import Counter
def duplicate(a):
c=Counter(str(a))
if any(value>1 for value in c.values()):
print("yes")
else:
print("no")
a=int(input())
duplicate(a)
|
20ea43dd64327963bd33ff27665044d646713551 | Ovoma/huper | /zadacha4.py | 1,049 | 4.0625 | 4 | #Напишите программу, которая считывает с консоли числа (по одному в строке) до тех пор,
#пока сумма введённых чисел не будет равна 0 и сразу после этого выводит сумму квадратов всех считанных чисел.
#Гарантируется, что в какой-то момент сумма введённых чисел окажется равной 0, после этого считывание продолжать не нуж... |
450907777189390114b4b5db7eba9c815881752a | solanum-tuberosums/bangazon_terminal_interface | /src/main.py | 15,691 | 3.640625 | 4 | """
--- Description ---
Main Bangazon Command Line Interface module that contains all of the
methods' invocations/calls and the logic for managing the user's
interaction with this program.
"""
import datetime
import os.path
from methods import *
def run_ordering_system(menu_command=None):
"""
Thi... |
b1273a5685cca685f44d61413989efd7ba006a8b | MatiasDuhalde/contenidos | /semana-05/ejercicios_propuestos/08-Problema_8.py | 1,569 | 3.5625 | 4 | import threading
import time
from random import shuffle
bebestibles = ["Vino"] * 15 + ["Pipeño"]
helados = ["Vainilla"] * 20 + ["Piña"]
shuffle(bebestibles)
shuffle(helados)
pipeño_encontrado = threading.Event()
helado_encontrado = threading.Event()
def busca_pipeño():
print("¡Voy por el pipeño!")
for bebest... |
7409ef9ed3fb21680f9ba1963f92a578654c77f5 | mandybawa/HackerRank | /30_days_of_code_challenge/day_14_scope.py | 1,063 | 3.875 | 4 | # Task:
# Complete the Difference class by writing the following:
# A class constructor that takes an array of integers as a parameter and saves it to the elements instance variable.
# A computeDifference method that finds the maximum absolute difference between any 2
# numbers in N and stores it in the maximumDif... |
97a12dfa3614cfec5eb8348f803462a344dcff98 | trendscenter/coinstac-ssr-vbm | /scripts/utils.py | 405 | 3.984375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 24 20:37:34 2019
@author: hgazula
"""
def list_recursive(parsed_dict, key):
"""Recursively searched to find the value of the key."""
for k, val in parsed_dict.items():
if isinstance(val, dict):
for found in list_recursi... |
6d7ada23afdf2b3bc8b56449e40950e05d309fca | Kcpf/DesignSoftware | /Palavras_iniciadas_em_a.py | 692 | 4.15625 | 4 | """
Crie um programa que pergunte palavras ao usuário e preencha uma lista. O programa deve parar com a palavra "fim". Ao final, imprima somente as palavras em que a primeira letra seja "a". Use um print por palavra.
Dica: você pode acessar um único caractere de uma string da mesma maneira que acessamos um elemento de... |
65a279348a3ce2a6a4a15a4db846082e1c1b8952 | darkless456/Python | /timing.py | 517 | 3.71875 | 4 | # timing.py
import datetime, calendar
today = datetime.date.today()
yesterday = today - datetime.timedelta(days = 1)
tomorrow = today + datetime.timedelta(days = 1)
print(yesterday, today, tomorrow)
# -------------------------
'''
last_friday = datetime.date.today()
oneday = datetime.timedelta(days = 1)
while la... |
1e385b8517033c35018f831428af43a17eb3ad57 | ACyong/py_learn | /01_python3/day19/code/slice.py | 776 | 3.890625 | 4 | class MyList:
def __init__(self, lst):
self.data = lst
def __repr__(self):
return "MyList(%r)" % self.data
def __getitem__(self, i):
print("__getitem__被调用, i的值是:", i)
if isinstance(i, slice):
print("这是切片")
print("起始值是:", i.start)
print("终... |
255a3db5d7a41ab65e3a9c5147c26b8d4a153cbb | huangshaoqi/programming_python | /XDL/python/Part_1/Day10/3.py | 656 | 3.671875 | 4 | from functools import wraps
def outer(func):
"""
1.This is outer function doc
"""
print("1This is outer function\n", outer.__name__, outer.__doc__)
# @wraps(func)
def inner():
"""
2.This is inner function doc
"""
print("2This is inner function\n", inner.__name_... |
a8e2bb5de687424497fac3b698a3e84cbc91cb3b | ezanat1/twitterSentimentAnalysis | /twitts.py | 1,886 | 3.5 | 4 | from textblob import TextBlob
import tweepy
import matplotlib.pyplot as plt
def percentage(part,whole):
return 100 * float(part)/float(whole)
consumerKey= "XhT1fkX1AVdt3h3mc3lo8VthQ"
consumerSecret = "XzPQ1xw3T0RCOlcxwmVEo5whe7vcJS3mV9tQoyfj79iPznBC85"
accessToken = "534754924-eAnC6UTt8hD1osft5upI94Gjwfp6DBfFIXi1... |
7256475f7a8c59b5b83c2cac5250a074a457b73d | japanshah17/Python_coding | /compare.py | 252 | 4.125 | 4 | a = input(('enter number 1'))
b = input(('enter number 2'))
c = input(('enter number 3'))
if a > b and a > c:
print("greater is " + a)
if b > a and b > c:
print("greater is " + b)
if c > b and c > a:
print("greater is " + c)
|
00e013085613cf0aefd7ad014fd15f97f8b06676 | sachdeva-ay/Data-Analysis-Python | /Assignment3/Question2_Part2/Q2_Part_2.py | 1,342 | 3.75 | 4 |
# coding: utf-8
# In[2]:
import pandas as pd
import numpy as np
#reading the CSV file
df=pd.read_csv(r'employee_compensation.csv')
# In[3]:
#Filtering the dataset for only Calender year
df_Calender=df[df["Year Type"]=='Calendar']
# In[4]:
# Grouped the dataset by Job Family and employee identifier to find the ... |
6368c775481dba039658d8eb55b59e9842dfc738 | anupkumarsahu/Machine_Learning_with_python_cookbook | /chapter2 Loading data/simulatedData.py | 681 | 3.53125 | 4 | # Load library
from sklearn.datasets import make_regression
# Generate features matrix, target vector, and the true coefficients
features, target, coefficients = make_regression(n_samples=100,
n_features=3,
n_informative=3,... |
1af5fe7564bf771436e6d6793e87df0bd3dc6bb0 | Sladkish/python | /les2 task2 normal.py | 1,732 | 4.1875 | 4 | # Задача-2: Дана дата в формате dd.mm.yyyy, например: 02.11.2013.
# Ваша задача вывести дату в текстовом виде, например: второе ноября 2013 года.
# Склонением пренебречь (2000 года, 2010 года)
__author__ = 'Михайловский Василий Владимирович'
date=input("Ведите дату ввиде dd.mm.yyyy: ")
print(date)
day = int(date[:2]... |
8693ed20749c9ae56fd52e1e7ac416c45ce89633 | rahul-aggrawal/2048-Puzzle-Game | /PuzzleGame.py | 7,476 | 3.578125 | 4 | from tkinter import *
from tkinter import messagebox
from random import randint
FONT = ("Verdana", 40, "bold")
SCORE_FONT = ("Verdana", 10, "bold")
def new_game():
board = [[0 for i in range(4)] for i in range(4)]
return board
def add_two(board):
zero_block = []
for i in range(4):
... |
025bac76e98cb9662d4f3c297ac17f49060de409 | flavius87/aprendiendo-python | /07-ejercicios/ejercicio7.py | 419 | 3.90625 | 4 | """
Ejercicio 7: hacer un programa que muestre todos los números impares
entre dos números que elija el usuario.
"""
numero1 =int(input("Elige el primer número: "))
numero2 =int(input("Elige el segundo número: "))
if numero1 < numero2:
for contador in range (numero1, (numero2 + 1)):
if contador%2 != 0:
... |
930ff443dff948f65aa2f1ac2daeda7fcdca1577 | stephenfrench9/pytest-examples | /fixture_availability/test_1.py | 2,627 | 3.671875 | 4 | """
When a test searches for a fixture, it searches
- function-scope
- class-scope
- module (file) scope
- package (directory) scope
"""
import pytest
"""
This fixture is scoped to the function
This fixture is defined in a module-scope
"""
@pytest.fixture
def order():
return []
"""
1. This fixture is scoped to ... |
aa2fe47c484050b0394b7a42cc80c9ca0383da12 | caiogo18/IAProject1 | /RandomCityMap.py | 1,138 | 3.734375 | 4 | # -*- coding: utf-8 -*-
from CityMap import CityMap
from random import randint
class RandomCityMap(CityMap):
MAX_COST = 100
def __init__(self, numberOfCities):
cityList = RandomCityMap.__generateCityList(numberOfCities)
costs = RandomCityMap.__generateCosts(cityList)
CityMap.... |
259104a203da9ca38e3fdb846a74b511832b6baf | flyinNet1020/Products | /Products.py | 1,829 | 3.84375 | 4 | import os
# function呼叫需要參數、回傳值
# function儘量只做一件事
# 讀取檔案
def read_file(filename):
products = []
with open(filename, 'r', encoding = 'utf-8') as f: # 寫入/讀取檔案都會有編碼的問題,要特別注意
for line in f:
if '商品,價格' in line:
continue # 不處理後面再繼續一次迴圈;break會直接跳出當下迴圈
name, price = line.strip().split(',') # 把換行符號(\n)去除後,遇到逗點就分割,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.