blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
fcb0250482d203dff40358708c5dff6a91edcbde | JawshyJ/Coding_Practice | /Games and Entertainment/Overlord.py | 11,286 | 3.671875 | 4 | #11/3/2020 - Overlord
# A game where a user takes control of a small military cell during World War III
# Tasks:
## Add Tutorial information
## Add Advisor Customization
## Add enemy calculations?
## Add Strength system
## Perfect combat algorithms
import random
# System Variables
game = True
tutorial = True
userInpu... |
dc2af9ce58805cf0299e8e5eb000e70cdfbc21e8 | muhammadnasrudin26/Tugas3 | /latihanB .py | 194 | 3.96875 | 4 |
print('====== Menentukan Bilangan Terbesar ======')
max=0
while True:
a=int(input('Masukkan bilangan = '))
if max < a:
max = a
if a==0:
break
print('Bilangan terbesarnya adalah = ',max)
|
bc4315de56d0785677de7f7556c76130d7136ad3 | pratibashan/Wk2_Monday_Assignments | /vehicleclass.py | 335 | 4 | 4 |
class Vehicle:
def __init__(self,make,model,year):
self.make = make
self.model = model
self.year = year
def print_info(self):
print(f"{self.year} {self.make} {self.model}")
car = Vehicle('Nissan','Leaf','2015')
print(car.make)
print (car.model)
print (car.year)
c... |
0bef014682f8a4663374bfc12420f2b08f91693f | MissLivesey/password_gen | /words.py | 2,205 | 3.890625 | 4 | import random
import tkinter as tk
import pyperclip
from tkinter import ttk
LETTERS = 'bcdfghjklmnprstvwxzaeiou'
LETTERSUPPER = 'BCDFGHJKLMNPRSTVWXZAEIOU'
SYMBOLS = '!@#$%^&*()?/":;+-§№'
DIGITS = '1234567890'
LETTERS = list(LETTERS)
LETTERSUPPER = list(LETTERSUPPER)
SYMBOLS = list(SYMBOLS)
DIGITS = list(DIGITS)
DEFAUL... |
4c1d4992a4414d83d0ba26f09da8f25b73f2fae9 | glider4/numerical-analysis | /python-scripts/bisection.py | 1,090 | 4.09375 | 4 | # Numerical Analysis
# Bisection Method to find roots of an equation
import time
start_time = time.time()
def main():
bisection(1.0, 2.0, 0.5e-12) # lower bound, upper bound, accuracy desired
def function(x): # function we're trying to find root of
return (x ** 3) + 2 * (x ** 2) + 10 ... |
5f2f7e32e1b8e9c016c8749dc65d6076d9f23f73 | muedwin/pythonproject1 | /indicators.py | 1,253 | 3.921875 | 4 | import numpy as np
def moving_average(stock_price, n=7, weights=[]):
'''
Calculates the n-day (possibly weighted) moving average for a given stock over time.
Input:
stock_price (ndarray): single column with the share prices over time for one stock,
up to the current day.
n (int... |
868726eca0026e77b7bebdf91ad272a83f22b35b | Lucx14/Exercism-Python | /meetup/meetup.py | 1,294 | 3.640625 | 4 | from datetime import date, timedelta
position = ["last", "1st", "2nd", "3rd", "4th", "5th"]
def meetup(year, month, week, day_of_week):
start, end = date(year, month, 1), add_month(year, month)
days = find_days(start, end, day_of_week)
if week == "teenth":
day = list(filter(lambda date: date.day ... |
ae2db41b7947fe968c423f1d2c13377825a474ca | Lucx14/Exercism-Python | /linked-list/linked_list.py | 1,858 | 3.921875 | 4 | class Node:
def __init__(self, value, succeeding=None, previous=None):
self._value = value
self._next = succeeding
self._previous = previous
def value(self):
return self._value
def next(self):
return self._next
def previous(self):
return self._previous
... |
0a968c7ac9610dcf2800a2e2ec9e144a86652a81 | Lucx14/Exercism-Python | /tree-building/tree_building.py | 1,640 | 3.578125 | 4 | from typing import List
ROOT_ERROR = "Root node cannot have a parent"
PARENT_ID_ERROR = "Parent id must be lower than child id"
TREE_CYCLE_ERROR = "Tree is a cycle"
RECORD_ID_ERROR = "Tree must be continuous with a 0 root id"
class Record:
def __init__(self, record_id, parent_id):
self.record_id = record... |
279fceef921d0a713e3e22f4a193222a765b37c1 | Lucx14/Exercism-Python | /variable-length-quantity/variable_length_quantity.py | 552 | 3.71875 | 4 | def encode(values):
encoding = []
for v in values:
bs = []
mask = 0
while not mask or v:
bs.append(mask | (v & 0x7F))
v >>= 7
mask = 0x80
encoding += reversed(bs)
return encoding
def decode(encoding):
if len(encoding) and (encoding[-1... |
df883acef0142a1e57d1ca7c01cfc0480f68b0b2 | Lucx14/Exercism-Python | /word-count/word_count.py | 156 | 3.625 | 4 | import re
from collections import Counter
def count_words(sentence):
return Counter(re.findall(r"[\w]+(?:'\w)*", sentence.lower().replace("_", " ")))
|
d23819c935321285b4c694023a7714b57074cd12 | Amanjain24/inamorata | /prime using list comprehension.py | 305 | 3.828125 | 4 | a=input("number please")
a=int(a)
if a==2:
print ("prime")
else:
c = [x for x in range(2, a) if a % x == 0]
if len(c)>0:
print("NOT PRIME method 1")
else : print ("prime11")
b=2
while (b!=a):
if a%b==0 & a!=b:
print("not a prime")
break
else:
b=b+1
if(b==a):
print("prime")
|
06d06080ebd934da89f890fff80dd5a7a8ec669f | Jananisathya/jananisathya | /evee.py | 144 | 3.984375 | 4 | num = int(input(" "))
flag = num%2
if flag == 0:
print(num, "Even")
elif flag == 1:
print(num, "Odd")
else:
print("Error, Invalid")
|
9d08586ac96e7cdbeeeb962cff8fd77ca95d6982 | Jananisathya/jananisathya | /positive.py | 129 | 4.21875 | 4 | num = float(input("Enter a number: "))
if num > 0:
print("positive")
elif num == 0:
printf("Zero")
else:
printf("negative")
|
a1511016d105be5b2e74919c452d2fe9292168cd | Jananisathya/jananisathya | /j3.py | 105 | 3.59375 | 4 | import sys
n = int(input('enter n : '))
sum = 0
a = n
while a > 0 :
sum += 1
a //= 10
print(sum)
|
a24e2279a1a9746dee9adcbb628457c8b9c33586 | zhang-qiyun-seven07/Qiyun_book-recommendation_bot | /app.py | 1,673 | 3.875 | 4 | print("Title of program: Book Recommendation bot")
print()
while True:
description = input("Could you describe what genre do you prefer in a sentence?")
list_of_words = description.split()
genre_list = []
recommendation_list = []
counter = 0
for each_word in list_of_words:
if each_word == "fan... |
935b9aa24392a63541064f339f6b1b4106e4dda3 | dox404/basic_python- | /first.nn.py | 120 | 3.765625 | 4 | name=("mani")
age=("20")
print("hello " + name + " your age is " + str(age))
print(f"hello {name} your age is {age}") |
c75ffaf302cf0b248bac4afc2c9da24545782410 | grantf28/Project-Euler-Solutions | /Project Euler 1 - Multiples Of 3 and 5.py | 262 | 3.65625 | 4 | #LCM = Lowest common multiple
n = int(input().strip())
m = 3
x = 5
lcm = 15
mulM = (n-1) // m
mulx = (n-1) // x
mulLcm = (n-1) // lcm
print( m * mulM * (mulM + 1) // 2 + x * mulx * (mulx + 1) // 2 - lcm * mulLcm * (mulLcm + 1) // 2 )
|
dbffdb73d9db17b1fd1eac56fade8592c784d130 | MickiCZ/Projekt-hra | /Inventář.py | 1,020 | 3.515625 | 4 | #item list - 0. name, 1. dmg 2. price 3. equipable 4. type
#wooden_sword = ["Wooden sword", 5, 100, True, "weapon"]
#stick = ["Stick", 0, 0, False, "item"]
#shield = ["Shield", 0, 200, True, "weapon"]
#rock = ["Rock", 0, 0, False, "item"]
#inventory_list = [wooden_sword, stick, shield, rock]
#equiped = []
def in... |
20fb28a32f94769149165000db580f4f3a69eaa2 | LudovicLemaire/Bootcamp-Py-ML-42 | /day01/ex00/recipe.py | 2,056 | 3.671875 | 4 | import sys
def isNb(value):
try:
int(value)
return True
except Exception:
return False
class Recipe:
def __init__(
self,
name,
cooking_lvl,
cooking_time,
ingredients,
description,
recipe_type):
... |
9be0f3ecc6026481c9afecd3695d054f4b4039b6 | LudovicLemaire/Bootcamp-Py-ML-42 | /day01/ex04/generator.py | 1,108 | 3.59375 | 4 | import random
import datetime
def strSort(word):
return word.lower()
def rnDup(words):
seen = set()
seen_add = seen.add
return [x for x in words if not (x in seen or seen_add(x))]
def generator(txt, sep=" ", option=None):
"""Option is an optional arg, sep is mandatory"""
if not isinstance(... |
087f4a2ff93f9ce7a61cb250b1ee49b198832eaf | amadi5892/PythonPrac | /functions.py | 3,263 | 3.765625 | 4 | # def say_hello(name='Default'):
# print(f'Hello {name}')
# def add_num(num1,num2):
# return num1 + num2
# res = add_num(3,4)
# def print_result(a,b):
# print(a+b)
# def return_result(a,b):
# return a + b
# res = print_result(10,20)
# def even_check(number):
# return number % 2 == 0
# print(... |
67c62395c49f7327da7f66d2ab1d04b96886b53a | UnicodeSnowman/programming-practice | /simulate_5_sided_die/main.py | 565 | 4.1875 | 4 | # https://www.interviewcake.com/question/simulate-5-sided-die?utm_source=weekly_email
# You have a function rand7() that generates a random integer from 1 to 7.
# Use it to write a function rand5() that generates a random integer from 1 to 5.
# rand7() returns each integer with equal probability. rand5() must also ret... |
4235ef7dbad2b91aa919d0a3cb36d3f1e1afb042 | UnicodeSnowman/programming-practice | /kth_to_last_node_in_singly_linked_list/main.py | 1,137 | 3.96875 | 4 | # https://www.interviewcake.com/question/kth-to-last-node-in-singly-linked-list
#
# You have a linked list and want to find the kth to last node.
# Write a function kth_to_last_node() that takes an integer k and the head_node
# of a singly linked list, and returns the kth to last node in the list.
class Node:
def _... |
ab8d29337e63fcf2affb908eaf400de7f8c7efd7 | Strahl-12/Crypto_from_scratch | /first_script.py | 3,647 | 3.71875 | 4 | from __future__ import annotations
from dataclasses import dataclass
import random
@dataclass
class Curve:
"""
Elliptic Curve over the field of integers modulo a prime. Points on the curve
satisfy y^2 = x^3 + a*x +b (mod p )
"""
p: int #prime modulus of the finite field
a: int
b: int
#We t... |
ec7d8f68dcd54cbc89fe4f2624fdd033afff8339 | ZumeITInc/Vinod | /Function.py | 760 | 3.75 | 4 | def Mynew():
print('1.Hello Vinod')
Mynew()
print('<============================>')
def myfunc(name):
print('2.Hello' " "+name)
myfunc('vinod')
print('<============================>')
def slide(add1,add2):
return(add1+add2)
sum=slide(20,25)
print('<============================>')
def new(mystrin... |
18792c138a49dacab7532e6d9ac5deeb1e151253 | dundass/dundass.github.io | /plive.py | 972 | 3.515625 | 4 | from Tkinter import *
import socket
HOST = "localhost"
PORT = 3000
ctrlenter = [False, False]
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((HOST, PORT))
def keyup(e):
#print 'up', e.keysym
if "Control" in e.keysym:
ctrlenter[0] = False
elif e.keysym == "Return":
ct... |
a2aff69e47ac602ed2facc4931d975754ce7b8ea | SteephanSteve/Hunter_Program | /odd_caps.py | 253 | 3.65625 | 4 | s=list(raw_input())
x=[]
for i in s:
if not i==' ':
x.append(i)
for i in range(len(x)):
if i%2==0:
x[i]=x[i].upper()
for i in range(len(s)):
if s[i]==' ':
x.insert(i,' ')
print ''.join(x)
|
51b921168646e463e667b4c28e9b879c133ee487 | rogersilveiraa/Python | /Semana 2/conversor de segundos.py | 302 | 3.546875 | 4 | txtseg = input("Por favor, entre com o número de segundos que deseja converter:")
seg = int(txtseg)
minutototal = seg//60
horas = minutototal//60
minutof = minutototal%60
segf = seg%60
dias = horas//24
horasf = horas%24
print (dias, "dias,", horasf, "horas,", minutof, "minutos e", segf, "segundos")
|
b9566298fc23afd294db875ee0b2e0ddefcf26a6 | rogersilveiraa/Python | /Projetinhos/RG.py | 321 | 3.828125 | 4 | rg = int(input("Digite os oito primeiros digitos do seu RG:"))
z = rg
x = 9
soma = 0
while rg != 0:
aux = rg % 10
rg = rg // 10
soma = soma + (x * aux)
x -= 1
digito = 11 -(soma % 11)
if digito == 10:
digito = x
if digito == 11:
digito = 0
print ("Seu RG completo é:", z,"-",digito)
|
905a5ed284e6b3ab7654351ea5ebcbddb9343603 | rogersilveiraa/Python | /Semana 3/Fizz.py | 104 | 4.1875 | 4 | x = int(input("Digite um número inteiro:"))
if x%3 == 0:
print ("Fizz")
else:
print (x)
|
93eb75310d5994275c3b89190774da1b1ba17eb2 | rogersilveiraa/Python | /Semana 5/maior primo.py | 322 | 3.609375 | 4 | def maior_primo (x):
aux = 2
teste1 = True
while x <= 1:
x = int(input("Digite um valor inteiro maior que 1:"))
while x != aux:
if x % aux == 0:
x -=1
aux = 2
else:
aux += 1
if (x / (aux - 1)) < 2:
return ... |
9b115708f8d40e96f3612b83b18fb2b46b152435 | prathy16/LeetCode | /find_median_from_data_stream.py | 1,024 | 3.640625 | 4 | '''
Problem: https://leetcode.com/problems/find-median-from-data-stream/
'''
from heapq import *
class MedianFinder(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.maxheap = []
self.minheap = []
def addNum(self, num):
"""
... |
2a5b7a6be66898e1465be3101358045965b86432 | prathy16/LeetCode | /friend_circles.py | 698 | 3.640625 | 4 | '''
Problem: https://leetcode.com/problems/friend-circles/
'''
class Solution(object):
def findCircleNum(self, M):
"""
:type M: List[List[int]]
:rtype: int
"""
def dfs(M, visited, i):
for j in range(len(M)):
if M[i][j] == 1 and visited[j] == False... |
b70ba945d1202ff0654e826d8c62126e6a16455a | prathy16/LeetCode | /self_dividing_nums.py | 840 | 3.6875 | 4 | '''
Problem: https://leetcode.com/problems/self-dividing-numbers/submissions/
'''
class Solution(object):
def selfDividingNumbers(self, left, right):
"""
:type left: int
:type right: int
:rtype: List[int]
"""
def isSelfDividingNum(n):
if(n<10):
... |
a2e7c0dd9b52f76edb2cc4a30efc1380b45d0cfd | MB25/BipedalWalker | /myModules/Agent.py | 3,813 | 3.75 | 4 | import numpy as np
'''
This is the agent. It's main purpose is to decay epsilon (so that in the beginning there are more random actions) and is
used to pick a targetFrame, which is the output of the first NN and the input of the second NN
---------------------------------------------------------------------------------... |
8e20a2c8c1c58fba18f3dba500184fe4befc479f | erinleeds11/hackbright-challenges | /search-sorting.py | 1,008 | 3.75 | 4 | #Binary search simple
def binary_search(sequence, item):
start_idx = 0
last_idx = len(sequence) - 1
found = False
while begin_index <= end_index:
midpoint = start_idx + (last_idx - start_idx) // 2
midpoint_value = sequence[midpoint]
if midpoint_value == item:
found... |
70f112f1f50149c4020ad4ccd0169f0adf4dbb7b | CodingTestPreparation/python-algorithm-interview | /solutions/10trie/56taelee.py | 2,104 | 4.09375 | 4 | # version 1 : simple
# class TrieNode:
#
# def __init__(self):
# self.word = False
# self.children = {}
#
# class Trie:
#
# def __init__(self):
# self.root = TrieNode()
#
# def insert(self, word: str) -> None:
# node = self.root
# for char in word:
# if no... |
727e05f25d4c311fcaa40bb367b3949fb8ac4076 | CodingTestPreparation/python-algorithm-interview | /solutions/01array/10taelee.py | 286 | 3.5 | 4 | from typing import List
class Solution:
def arrayPairSum(self, nums: List[int]) -> int:
nums.sort()
sum = 0
for i in range(0, len(nums), 2):
sum += nums[i]
return sum
a = [1,4,3,2]
solution = Solution()
print(solution.arrayPairSum(a))
|
64972f84c490d3f42215f88026942ca89704e833 | CodingTestPreparation/python-algorithm-interview | /solutions/02LinkedList/14jehong.py | 789 | 3.921875 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if not l1:
return l2
if not l2:
return l1
... |
470e4c0591aca8d19029bb958ba2adc02ac88641 | hjq1993/story_paqu | /douban-story.py | 2,174 | 3.578125 | 4 | # 豆瓣小说排行爬取
import requests
from lxml import etree
import json
class DouBan:
def __init__(self):
self.url = "https://book.douban.com/tag/%E5%B0%8F%E8%AF%B4?start={}&type=T"
self.headers = {"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64)"
" AppleWebKit/537.36 (KHTML, like... |
b8b7e6f8a08cc43208075dee98e9b65a723a54af | mrevvin/postfix | /postfix.py | 2,097 | 3.5 | 4 | def drje(n):
if n=="^":
n=4
elif n=="*" or n=="/":
n=3
elif n=="-" or n=="+":
n=2
return(n)
inf=input("plz enter infix : ")
amlgr=[]
pos=[]
post=""
for item in inf:
if item != "+" and item !="^" and item !="*" and item !="-" and item !="(" and item !=")" and item !="/":
... |
15ae5eb1eee0c8553c53419599e1d29127e7be72 | yeelvis/codeeval | /easy/multiplication-tables/multiplication-tables.py | 204 | 3.546875 | 4 | for i in range(1,13):
row = []
for j in range(1,13):
if j == 1:
row.append(str(i * j))
else:
row.append("{:>4}".format(str(i * j)))
print ''.join(row)
|
7443a894f9ca0f6e6276d36e49a12f27dbd76b80 | JITHINPAUL01/Python-Assignments | /Day_5_Assignment.py | 1,654 | 4.25 | 4 | """
Make a generator to perform the same functionality of the iterator
"""
def infinite_sequence(): # to use for printing numbers infinitely
num = 0
while True:
yield num
num += 1
for i in infinite_sequence():
print(i, end=" ")
"""
Try overwriting some default dunder methods and manipu... |
64987feea65320ebafd9768047f541f759282fe2 | trenator/PfCB | /chapter_6/novels.py | 312 | 3.578125 | 4 | data = open("data.csv")
for line in data:
# split the line up
columns = line.rstrip("\n").split(",")
# assign the columns to variables
title = columns[0]
year = columns[1]
type = columns[2]
length = columns[3]
if type == 'novel' or type == 'novella':
print(title)
|
e55afd5bcae9bb61b1fa105804628294bb4788b3 | trenator/PfCB | /chapter_2/Ex2_1.py | 1,137 | 3.671875 | 4 | # counting vowels
# what proportion of this sentence is made up of the vowels (a e i o u)
sentence = "It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness, it was the epoch of belief, it was the epoch of incredulity, it was the season of Light, it was the season ... |
177907db43011bb8ba991b7b789ccfd90e228530 | trenator/PfCB | /chapter_4/Chapter4_Ex1.py | 425 | 3.640625 | 4 | file_name = "two_cities.txt"
input_file = open(file_name)
paragraph = input_file.read()
#print(paragraph)
removed_line = "it was the "
new_paragraph = paragraph.replace(removed_line, "")
#print(new_paragraph)
new_file = open("edited_two_cities.txt", "w")
new_file.write(new_paragraph)
new_file.close()
input_file.close... |
f80b9931facb277a6ade16d67ebebd620799cc8d | trenator/PfCB | /chapter_2/sentence_lengths.py | 628 | 3.71875 | 4 | text = "Night is generally my time for walking. In the summer I often leave home early in the morning, and roam about fields and lanes all day, or even escape for days or weeks together; but, saving in the country, I seldom go out until after dark, though, Heaven be thanked, I love its light and feel the cheerfulness i... |
9d1267825b8f837b1586561305837c889881953b | trenator/PfCB | /chapter_8/csv_module.py | 220 | 3.65625 | 4 | import csv
data = open("data.csv")
data_reader = csv.reader(data)
for row in data_reader:
title = row[0]
year = int(row[1])
type = row[2]
length = row[3]
print(title + " published in " + str(year))
|
66d0dfc6de97ba43c3765cdfa66a5d0e2a5d16a8 | trenator/PfCB | /chapter_2/replace.py | 213 | 3.96875 | 4 | greeting = "Hi, friend!"
# replace i with o
print(greeting.replace("i", "o"))
# we can replace more than one character
print(greeting.replace("Hi", "Howdy"))
# the original variable is not affected
print(greeting)
|
459c7c225d1c8cec2332609f506fe310ea03d51a | trenator/PfCB | /chapter_3/Chapter3_scratch.py | 448 | 3.859375 | 4 | # my_file_name = "first_line.txt"
# my_file: TextIO = open(my_file_name)
# my_file_contents = my_file.read()
# open the file
my_file = open("first_line.txt")
# read the contents
# sentence = my_file.read()
# remove the newline from the end of the file contents
sentence = my_file.read().rstrip("\n") # 2 steps in 1
# ... |
dc677bd495638cdf15d489c3de2c34af548dd602 | lijianzwm/leetcode | /110.py | 981 | 3.84375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 18/11/9 17:34
# @Author : lijian
# @Desc : https://leetcode.com/problems/balanced-binary-tree/
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None... |
b461bf0edc931efe39b3f6a00dcf5f86e3dd2cf8 | lijianzwm/leetcode | /101.py | 1,021 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 18/11/9 14:05
# @Author : lijian
# @Desc : https://leetcode.com/problems/symmetric-tree/
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
clas... |
d9473b7afb52e047e699352526616ec7fdf1d52f | CyberSpecialist/R | /Random number game.py | 288 | 4.0625 | 4 | import random
num_to_guess = random.randrange(1, 10)
number = input("Pick a number between 1 and 10 ")
answer = int (number)
if answer == num_to_guess:
print ("Congrats You Guessed Right!")
else:
print("Too bad. You guessed wrong.")
print ("The number was ", num_to_guess)
|
36a3aa0df6425f0876442c374eca48c0c709d592 | shahasifbashir/LearnPython | /ListOver/ListOverlap.py | 591 | 4.28125 | 4 | import random
#This Examples gives the union of two Lists
A = [1,2,3,4,5,6,7,8,5,4,3,3,6,7,8]
B=[6,7,8,9,4,3,5,6,78,97,2,3,4,5,5,6,7,7,8]
# we will use the set becouse a set contains unique elemets only ann then use an and operator
print(list(set(A)&set(B)))
# The same example using Random Lists
A= range(1,random.r... |
d47688c8ce8f98563ed5c39dd44318cac5aa8c42 | Plaudenslager/dtree | /DTree_app2.py | 2,048 | 3.5 | 4 | __author__ = 'peter'
from DTree import *
'''
Create a sample tree:
Should I repair or replace my car?
Repairing my car costs $2,600 today, and has cost about $9000 over last 4 years.
This averages to $2,250 per year, but usually comes in big lumps at random times.
Replacing my car will cost $5,000 today, and $42... |
46966d20a04825783f7a9f9d717e0c56c4f356b1 | shaung/euler | /python/p7.py | 385 | 3.609375 | 4 | from itertools import count
def is_prime(n):
for i in range(2, n):
if n % i == 0:
return False
return True
def gen_prime():
yield 2
yield 3
for i in count(1):
for n in (6*i - 1, 6*i + 1):
if is_prime(n):
yield n
for i, n in enumerate(gen_pri... |
acb6ac656cca2f107e95e799302962c2145dc2b1 | hrishi32/mtp-both | /Dimensionality-Reduction - Real/Test Files/Object_Files/mapper.py | 7,049 | 4 | 4 | import numpy as np
import random
"""
* class mapper
*
* Summary of mapper class:
*
* This class stores the mapping between input vector and output vector.
* Implemented methods support feature insertion, deletion and other functionalities.
*
* Description:
*
* This class cr... |
3ad9b5180cd7b5438922ff16116b2442ab6c249b | avjgit/kata | /exercism/python/pangram/pangram.py | 222 | 3.8125 | 4 | def is_pangram(sentence):
sentence_case_insensitive = sentence.lower()
for character in "abcdefghijklmnopqrstuvwxyz":
if character not in sentence_case_insensitive:
return False
return True
|
6cd7e441a2d64aae9b8fd79b3ca3183796ad21a9 | MITLLRacecar/racecar-daniel-chuang | /library/real/GPIO.py | 2,063 | 4.0625 | 4 | import serial
import struct
def pin_mode(pin, mode, ser):
"""
Sets a GPIO pin to be able to read or be written to.
Example:
# pin 12 will be set as an OUTPUT pin
# the instruction is sent through a Serial port to the Arduino
ser = serial.Serial('COM15', 115200)
def start()... |
72a72dee6350b03bae8c086b680e00c7c2b49ec7 | r-souza/dio-security-with-python | /password/password_generator.py | 242 | 3.78125 | 4 | import random
import string
size = int(input("How many characters do you want your password to be? "))
chars = string.ascii_letters + string.digits + '!@#$%^&*()-_=+'
print(''.join(random.SystemRandom().choice(chars) for _ in range(size)))
|
8442eaca4073840972d883f7c04e822d66366eea | JoaoPedroToledo/Forca-Python | /Forca-Python/EP 2.py | 5,334 | 3.90625 | 4 |
# Exercicio Programa 2: João Pedro, Lucas Monteiro
#ADS 1°B 2016
# coding=<nome da codificação>
print('O jogo começara em breve, aguarde alguns instantes!')
def escolhe():
import urllib.request
page = urllib.request.urlopen ('http://www.ime.usp.br/~pf/dicios/br')
palavra = page.read().decode ("is... |
57992d8e576a9c5df264083e74d67b6d29ae00c9 | susanbruce707/Virtual-Rabbit-Farm | /csv_mod.py | 1,205 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 13 00:27:26 2020
@author: susan
Module to read CSV file into nested dictionary and
write nested dictionar to CSV file
rd_csv requires 1 argument file, as file name for reading
wrt_csv requires 2 arguments file name and dictionary name to write CSV file.
"""
imp... |
6f6d6e14ffa30489eea67bb5b496032bdedb0214 | EmmanuelME25/PythonCode | /list.py | 378 | 4.03125 | 4 | #arreglos
num=[1,2,3,4,5]
fru=['Naranjas','Uvas','Peras','Manzana']
#otro cambio
print (num,fru)
#tamano del arreglo
print(len(fru))
#agragar al arreglo
fru.append('Mango')
print(fru)
#ciclo
for i in range(0,4):
print(fru[i])
fru.remove('Uvas')
print (fru)
fru.insert(2,'Pina')
print (fru)
fru.pop(2)
print(fru)... |
cc85d28f57cb9d8971c50a22e02f30404b844595 | ztw11ll/data-mining | /Numeric Data Analysis.py | 4,950 | 3.84375 | 4 | ######################################## BM489E HW NO.1 ##############################################
## ALi KARATANA ##
## 121180043 ##
###########... |
9177f5a2439888f086b54aadd81487d5638d9b4e | yashsharm884/Attendance-System-Using-Face-Recognition- | /main.py | 6,180 | 3.6875 | 4 | from tkinter import*
import tkinter
from tkinter import ttk
from PIL import Image,ImageTk # Operations on Image.
import os
class face_recognition123:
def __init__(self, root): # root is the name of the windows.
self.root = root # Initializing the Root.
... |
e81edc82368a14799d1cad6867caa5153b7946f2 | pmoses222/Mypython-projects | /Company_Income _tax.py | 1,708 | 3.59375 | 4 |
# Input the necessary figures
n =int(input('Profit before tax: '))
de =int(input('Disallowable Expenses for the period: '))
a =int(input('Allowable Expenses for the period: '))
capital_allowance = int(input("Capital_allowance for the period: "))
# Where n = Net_profit, de = Disallowed expenses, a = Allowable expen... |
59e4b92fc4388fdf069bc2d301f3e3b077e122e5 | Ikeaven/P4_konrath_kevin | /views/utilities.py | 1,132 | 3.578125 | 4 | """Utilities View"""
class UtilitiesView:
def line_separator(self):
"""Display a line of 118 underscores."""
for _ in range(118):
print('_', end='')
print()
def display_error_NaN(self):
"""Display an error : this field accepts only numbers."""
self.line_sep... |
97e044ca8d9150e2df2d99e46b77fa6e81def00d | ssshrihari/qq | /classes_and_functions.py | 1,136 | 3.84375 | 4 | class Vehicle:
def __init__(self, number_of_tyres, engine_type, body_type,transmission):
self.number_of_tyres = number_of_tyres
self.engine_type = engine_type
self.body_type = body_type
self.transmission=transmission
def engine_start(self):
print(f"{self.engine_type}Engi... |
107b182b99fed80f1807ae3bbdc1e3b2c7ff776d | nithya-06/Comparison-of-Sorting-Algorithmss | /quicksort.py | 2,209 | 4 | 4 | class quick:
#function for quick sort
def partition(object,array, lowelement, highelement):
counter = (lowelement - 1)
# choose the highest element as pivot element
pivot = array[highelement]
for j in range (lowelement, highelement):
# if the pivot is great... |
f30e51134141ffc0f5c92fbafe8534b564458f03 | k3ymkr/amy_python | /numbpick.py | 420 | 4 | 4 | #!/usr/bin/env python
import sys,random
min=1
max=100
onumber=random.randint(min,max)
guess=-1
while int(guess)!=onumber:
print "Pick a number from %d to %d:"%(min,max),
guess=raw_input()
try:
if (int(guess)<onumber):
print "Too low. Guess Higher"
elif (int(guess)>onumber):
print "Too high. Guess Lower... |
63ebd02c44999e8c19252b6ab7fc4fe35e541e95 | Marcio-Marchiori/shark_attack | /shark_.py | 4,075 | 3.6875 | 4 | import re
import pandas as pd
import numpy as np
def use_dates(column_dates):
'''This function will receive a date in the dd-mm-yyyy format, get rid
of anything that isn't an actual date, change the date format to
yyyy-mm-dd all numerical and return it as the date changed or as a string
'Not useful.' ... |
c42162a49ddcc7471982c9dc6bca8abc25a88598 | DIVYAJAYA1997/python-project | /fileopen.py | 390 | 3.625 | 4 | f=open("demo","r")
dict={}
stopwords=["the","is","and","were","was","where","how","an","at","a","than","who"]
for lines in f:
w=lines.rstrip("\n").split(" ")
for word in w:
if word in stopwords:
pass
else:
if word not in dict:
dict[word]=1
... |
9a7c50b878236821d964be4ed13e6ceddcdcb349 | DIVYAJAYA1997/python-project | /prgoops.py | 577 | 3.84375 | 4 | class Student_details:
def __init__(self,name,course,total):
self.name=name
self.course=course
self.total=total
obj=Student_details("Divya","b.tech",1234)
obj1=Student_details("Athulya","mca",4567)
obj2=Student_details("Sherlin","mca",6789)
obj3=Student_details("Arathi","b.tech",7567... |
cb38bac518ad8207bc14c30768b1dea33aab5204 | DIVYAJAYA1997/python-project | /lambdafunction.py | 202 | 3.59375 | 4 | add=lambda n1,n2:n1+n2
print(add(20,10))
sub=lambda a,b:a-b
print(sub(80,30))
cube=lambda n:n**3
print(cube(3))
sqr=lambda x:x**2
print(sqr(2))
even=lambda n:n%2==0
print(even(7))
|
6dfaadc752468d7600616f1e9fcdde057f3f10e5 | DIVYAJAYA1997/python-project | /even num.py | 104 | 4.125 | 4 | n=int(input("ENTER A NUM"))
if(n%2==0):
print("NUMBER IS EVEN")
else:
print("NUMBER IS ODD") |
860a5e117dc62eae13c2f9cf1ea249c706f29d60 | DIVYAJAYA1997/python-project | /datastructures.py | 137 | 3.75 | 4 | person=[1,"abc",20000,"ca"]
person[2]=30000
print(person)
person.append("female")
print(person)
for data in person:
print(data) |
2f4d93b6d0ca5b12e7fed982b2fe86d8e6c1bec9 | DIVYAJAYA1997/python-project | /prg3.py | 193 | 3.765625 | 4 | text="abbac"
dict={}
for ch in text:
if ch not in dict:
dict[ch]=1
else:
dict[ch]+=1
for k,v in dict.items():
if v==1:
print(k,"is non recursive")
|
1550d5dc566bb40e2081f79469a94334305d874f | kotteeshwaran/91social | /files.py | 390 | 4.09375 | 4 | with open("File1.txt","w") as f:
f.write("A text file is a computer file that only contains text and has no special formatting such as bold text, italic text, images, etc. With Microsoft Windows computers text files are identified with the .txt file extension, as shown in the example picture")
with open("File1.tx... |
fc07924fd7739c9816753ce8c051e8a60f6f98c5 | jamesthesnake/Random-code-side-projects | /GRAPHKMERALGO.py | 2,549 | 3.6875 | 4 | #python3
import sys
def overlap_graph(patterns):
"""Creates an overlap graph from a list of k-mers
Args:
patterns: a list of string k-mers
Returns:
a string containing an adjacency list representation of the overlap
graph as described in the problem specification
"""
... |
5a087b5fa4697d02631fa24b2703d76411482579 | cliffeh/util | /examples/python/compare.py | 565 | 3.75 | 4 | #!/usr/bin/env python
''' compare.py - compares two files, outputing the differences between them '''
import sys
if len(sys.argv) < 3:
print "usage:", sys.argv[0], "file1 file2"
sys.exit(1)
file1 = open(sys.argv[1], "r")
file2 = open(sys.argv[2], "r")
list1 = {}
list2 = {}
for line in file1.readlines():
... |
8ae649beb3e9d410d59bab85c7fc38b8d0733f7c | albertqjiang/HackMovies | /Analytics.py | 650 | 3.59375 | 4 | # Data analytics on clustered data
import numpy as np
from KMeans import KMeansClustering
from KMeans import DBSCANClustering
def analyze(X, n_clusters = 8):
"""
This function takes the vector matrix and number of clusters wanted
and returns a dictionaries of lists of the indices of movies.
"""
X_labels = KMeans... |
25a5dc67acc26fb23dc272d0852d5d7c13a75fcb | fadhilmulyono/cp1404practicals | /prac_08/unreliable_car_test.py | 920 | 3.609375 | 4 | """
CP1404/CP5632 Practical
Test Unreliable Car
"""
from prac_08.unreliable_car import UnreliableCar
def main():
# Create several cars
car_1 = UnreliableCar("Fast Racer", 100, 88)
car_2 = UnreliableCar("Azure Racer", 100, 66)
car_3 = UnreliableCar("Red Danger", 100, 44)
car_4 = UnreliableCar("Good... |
29e7fdf995e4f6245899f4a61aac03ac1cac6426 | fadhilmulyono/cp1404practicals | /prac_09/sort_files_1.py | 910 | 4.25 | 4 | """
CP1404/CP5632 Practical
Sort Files 1.0
"""
import os
def main():
"""Sort files to folders based on extension"""
# Specify directory
os.chdir('FilesToSort')
for filenames in os.listdir('.'):
# Check if there are any files in directory
if os.path.isdir(filenames):
conti... |
6e6569c90097c6ae65b39aa6736e234fbf6f4bdf | BruderOrun/PY111-april | /Tasks/a0_my_stack.py | 798 | 4.1875 | 4 | """
My little Stack
"""
stak = []
def push(elem) -> None:
"""
Operation that add element to stack
:param elem: element to be pushed
:return: Nothing
"""
stak.append(elem)
def pop():
"""
Pop element from the top of the stack
:return: popped element
"""
if stak == []:
... |
71bea8432e320bb548361588100ff9d78cf04b02 | ducanh-99/oop | /4_inheritance.py | 532 | 4.09375 | 4 | from abc import ABC, abstractclassmethod
class Animal(ABC):
legs: int
weight: float
height: float
def eat(self):
pass
def drink(self):
print("Animal Drink")
def move(self):
pass
class Fish(Animal):
def drink(self):
print("Not Drink")
class Mammal(Anima... |
7f72b1120e1a02c17ccc9113866e32cab1164830 | tjgiannhs/Milisteros | /GreekBot/greek_preprocessors.py | 1,609 | 4.15625 | 4 | """
Statement pre-processors.
"""
def seperate_sentences(statement):
'''
Adds a space after commas and dots to seperate sentences
If this results in more than one spaces after them another pre-processor will clean them up later
:param statement: the input statement, has values such as text
... |
27574e0b23077340e7c83fcdbac70fac7e408d94 | tremlab/kata | /hackerrank/big_sort.py | 825 | 4.09375 | 4 | """sort for big numbers. (too big for normal int use)
"""
# need to optimize!!! works fine, but meant for
# gigantic strings of gigantic numbers.
def big_sort(unsorted):
strings = {}
for i in unsorted:
st = str(i)
l = len(st)
# convert all to strings
# put into buckets of s... |
ce47e99db613fc2f530f86c4647f031af2e2fea3 | tremlab/kata | /hackerrank/make_anagram.py | 740 | 3.875 | 4 | """Hackerrank challenge - count how many letters must be deleted to make
to make 2 strings anagrmas of each other.
"""
def number_needed(a, b):
a_list = list(a)
a_list.sort()
b_list = list(b)
b_list.sort()
count = 0
while a_list and b_list:
if a_list[-1... |
efdfbc0de07d0e5da1a4248d8462c403d564936d | tremlab/kata | /hackerrank/balance_brackets.py | 588 | 3.609375 | 4 | def is_matched(expression):
dict_b = {
")": "(",
"]": "[",
"}": "{"
}
stack = []
for char in expression:
if char in dict_b.values():
stack.append(char)
elif char in dict_b.keys():
if stack:
most_recent = stack.pop()
... |
29093f93cd61a3fa947795e96224501d8df165db | unnunnjyann/kmeans | /readData.py | 383 | 3.578125 | 4 | import csv
def readData(fileName):
"""
:param fileName:
:return: a 2-dimensional array
"""
data = []
with open(fileName) as csvFile:
reader = csv.reader(csvFile)
for item in reader:
temp = []
for attribute in item:
temp.append(float... |
cbfbe5321a1dbf6587d80f6f1862c9728e29658d | Natsuki0928/TSP_2opt | /.ipynb_checkpoints/TSP-checkpoint.py | 4,712 | 3.5625 | 4 | import streamlit as st
import math
import numpy as np
import matplotlib.pyplot as plt
"""
## 巡回セールスマン問題(traveling salesman problem)
TSPは、都市の集合と各2都市間の移動距離が与えられたとき、
全ての都市をちょうど一度ずつ巡り出発地に戻る巡回路のうちで総移動コストが最小のものを求める
組合せ最適化問題である。
厳密に最適解を求めることを放棄して計算時間を短くする方法はとして、局所探索アルゴリズムを用いる。
"""
# seed値を決定
seed = st.sidebar.number_input(
... |
922f3f6d7341bbd91e62e080774cfbcf5d5a57cd | adam-hotait/3Dtictactoe | /client_side/graphical/connexionScreen.py | 3,786 | 3.59375 | 4 | from .colors import *
import pygame
from pygame.locals import *
import socket
import select
class ConnexionScreen:
"""This class represent the waiting screen where the players must wait the other is ready"""
def __init__(self, window, mySocket, isInviting=False):
"""Creates the connexion screen"""
... |
f695ec43a45a615c8d59b0e4ef20a066a5d82c15 | shjang1013/Algorithm | /BAEKJOON/스택/9012_괄호.py | 887 | 3.609375 | 4 | # input()는 시간초과 발생할 수도 있음 => sys.stdin.readline() 사용
import sys
T = int(input())
for _ in range(T):
# sys.stdin.readline()은 개행을 포함하기 때문에 strip() 사용할 것
bracket = sys.stdin.readline().strip()
stack = []
for i in bracket:
if i == '(':
stack.append(i)
else:
if len(s... |
2917024d4e1ae8208ac9d7c17e3faaf3c637455a | shjang1013/Algorithm | /BAEKJOON/큐, 덱/18258_큐2.py | 1,240 | 3.65625 | 4 | # queue.pop(0)에서 시간초과
import sys
N = int(input())
queue = []
for _ in range(N):
command = sys.stdin.readline().split()
if command[0] == 'push':
queue.append(command[1])
elif command[0] == 'pop':
print(queue.pop(0)) if len(queue) else print("-1")
elif command[0] == "size":
... |
a05b664326041df6246ab3d0f5cd548f30b61856 | shjang1013/Algorithm | /BAEKJOON/문자열/1543_문서 검색.py | 240 | 3.625 | 4 | # 중복되지 않게 최대 몇 번 등장하는지 출력하기
import sys
# 입력받기
document = sys.stdin.readline().rstrip()
word = sys.stdin.readline().rstrip()
document = document.replace(word, '!')
print(document.count('!'))
|
454407b585d1ad68e03387d5a8860b6f9263b63e | shjang1013/Algorithm | /SWEA/5120_암호.py | 1,900 | 3.765625 | 4 | # 문제
# SWEA 5120 - [파이썬 S/W 문제해결 기본 7일차] Linked List - 암호
# 나의 코드
def addtoFirst(data): # 첫 노드에 데이터 삽입
global Head
Head = Node(data, Head)
def add(pre, data): # pre 다음에 데이터 삽입
if pre == None:
print('error')
else:
pre.link = Node(data, pre.link)
def addtoLast(data): # 마지막에 데이터 삽입
... |
2302abc3d949769b74c3a24d73ea2574c8730f89 | shjang1013/Algorithm | /BAEKJOON/큐, 덱/5397_키로거.py | 535 | 3.65625 | 4 | # 강산이의 비밀번호 출력하기
# 커서의 위치 파악하기
from collections import deque
N = int(input())
for _ in range(N):
l = deque()
r = deque()
password = input()
for i in password:
if i == '<':
if l:
r.appendleft(l.pop())
elif i == '>':
if r:
... |
5408fdc6eb2d257ac0958a76578cb625b2330a0c | shjang1013/Algorithm | /Programmers/Level1/나누어_떨어지는_숫자_배열.py | 165 | 3.5625 | 4 | def solution(arr, divisor):
answer = sorted([i for i in arr if i % divisor == 0])
if len(answer) == 0:
answer.append(-1)
return answer
|
b48197ec41a0d33dfe7cd44e49b8419f9dd53a01 | dmcshane01/Etc | /Python/UPSHubSorter/sorter.py | 2,218 | 3.8125 | 4 | #Hub number in 3rd index of csv
#date at 2nd index
import csv
f = open('temp.csv') # Change File Name
csv_f = csv.reader(f) # Open Reader
hubs = []
found = False
"""
First iterate through and create a list of all unique hub #'s
"""
for row in csv_f: #iterate through csv
for i in range(len(hubs)): # it... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.