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 |
|---|---|---|---|---|---|---|
ac43bd467e910850751a6e0654c540bf4c0dbb36 | weidongyu/Code_Challenges | /leetcode/419_battleship_in_a_board.py | 459 | 3.5625 | 4 | class Solution(object):
def countShips(self, board):
counter = 0
for r in range(len(board)):
for c in range(len(board[0])):
if board[r][c] == 'X':
if not( r >= 1 and board[r-1][c] == 'X' or c >= 1 and board[r][c-1] == 'X'):
coun... |
38be8b856f24f1f1f4f91dc3d2656758f3752204 | njokuanthonia3/Budget-App-Zuri | /budget.py | 1,555 | 3.6875 | 4 | class Budget:
def __init__(self, categories, balances):
self.categories = categories
self.balances = balances
def deposit(self, category, amount):
index = self.categories.index(category)
self.balances[index] += amount
print("Deposit Successful!")
... |
300d31816ee875b6c1badf320dd73baf28dde898 | SergiBaucells/DAM_MP10_2017-18 | /Tasca_1_Python/src/exercici_8_python.py | 261 | 3.90625 | 4 | def num_primer():
a = 0
numero = int(input("Introdueix un número: "))
for i in range(1, numero + 1):
if(numero % i == 0):
a = a + 1
if(a != 2):
print("No es primer")
else:
print("Es primer")
num_primer() |
d5d37cee9cdfcc9d9e949ed99da5dd70d723b536 | SergiBaucells/DAM_MP10_2017-18 | /Tasca_1_Python/src/exercici_5_python.py | 417 | 4.125 | 4 | numero1 = int(input("Número 1: "))
numero2 = int(input("Número 2: "))
numero3 = int(input("Número 3: "))
if numero1 < numero2 and numero1 < numero3:
mcd = numero1
elif numero2 < numero1 and numero2 < numero3:
mcd = numero2
else:
mcd = numero3
while True:
if numero1 % mcd == 0 and numero2 % mcd == 0 an... |
fec24e1aea01e0181a5a15303e6a2121acca0912 | SergiBaucells/DAM_MP10_2017-18 | /Tasca_1_Python/src/exercici_3_python_v2.py | 315 | 3.953125 | 4 | def num_xifres_sequencial(numero):
return len(str(numero))
while True:
try:
numero = int(input("Introdueix un número: "))
print("Número sequencial: " + str(num_xifres_sequencial(numero)))
break
except:
print("El valor introduït ha de ser un número enter")
|
2516a11d2a26ef6ba002de152d1942dee50381c5 | MargaritaPopova/OTUS | /lesson6_OOP/Car.py | 1,646 | 3.703125 | 4 | from .bases import Vehicle
from inspect import currentframe
class Car(Vehicle):
def __init__(self, weight, capacity, tank):
super().__init__(weight, capacity, tank)
self.weight = weight
self.capacity = capacity
self.tank = tank
self.fuel = 0
def get_gas(self, add):
... |
c28356275fffbb60435108d7c8ab4709f1d4ac6c | typemaster007/mesos-assignment | /fibonacci.py | 996 | 3.671875 | 4 | from __future__ import print_function
import random
import time
#Section to create and store 100 random integers
numfile = open("fibo.txt", "w")
for i in range(100):
line = str(random.randint(1,100)) + '\n'
numfile.write(line)
#print(line)
numfile.close()
id = random.randint(1500,1999)
#Section to calcul... |
c4ee42ccb8d73c5330c3fee378a6e84eb26b9e9c | armossss/Requests1 | /demo9.py | 664 | 3.6875 | 4 | # 实现 输入文字即可百度翻译
import requests
import json
url = "http://fanyi.baidu.com/basetrans"
query_str = input('请输入你想翻译的文字')
data = {"query": query_str, "from": "zh", "to": "en"}
headers = {
"user-agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mob... |
c94fe10616b30c1291d5675772810fc0374fbc69 | KeithWilliamsGMIT/Emerging-Technologies-Python-Fundamentals | /03-fizzbuzz.py | 506 | 4.34375 | 4 | # Author: Keith Williams
# Date: 21/09/2017
# This script iterates between the numbers 1 and 100.
# For each iteration there is a condition for each of the following:
# 1) For numbers which are multiples of both three and five print "FizzBuzz".
# 2) For multiples of three print "Fizz".
# 3) For multiples of five print... |
560ba1c00dcb9eaec9d747f54876d1389dc74c2b | galaxy001/libtorrent | /python_BTL_BitTorrent-5.3-GPL/BTL/btl_string.py | 4,284 | 3.625 | 4 | # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# bu... |
115e333b783e5315e415d4b4f61d0e734808310c | galaxy001/libtorrent | /python_BTL_BitTorrent-5.3-GPL/BTL/circular_list.py | 5,354 | 3.5 | 4 | # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# bu... |
9b6f02c31e7263ceba596df256a1d8a6893109b5 | asinggih/CS-Review | /data-struct/Linked_List/Node.py | 196 | 3.625 | 4 | #!/usr/bin/env python3
class Node:
"""Node class to be used with Linked List"""
def __init__(self, value=None, next_node=None):
self.value = value
self.next = next_node
|
b8d7492c19dc1a012ab6cd29d395c38383283fdd | ashishc628/Spark_Foundation_Internship | /Task_1_Prediction using Supervised ML/app.py | 3,015 | 3.921875 | 4 |
import pickle
import streamlit as st
# loading the trained model
import pickle
import streamlit as st
pickle_in = open('regressor.pkl', 'rb')
regressor = pickle.load(pickle_in)
@st.cache()
#Importing All major libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
#Lo... |
f1621328203f355f6ba236bd40e53e73a32931e6 | FriendedCarrot4z/Final-Project-CSE-212 | /QueueMusicProblem.py | 2,908 | 3.515625 | 4 | import pygame
from pygame import mixer
pygame.mixer.init()
class Priority_Queue:
class Node:
def __init__(self, song, priority):
self.song = song
self.priority = priority
def __str__(self):
return "{} {}".format(self.song, self.priority)
def __init__(self)... |
a406961c86682d5d15c0b6eaa25a187a33a8ae59 | scoffers473/python | /uneven_letters.py | 564 | 4.28125 | 4 | #!/usr/bin/python3
"""
This takes an input word and prints out a count of uneven letters
for example in aabbc we have one uneven letter (c). In hello we have 3 (hme and o)
"""
import sys
from collections import Counter
def solution (S):
removal=0
counter = Counter(S)
for letters in S:
if count... |
680528fefc54b25668e4e7fdb1ebc2cfc752f1ff | scoffers473/python | /days_offset.py | 1,197 | 4.25 | 4 | #!/usr/bin/python3
"""
This take an input number and works out the offset day based on this number
Days are Mon:1
Tue:2
Wed:3
Thu:4
Fri:5
Sat:6
Sun:7
So if i passwd an offset of 7 this would be a Sunday, a 5 a Friday, a 13 a Saturday, etc
"""
import sys
def solu... |
312f47666b04f87e2128aabd6dc81d618c3ebf2f | JonathanLoscalzo/ml-courses | /DataCamp/case study: school budgeting/ch4-tips_tricks.py | 7,584 | 4.09375 | 4 | #
# text:
# NLP tricks
# - tokenize
# - include ngram, 1-ngram, 2-gram...
# e.g. CountVectorizer(ngram_range=(1,2))
# Import the CountVectorizer
from sklearn.feature_extraction.text import CountVectorizer
# Create the text vector
text_vector = combine_text_columns(X_train)
# Create the token pattern: TOKENS_ALPHANUM... |
1fec87de2253f29a48c52f975b535d2d6ec7778d | JonathanLoscalzo/ml-courses | /DataCamp/statistical_thinking/part_II/ch4.py | 5,843 | 3.59375 | 4 | # A/B testing
# he Civil Rights Act of 1964 was one of the most important pieces of legislation ever passed in the USA.
# Excluding "present" and "abstain" votes, 153 House Democrats and 136 Republicans voted yea.
# However, 91 Democrats and 35 Republicans voted nay.
# Did party affiliation make a difference in the ... |
43440e45c3d17d9036fabbf0ba0fb0bc441bb770 | JonathanLoscalzo/ml-courses | /DataCamp/supervised learning/ch4.py | 6,458 | 3.625 | 4 | ## Preprocessing Data
# Categorical Features
# - sklearn not accept them
# - need to encode numerically
# - dummy => col_value, col_value2, col_val3. OneHotEncoder or get_dummies
# >>> pd.get_dummies(df)
# - label => LabelEncoder
#######################
# Import pandas
import pandas as pd
# Read 'gapminder.csv' into ... |
e91139556aafc71675798d826d0adc8f7c0c50fd | Dylan-Barclay/hello_flask | /server.py | 998 | 3.578125 | 4 | from flask import Flask, render_template # Import Flask to allow us to create our app
app = Flask(__name__) # Create a new instance of the Flask class called "app"
@app.route('/') # The "@" decorator associates this route with the function immediately following
def index():
return "Hello World!"
@ap... |
dd66ea4df90875433d06fb5e991f6cf70a3b669b | sayamsingla2000/face-Recognition-using-openCV-and-keras | /opencv_2.py | 276 | 3.609375 | 4 | # Simple program to read and showw image
import cv2
img = cv2.imread('dog.png')
gray = cv2.imread('dog.png',cv2.IMREAD_GRAYSCALE)
cv2.imshow('Dog Image',img)
cv2.imshow('gray dog image',gray)
cv2.waitKey(0) #program will stop when any key is pressed
cv2.destroyAllWindowa() |
059075a5b5f47638333f016fa4676e2afcfe49b7 | vondirath/functions | /stock.py | 985 | 3.921875 | 4 | # This answer is incorrect because the highest stock price can come before the lowest
"""
stock_prices_yesterday = [10, 7, 5, 8, 11, 9]
def get_max_profit(array):
new_array = sorted(array)
var_1 = new_array[0]
var_2 = new_array[(len(new_array) - 1)]
return (var_1 - var_2)
get_max_profit(stock_prices... |
fb613d260b41cc384dd260f50a3cb3f9f67c36f9 | vondirath/functions | /testquestionplus.py | 1,438 | 3.703125 | 4 | import re
# making an empty template
list_content = """
<ul>
{list_item}
</ul>
"""
# this is a list accomidating for a good amount of edge cases
# for html and python.
list = ["this", "<h1>is</h1>", "a ", "list {list_content}(open_page() } \|"]
def format_list(list):
"""
formats a list by using pytho... |
bec46a0d962e5bc4521bc4ca4cadde19e7ac5f9f | tanayseven/algostructures-c | /algostructures/benchmark.py | 1,290 | 3.90625 | 4 | from random import randrange
from timeit import timeit
from typing import Generator
from algostructures.search import py_search, py_search_parallel
TIMEIT_REPS = 10
def random_int_generator(integer_digits: int) -> Generator[int, None, None]:
print(f"Generating {integer_digits} random numbers")
for _ in rang... |
51cbb9c63bdc3387100efd9c91a2b957a97e42d9 | puncharasx/100DaysOfCode | /Day1/Exercises/day-1-3-exercise.py | 92 | 3.8125 | 4 | # len is a function for get the length of a string
print(len(input("What is your name: ")))
|
8cf4923f3bb55e4ce4ab944ea7ec788415297366 | deepeshkumarsoni/Python_OOPs_Concepts | /class.py | 368 | 3.828125 | 4 | print('******** Welcome To The World Of CLASSES ********')
class abc:
a=100
def __init__(self):
print("Hii..Deepesh")
def abc(self,c):
self.b=200
self.d = self.a + c
print("Hello World",self.b,self.a,self.d)
def xyz(self):
print('hii',self.b,self.a,s... |
7f2ee46442ab635a448ae7663f01cc91dc6beffd | Hemangi3598/chap-7_p12 | /p12.py | 603 | 3.984375 | 4 | s1 = {10, 20, 30}
print(s1)
# add ele
s1.add(40)
print(s1)
s1.add(10) # sets are unique so it only shows one element at once
print(s1) # since 10 is already in set it will show 10 only once
s1.update([20, 50]) # update is to add more than one elements
print(s1)
# remove ele
s1.remove(20)
print(s1)
#s... |
73be7990bf805bb476d28d13a432d69cddc03de9 | shlokashah/Coding-Practice | /Linked Lists/Even Reverse.py | 698 | 3.828125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param A : head node of linked list
# @return the head node in the linked list
def solve(self, A):
odd = []
even = []
odd.append(A.val... |
d81f377decbf0bad61ea8635bdeee8c6a987913d | shlokashah/Coding-Practice | /Trees/Inorder without Recursion.py | 518 | 3.640625 | 4 | class Solution:
# @param A : root node of tree
# @return a list of integers
def inorderTraversal(self, A):
current = A
stack = []
answer = []
while True:
if current is not None:
stack.append(current)
current = current.left
... |
5967f3d5ba813f3b00b37e9b24eecfc841dffcb4 | shlokashah/Coding-Practice | /Trees/Kth Smallest Element in a BST.py | 489 | 3.609375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def inorder(self,root,l):
if root:
self.inorder(root.left,l)
l.append(root.val)
self.inorder(... |
b818a168172b797a021121cf62bbdb5b699ee8b3 | 07kamrul/Python-Interview-Questions | /Enumerate.py | 104 | 3.53125 | 4 | subjects = ('Python', 'Interview', 'Questions')
for i, sub in enumerate(subjects):
print(i, sub) |
757645a0b3c42742b439ac4e91d5ba98989190a1 | ashuChufamo/DSP-in-python | /lab/occurence_counter.py | 1,455 | 3.65625 | 4 | from threading import Thread, Lock
from queue import Queue
total_counter= 0
total_queue = Queue()
def count_word(filepath, search_word, l: Lock):
counter = 0
with open(filepath) as f:
for line in f.readlines():
for word in line.split():
if word.lower() == search_word:
... |
6d33e9ac7a2376e5e7e24546ef694329b7cc57b9 | sssschenyi/tools | /统计字符串出现的次数.py | 440 | 3.75 | 4 | # author: chenyi
# ide: notepad++
# date: 22:26 2022/10/11
#返回子字符串在字符串中出现的次数。
def fun():
s = "this is string example he"
sub ="x" # 查找的字符
# 调用函数只需要更改上面 2 个变量
### 下面不用改
n = 0
for i in s:
if sub == i:
n += 1
return n
# 查找单纯出现的次数
if __name__ == '__main__... |
a4c8465e93827e01a24113b0fe83a59d8bb2080f | Researchnix/6nimmt-python | /game/Field.py | 2,222 | 3.515625 | 4 | #
# Field.py
# 6nimmt
#
# Created by Lennart Doppenschmitt on 2016-08-06.
# Copyright 2016 Researchnix. All rights reserved.
#
class Field:
"""The field of cards on the table"""
cards = []
def initialize(self, initValues):
self.cards = []
for e in initValues:
... |
50a09255ba84d0302795b21176ebb4f3ab3d3340 | davide-serramazza/MLExam | /src/neuron.py | 3,321 | 4.09375 | 4 | import numpy as np
import sys
# superclass abstract Neuron
class Neuron(object):
""" Abstract Neuron class.
Its subclasses implements the activation function and its derivative.
Parameters
----------
len_weights : float
number of parameters attached to the neuron
Attributes
-----... |
0e55bc414b576a4a6962eaac939dd1709fcb04de | ksu-is/Congrats | /test_examples.py | 269 | 4.125 | 4 | # Python code to pick a random
# word from a text file
import random
# Open the file in read mode
with open("MyFile.txt", "r") as file:
allText = file.read()
words = list(map(str, allText.split()))
# print random string
print(random.choice(words)) |
96a7a8a7f3e46a3065fbcc167c7d152d314f3208 | welloworld/SecureMyTux | /GUI/tools/ps_by_user.py | 1,718 | 3.75 | 4 | import subprocess
#Ps only prints the first 7 characters of the username so this function is used to search for a username we want.
def get_shortened_username(s):
""" This function shortens a string which is supposedly a username into 7 chars long """
if(len(s) > 7):
return s[:7]
return s
def is_not_empty(s)... |
52a3d80f3e1525d278110631e2ce2e6d812c7af3 | a-dempsey/SocketProgramming | /UDPClientServer/UDPClient.py | 895 | 3.5 | 4 | # from the socket module import all
from socket import *
# Create a UDP socket
#(AF_INET is used for IPv4 protocols)
#(SOCK_DGRAM is used for UDP)
clientSock = socket(AF_INET, SOCK_DGRAM)
# get domain name of server.
domainName = getfqdn()
ip = gethostbyname(domainName)
server_address = (domainName, 6789)
## Create a d... |
5624c0729bf7b133db737cbee7c1c56e24f9beed | simonsirak/msc-complementary-labels | /src/scripts/generate_plots.py | 12,914 | 3.5625 | 4 | import matplotlib.pyplot as plt
import numpy as np
import os
from glob import glob
import json
import scipy.stats
import itertools
def mean_confidence_interval(data, confidence=0.95):
cis = []
for point in data:
a = 1.0 * np.asarray(point)
n = len(a)
m, se = np.mean(a), scipy.stats.sem(a)
h = se * s... |
eecc92e34b53b742ad762b394a64dfacece45eb1 | wuyouting/git21 | /python基础2/member.py | 158 | 3.53125 | 4 | #coding:utf-8
member = ['wu','yu','liu']
print raw_input('Enter your name:')in member
t1 = list('hello')
print type(t1)
print type('hello'.join('something')) |
0098fb641ff7df97e2e6864b13411383897ec3b9 | divyaparwani/PythonCodes | /one.py | 428 | 3.890625 | 4 | <<<<<<< HEAD
fname=input("enter the first name:")
lname=input("enter the last name:")
print("WElcome",fname,lname)
First line using file handling
this is file handling
omg so easy
=======
fname=input("enter the first name:")
lname=input("enter the last name:")
print("WElcome",fname,lname)
First line using fi... |
00f70327f5b9916fe3988f0065f0cd322f3c8e1f | lakowske/Craw | /Craw/PathBuilder.py | 513 | 3.625 | 4 | import os
class PathBuilder:
"""Constructs a sequence of paths at the given path directory with the given suffix"""
def __init__(self, path="./tmp/", suffix=".png"):
self.path = path
self.suffix = suffix
self.count = 0
#Construct the path if none exists
if not os.path.i... |
32942bc90a8076c79b01cc9c474a7cbf139c5a40 | gostephen/Data-Structures-and-Algorithms | /week 3/selection_sort.py | 293 | 3.734375 | 4 | def selection_sort(l: list):
for i in range(0, len(l) - 1):
lowest = l[i]
for j in range(i + 1, len(l)):
store = l[i]
if l[j] <= lowest:
lowest = l[j]
ind = j
l[i] = lowest
l[ind] = store
return l
|
54d2704bab5d490b03c9ca58c3c35a1f58cdbcd7 | JRaketa/OOP-projects | /OOP projects/tic_tac/tic_tak.py | 14,179 | 4.25 | 4 | import random
import time
class Player:
"""Class that represents a player of the game.
The player can be a human or the computer. The human player is a real player
that is supposed to make move by typing it in the terminal. The computer
player makes random move.
Attributes:
is_human (bool... |
066c63ba14d356f768062a9793aea1aad44f4812 | ddhorstman-lambdaschool/cs-module-project-hash-tables | /hashtable/hashtable.py | 9,552 | 3.671875 | 4 | class HashTableEntry:
"""
Linked List hash table key/value pair
"""
def __init__(self, key, value, next_=None):
self.key = key
self.value = value
self.next = next_
def __str__(self):
return f"[{self.key}]: {self.value}"
def __repr__(self):
return f"<Has... |
8ddc3b5eee33c50ded6932f27b76d6d538bdcbb7 | samantha/Python-Programming-I | /Assignments/Assignment4_spell_checker.py | 2,504 | 4.03125 | 4 | '''
Created on Apr 25, 2018
@author: Samantha Hangsan
Assignment: 4
SPECS:
- Develop spell checker program that spots and identifies misspelled words in a file
- Prompt the user to enter a word and it should report the number of times the word appeared in the file
'''
import string
def read_reference():
ref... |
59d3b37dae44cc0d229a41f827fb3ebced126fd7 | gwstudy/MCTS-agent-python | /gamestate.py | 7,982 | 3.53125 | 4 | from numpy import zeros, int_
from unionfind import UnionFind
from meta import GameMeta
class GameState:
"""
Stores information representing the current state of a game of hex, namely
the board and the current turn. Also provides functions for playing game.
"""
# dictionary associating numbers wit... |
fa253171ccc7abee641a7c5d55dea1ea727abff5 | SathvikPN/Algorithmic-Toolbox | /Dynamic-Programming/Money-Change-Min-coins.py | 1,257 | 3.796875 | 4 | # Uses python3
import sys
from math import lcm
def get_change(m): #m==money
#write your code here
LCM = lcm(1,3,4) #LCM of denominations available
''' Safe whole number and it's least coins is with biggest denomination'''
safeCoins = (m//LCM)*3
print(f'safeCoins {safeCoins} of [Rs.4]')
remainin... |
3356632c7e8883a485f44676d4a9d5189b5ce648 | airtonsiqueira/python-safaribooks-exercises | /Introduction to Python/Exercises/Jeopardy/category_clues.py | 680 | 3.8125 | 4 | import sqlite3
# Settings
db = "Jeopardy/jeopardy.db"
connection = sqlite3.connect(db)
cursor = connection.cursor()
# Queries
query1 = "SELECT id, name FROM category ORDER BY RANDOM() LIMIT 1"
query2 = """SELECT text, answer, value FROM clue where category=%d ORDER BY value"""
cursor.execute(query1)
result... |
b4b3853c5184a5fbf5847a1b681a683a815fa0af | airtonsiqueira/python-safaribooks-exercises | /Introduction to Python/Exercises/Jeopardy/categories.py | 307 | 3.640625 | 4 | import sqlite3
connection = sqlite3.connect('Jeopardy/jeopardy.db')
# Necessita de um cursor pra executar as queries
cursor = connection.cursor()
cursor.execute('SELECT name FROM category LIMIT 10')
results = cursor.fetchall()
for result in results:
print(result[0])
connection.close()
|
466c60c427aabd984133fc8bc0faf990bc6d5b27 | lttviet/py | /list/reorder_false_true.py | 575 | 4 | 4 | from typing import List
def reorder_false_true(lst: List[bool]) -> List[bool]:
"""Reorder a list of booleans to have false first.
"""
# lst[:f] false
# lst[f:t] unclassified
# lst[t:] true
f, t = 0, len(lst)
while f < t:
if not lst[f]:
f += 1
else:
t ... |
3b4d4944bfe4a170225e0d213f327c89d890905d | lttviet/py | /bitwise/count_bits.py | 337 | 4.15625 | 4 | def count_bits(x: int) -> int:
"""Returns the number of bits that are 1.
"""
num_bit: int = 0
while x:
# if odd, right most bit is 1
num_bit += x & 1
# shift to the right 1 bit
x >>= 1
return num_bit
if __name__ == '__main__':
for i in (1, 2, 11):
print(... |
f9dc3a14e8a338aa0fef73b7f4cf6858131b42a1 | lttviet/py | /list/update.py | 819 | 3.75 | 4 | from typing import List
def update(lst: List[int], m: int) -> List[int]:
"""Given an ordered list, positive int m, update the list so
if x appears m times in original list, x will show up min(2,m) in returned list
ex. update([10,10,10], 2) -> [10,10]
update([10,10,10], 1) -> [10]
updat... |
c99ca844f345de4ff03a8ce913ea3d9e26761cd9 | TITANS-Code-Base/Python_Contact_App_Javid | /Test_App/main.py | 1,428 | 3.953125 | 4 | from service import delete_one
from service import add_person, show_all, select_and_list, update_record
texts={
"greeting":"Welcome!",
"intro":"This is software for saving contacts. Please, choose the action for the next step: Press 1 to add new contact, 2 in order to view contacts, 3 to delete one of them, 4... |
457145e366910dd4fc557f134838f07dfa1f2c39 | davestarling/Project-Euler---Hadoop | /problem1/mapper.py | 700 | 4.03125 | 4 | #!/usr/bin/env python
"""Project Euler - project 1 - Hadoop version (mapper)
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000."""
import sys
def read_input(file):
for line in f... |
e94b9d1fc068718f960bfed4819124f379f199fc | h3nok/MLIntro | /Algorithms/Sorting/search_algorithms.py | 1,185 | 3.75 | 4 | def linear_search(data, item):
index = 0
found = False
while index < len(data):
if data[index] == item:
found = True
else:
index += 1
return found, index
def binary_search(data, item):
first = 0
last = len(data) - 1
found = False
while fir... |
4d48b79254926662c06f587c1b0e81d24b36fc81 | denisdenisenko/job_codewars_practice | /the_boolean_order.py | 1,313 | 3.984375 | 4 | """
In this Kata, you will be given boolean values and boolean operators.
Your task will be to return the number of arrangements that evaluate to True.
t,f will stand for true,
false and the operators will be Boolean AND (&), OR (|), and XOR (^).
For example, solve("tft","^&") = 2, as follows:
"((t ^ f) & t)" = True... |
6432ac3a35ffb6cc04cb48647a93bf04e86a1264 | BettyAtt/pands-problem-sheet | /secondstring.py | 370 | 3.96875 | 4 | # This program asks user to input a string
# and outputs every second letter in reverse order
# Author: Betty Attwood
# asks user to input a string
rawString = input("please enter a sentence:")
# start and end are blank which means default
# (0 and length of string)
# step is every second character
# negative means ... |
4e29a7a99a9e1c9d19756a5ca74ea505ecb01fb2 | FrEsHuUx/WD.162643 | /L2/Zad2.10.py | 140 | 3.71875 | 4 | try:
a = int(input("Enter a number: "))
print("Your number:", a)
except ValueError:
print("Please input a number, not a symbol") |
f8fa3a6cc579207a87fe0e826393b82b32af70fb | FrEsHuUx/WD.162643 | /L2/L2.6.py | 243 | 3.828125 | 4 | a = input('wprowadz liczbe a: ')
b = input('wprowadz liczbe b: ')
a = int(a)
b = int(b)
if a > b:
print('liczba ' + str(a) + ' jest wieksza')
elif a < b:
print('liczba ' + str(b) + ' jest wieksza')
else:
print("liczba sa rowne")
|
fe5e14bc9252555917db8050fcc05cace1eec5eb | FrEsHuUx/WD.162643 | /L3/Zad3.5.py | 118 | 3.5 | 4 | def trapez(a=0, b=0, h=0):
return (a+b)*h/2
print(trapez())
print(trapez(8, 6, 4))
print(trapez(b=6, a=8, h=4))
|
503b73134fb3266f8e89b3a5d52f031914b473d7 | hendrykosasih/workshop1404 | /Workshop6/doFromScratch.py | 367 | 3.875 | 4 | dictionary = {}
text = "this is a collection of words of nice words this is a fun thing it is"
listings = text.strip().split()
for each in listings:
if each in dictionary:
dictionary[each] += 1
else:
dictionary[each] = 1
sorted_keys = sorted(dictionary)
for each in sorted_keys:
print("{:... |
1e6bdb702d369780dcce5aea6f3ea1e85b0d8483 | hendrykosasih/workshop1404 | /Workshop1/bmiCalc.py | 255 | 4.09375 | 4 | print('Body-mass-index calculator, by Jason')
weight = float(input('Please enter your weight in kgs: '))
height = float(input('Please enter your height in m: '))
BMI = weight / height**2
print('Therefore, your BMI value is: ', BMI)
print('Thank you!')
|
85bf41014bd34d37c5b8a2e0d0ffbd36ddd66c21 | halfcress/Hackerrank_30_days_of_code | /025_Running_Time_and_Complexity.py | 715 | 3.9375 | 4 | """import sympy
n = input()
n = int(n)
l = []
for _ in range(n):
l.append(int(input()))
for i in l:
x = sympy.isprime(i)
if x:
print("Prime")
else:
print("Not prime")""" # Best solution. But hackerrank not support sympy library.
for _ in range(int(input())): #Witho... |
d7f5cb936d73123fa5620736ac34d785aada23f5 | halfcress/Hackerrank_30_days_of_code | /021_Generics.py | 940 | 3.984375 | 4 | #Non python question.
def NonPython(xd):
return xd
"""
Objective
Today we're discussing Generics; be aware that not all languages support this construct, so fewer languages are enabled for this challenge. Check out the Tutorial tab for learning materials and an instructional video!
Task
Write a single gen... |
99e2a47e1350d6fdc0f4d91656d12e62026461ff | kivzcu/heatmap.zcu | /modules/crawler/Utilities/helpers.py | 790 | 4.09375 | 4 | from typing import Dict
SKIP = "SKIP"
UNKNOWN = "UNKNOWN!"
def should_skip(device: Dict[str, str]) -> bool:
return device['x'] == SKIP or device['y'] == SKIP or device[
'x'] == UNKNOWN or device['y'] == UNKNOWN
def detect_change(first: Dict[str, str], second: Dict[str, str],
compareKe... |
d63041555035f5a167cd025661e3f378e47b77e7 | kivzcu/heatmap.zcu | /modules/crawler/DatasetProcessing/WIFI_processor.py | 1,352 | 3.53125 | 4 | from Utilities.CSV import csv_data_line
from Utilities import date_formating
from shared_types import DateDict
def process_file(filename: str) -> DateDict:
"""
Method that take path to crawled file and outputs date dictionary:
Date dictionary is a dictionary where keys are dates in format YYYY-mm-... |
12e955d8ab0eaafc1c04e0e5075df3cadccb9718 | BinYuOnCa/Algo-ETL | /Assignment3_Optimization/Yifan_Fan/pso_fun.py | 7,663 | 3.765625 | 4 | """
This script is to build the related function of Particle Swarm Optimization.
"""
import numpy as np
def pso_min(func_eva, low_bd, up_bd, cons=None,
swarm_size=100, gen_max=100, min_diff=1e-8,
c1_init=3, c1_final=1.5, c2_init=3, c2_final=2.5,
random_seed=None, show_result=False... |
abd463e653968f68a5f38762be23f2a4cd9b193b | BinYuOnCa/Algo-ETL | /Assignment2-Stat/zhangsongbin/assginment2_4.py | 1,217 | 3.6875 | 4 | """4. Take 10 stocks in S&P500 and collect daily close price from 2020-06-01 to 2020-12-31 for selected stocks.
(1) ) Calculate daily return (return = log(today close/previous close)) for each of 10 stocks [5 points]
(2) Run PCA on calculated daily return and find the first principal component. [15 points]
(3) Plot fir... |
21a5df59ae8d052bf1879305fc8d03df6e53999b | AbhishekVarshney98/Hactoberfest2020-1 | /sub2no.py | 118 | 3.859375 | 4 |
print("Give two numbers :")
a = int(input("Enter 1st number"))
b = int(input("enter second number"))
print(a-b)
|
d0cc73494c0ed0965cc4ebf6fe15642cb6c1813c | alexttyip/advent-of-code-2020 | /day02/day2.py | 1,436 | 3.546875 | 4 | def part1():
f = open("input.txt", "r")
count = 0
for line in f:
lower = int(line[0: line.index("-")])
upper = int(line[line.index("-") + 1: line.index(" ")])
char = line[line.index(":") - 1]
string = line[7:]
char_count = 0
for c in string:
... |
846d3c5dc83b78f19e7086b9d094c247b9ed5544 | maliha-chaity/Deep-Learning-Projects | /Image Classification CIFAR10/image_classification_cifar10.py | 2,941 | 3.625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
# Load the dataset from keras datasets module
from keras.datasets import cifar10
import matplotlib.pyplot as plt
(train_X,train_Y),(test_X,test_Y)=cifar10.load_data()
# In[3]:
# Plot some images from the dataset to visualize the dataset
n=6
plt.figure(figsize=(2... |
6ac444c19c446145da4edf9e2006d89c6e5080eb | dpruitt/Python-Crash-Course | /Chapter 5/favorite_fruit.py | 433 | 4 | 4 | favorite_fruits = ["strawberry", "pineapple", "orange"]
if "strawberry" in favorite_fruits:
print("You really like strawberries.")
if "banana" in favorite_fruits:
print("You really like bananas.")
if "orange" in favorite_fruits:
print("You really like oranges.")
if "blueberry" in favorite_fruits:
pr... |
8a09957117d06be0089b7ddbb3f9bcccbe9ca38e | dpruitt/Python-Crash-Course | /Chapter 9/lottery.py | 224 | 3.5 | 4 | import random
lottery = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e"]
winner = ""
for x in range(0, 4):
winner += str(lottery[random.randrange(0, 15)])
print(f"The winning lottery combination is {winner}.")
|
255b8406791e1786a69d14969065bb18b79ff1bc | dpruitt/Python-Crash-Course | /Chapter 9/three_restaurants.py | 539 | 3.609375 | 4 | class Restaurant:
def __init__(self, name, cuisine_type):
self.name = name
self.cuisine_type = cuisine_type
def describe_restaurant(self):
print(f"Name: {self.name} \nCuisine Type: {self.cuisine_type}")
def open_restaurant(self):
print(f"{self.name} is open!")
ravioli = R... |
54d1b55ba4bc3016344bf4d709daa22dc974f92c | dpruitt/Python-Crash-Course | /Chapter 6/people.py | 494 | 3.65625 | 4 | people = {
"dpruitt": {
"first_name": "Dylan",
"last_name": "Pruitt",
"age": 27,
"city": "Lansing"
},
"jbrown": {
"first_name": "Jack",
"last_name": "Brown",
"age": 33,
"city": "Grand Rapids"
},
"jbourne": {
"first_name": "Jason... |
9f809de66b0ba7123027bc5e8c42cf40d72de9ad | bowles123/CS-3430-Projects | /Assignment 7/Assignment7_server.py | 1,737 | 3.859375 | 4 | # Brian Bowles, Assignment 7, March 3, 2015.
import socket
import random
from math import exp
# Returns true if the given number is prime, false otherwise.
# num_trials defaulted to 50 because that seems to give me
# the most accurate answer.
def is_fermat_prime(num, num_trials = 50):
if num == 1:
return F... |
9499c7681a67ea097c75eb27ada5d3e2e95120da | prasadyacham/BackendAutomation | /MatchingECNPartyAddandDemoStep1.py | 1,082 | 3.578125 | 4 | # Step 1: Script to find matching ECNs between PartyAddress and Demographics
PartyAddress = {}
with open("C:\\Users\\Prasad.Yacham\\PartyAddress.txt", "r") as fs1:
for line in fs1:
currentlinef1 = line.split("|")
PartyAddress[currentlinef1[0]] = currentlinef1[0] + '|' + currentlinef1[7] + '|' + cur... |
564fd10f1bc602dadd6ae3272a86b38c3bde050b | f1lm/MS-2014-Boise-State-University | /Programming Languages/pub/sum/python/sum | 142 | 3.828125 | 4 | #!/usr/bin/python
# Python sum program
def sum(seq):
s=0
for v in seq:
s+=v
return s
seq=[5,6,1,8,3,7]
print sum(seq)
|
bebe7d331b8e35f90d78592982703d3c480d3d31 | Kasden45/Genetic-algorithm | /Generator.py | 6,281 | 3.875 | 4 | import math
import random
import time
from Individual import Individual
from Point import Point
from Segment import Segment
from Trace import Trace
def point_out_of_bounds(point, board):
"""
Checks if point is out of the board and
:param Point point: point to be checked
:param PCB_Board board: board o... |
2f70d61d5938d5fdfec145555bf36e1bbebb3438 | zhxjenny/SoftTest | /preview-exercise/ex19.py | 659 | 3.59375 | 4 | def cheese_and_crackers(cheese_count, boxes_of_crackers):
print "You have %d cheeses!" %cheese_count
print "You have %d boxes of crackers!" % boxes_of_crackers
print "Man that's enough for a party!"
print "Get a blanket. \n"
print "We can just give the function numbers directly:"
cheese_and_crackers(20,30)
print... |
3d6e9e17d87245281cc06c924b4c05ef4c39defd | zhxjenny/SoftTest | /preview-exercise/ex24.py | 888 | 3.71875 | 4 | print "Let's parctice everything."
print 'You\'d need to know \'bout escapes with \\ that do \n newline and \t tabs.'
poem ="""
\t The lovely world
with logic so firmly planted
cnanot discern \n the needs of love
nor comprehend passion from intuition
and reguires an explanation
\n\t\t where there is none.
"""
print "-... |
b81c76ba7cc637017c0432b6d9b0e527cd624fd3 | tvanrijsselt/file-renamer | /main.py | 1,058 | 4.15625 | 4 | """This main module calls the helper functions in the main-function, such that the right files in the right folder are changed."""
import os
from helperfunctions import ask_input_for_path, ask_input_base_filename, files_ending_with_chars
def main():
"""Main function to call the helper functions and
rena... |
f7b6a5a3cd40b846eb218913241d34d55238a302 | GianCarloMilanese/travelling_santa_metaheuristics | /sa.py | 6,919 | 3.5625 | 4 | import numpy as np
def shift_mutation(perm):
"""
Performs a shift mutation on a permutation
"""
n = len(perm)
i = np.random.choice(n, 2, replace = False)
i = np.sort(i)
i0 = i[0]
i1 = i[1]
perm = np.concatenate((perm[i1:], perm[i0:i1], perm[:i0][::-1]))
return perm
def swap_m... |
7469ad0ca4ae0019f1b76e2977bbb7beb72cadf5 | dave45678/PythonFundamentals | /Last Class/Zork/Zork.py | 3,157 | 3.90625 | 4 | import random as rnd
bailout = False
room = 1
print('Welcome to Zork\'s Haunted House')
while not bailout:
#print("Room is " + str(room))
#print("bailout is " + str(bailout))
# You are in the foyer
if room == 1:
print ("You are standing in the foyer of an old house.")
print ("You se... |
c26892b9e1d1563481e86a4c9595cf5fc8034ece | rutaks/Python_Algorithms | /create_phone_number.py | 767 | 4 | 4 | # A Function that accepts an array of 10 integers (between 0 and 9),
# that returns a string of those numbers in the form of a phone number.
# eg: [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] ==>> (123) 456-7890
def create_phone_number_1(n):
phone_number = '('
count = 1
if(len(n) == 10):
for i in n:
... |
5bbbe55fc122e6b69b879735cc8d9a31883cb44e | LukeSlev/Database_Info_Retrieval | /src/Master/termSearch.py | 1,132 | 3.5 | 4 | from bsddb3 import db
def termSearch(searchTerm):
DB_File = "te.idx"
database = db.DB()
database.set_flags(db.DB_DUP) #declare duplicates allowed before you create the database
database.open(DB_File,None, db.DB_BTREE, db.DB_CREATE)
curs = database.cursor()
resultSet = set()
# print(searchT... |
36de0e113b9bd78d42ec503d5a01d609e97ba64b | lfzyx/hello-Python | /list_files_by_days.py | 1,188 | 3.5 | 4 | #!/usr/bin/env python3
# Author: lfzyx
# Contact: lfzyx.me@gmail.com
"""
list files by days to days
import list_files_by_days
list_files_by_days.filelist(3 20 Downloads/*)
"""
import datetime
import os.path
import glob
import sys
def days(firstday, lastday):
"""
return the day in datetime.date format (year,... |
cdf2f6746d56e08bb55c4ef9d02e2a0e12aa6a54 | martin-porra/ejercicio8unidad3 | /main.py | 2,416 | 3.578125 | 4 | from manejadorempleados import manejador
from login import login
from ingerente import IGerente
from itesorero import ITesorero
def menu():
print('1 - agregar horas de trabajo de un empleado contratado')
print('2 - ver costo total de una tarea')
print('3 - lista de todos empleados que recibiran la ayuda')
print('4... |
abe207840ab46d6d86ded4c6cf7e79f2d11695a2 | ahathe/some-a-small-project | /MyPython/Dict/isprime.py | 327 | 3.890625 | 4 | #!/usr/bin/env python
def isprime(prime):
if prime == 1:
print 'False'
else:
for each in range(2,prime):
if prime % each == 0:
print 'False'
break
else:
print 'True'
break
try:
get = int(raw_input("input you number,must be number:"))
isprime(get)
except ValueError:
print 'must be number,... |
8abfa85407965a6e86e4e0207906df85b3f514fd | ahathe/some-a-small-project | /MyPython/Dict/FBNQ.py | 351 | 3.671875 | 4 | #!/usr/bin/env python
def run(num):
a = 1
b = 1
c = num / 2
d = num % c
if d == 1:
c = c + d
while c > 0:
print a
print b
a = a + b
b = a + b
c -= 1
if c == 1:
print a
break
else:
while c > 0:
print a
print b
a = a + b
b = a + b
c -= 1
get1 = int(raw_input("get ... |
02dbaffb13e9d4a386d3cc097ff338526538cdb9 | ahathe/some-a-small-project | /MyPython/Dict/HumanResources.py | 308 | 3.859375 | 4 | #!/usr/bin/env python
db = {}
print 'only can input ten key and value'
while True:
key = raw_input("input you employee name:")
value = raw_input("input you employee number:")
db[key] = value
length = len(db)
if length >= 10:
break
print 'employee name and numbers~'
for x in db.keys():
print db[x]
|
3c75087082521aed080ba91e45b066745e3e78d7 | ahathe/some-a-small-project | /MyPython/Dict/DictLogin.py | 3,362 | 3.5 | 4 | #!/usr/bin/env python
import time
import crypt
import Tkinter
import string
string = string.punctuation + string.whitespace + ' '
db = {}
log = {}
def showuser():
print 'All User And Passwd Is Here! '
for x in db.items():
print x
def deluser():
prompt = 'Input You Want To Del That User: '
name = raw_inpu... |
cf0b9f410f42bd4bf841af70a4aedf7c7638bf92 | ahathe/some-a-small-project | /MyPython/test/Rochambeau.py | 435 | 3.640625 | 4 | #!/usr/bin/env python
import random
while True:
rock = random.randint(0,10)
scissor = random.randint(0,10)
paper = random.randint(0,10)
dirc = {'rock':rock,'scissor':scissor,'paper':paper}
def Total(one,two):
if rock > scissor:
You_Input = raw_input("Tom input you choice!,rock,paper,scissors!:")
Other = raw... |
1c7f4931194d84e23de46b72744f4dc012e6199c | ahathe/some-a-small-project | /MyPython/Dict/FistName.py | 569 | 3.84375 | 4 | #!/usr/bin/env python
list2 = list()
def Fname(num):
count = 0
num1 = 0
while count < num:
ge1 = raw_input("input you name last name , first name:")
if ',' in ge1:
list1 = ge1.split(',')
list2.append(list1)
elif ',' not in ge1:
num1 += 1
print 'you have done this %s time already.fixing input..' % ... |
caedf25abc2fcbb1677d8743b9f50e254447bdd9 | ahathe/some-a-small-project | /MyPython/test/StrBecome.py | 320 | 4.15625 | 4 | #!/usr/bin/env python
'make string become largest to smallest orade! '
num = list(raw_input("plaese input number!thank you!:"))
choice = raw_input("input you choice!,one or two:")
one = 'one'
two = 'two'
if choice == one:
num.sort()
print num
elif choice == two:
num.sort()
for x,i in enumerate(num):
print x,i
|
f24817dc2ad44edbe7a094542da901122c7b941c | ahathe/some-a-small-project | /MyPython/test/Count.py | 229 | 4.3125 | 4 | #!/usr/bin/env python
def Count(count):
if ' ' in count:
count = count.split(' ')
lisT = ['+','-','*','/','%','**']
if count[1] in lisT:
Input = raw_input("input you want to count number and operator!:")
Count(Input)
|
0e3ebeca726b741e3773052133b4756e4cd6dcf7 | ahathe/some-a-small-project | /MyPython/somePy/count.py | 75 | 3.84375 | 4 | num = raw_input("input you number please:")
num = int(num)
print num * num
|
950c8785a6fe4cec2e491a1e1ca90a1651cae86d | ahathe/some-a-small-project | /MyPython/test/NumTest.py | 1,626 | 4.25 | 4 | #!/usr/bin/env python
'is input number to count mean and total'
empty = []
def Input():
while True:
num = raw_input("input you number to count mean!,input 'q' is going to quit!:")
if num == ('q' or 'Q'):
print 'rechoice input type,input or to count or remove or view!'
Choice()
else:
try:
number ... |
47b4ad4bbfc6171aae62bf79efe5e706b95387e9 | ahathe/some-a-small-project | /MyPython/Class/LIFO.py | 683 | 3.953125 | 4 | #!/usr/bin/env python
class LIFO(object):
def __init__(self):
self.lifo = []
def push(self):
while True:
Getin = raw_input('not empty to input you want to push thing:')
if not Getin:
break
self.lifo.append(Getin)
def pop(self):
while True:
Getout = raw_input('(pop) to out you thing:')
if ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.