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 |
|---|---|---|---|---|---|---|
394529d04bd7be33bf77db2a9c9eb43d0152dea3 | green-fox-academy/ZaitzeV16 | /python_solutions/week-01/day-4/average_of_input.py | 340 | 4.15625 | 4 | # Write a program that asks for 5 integers in a row,
# then it should print the sum and the average of these numbers like:
#
# Sum: 22, Average: 4.4
_sum = 0
number_of_inputs = 5
for i in range(number_of_inputs):
_sum += int(input("number {}: ".format(i + 1)))
print("sum: {}, average: {:.1f}".format(_sum, _sum /... |
eb033baa7c58e4528405cb1df6726cfc79250f74 | green-fox-academy/ZaitzeV16 | /python_solutions/week-01/day-4/one_two_a_lot.py | 472 | 4.09375 | 4 | # Write a program that reads a number form the standard input,
# If the number is zero or smaller it should print: Not enough
# If the number is one it should print: One
# If the number is two it should print: Two
# If the number is more than two it should print: A lot
user_input = int(input("ya numma: "))
if user_in... |
6cef60c67ed6680f4649a9aa9223ad38793d6f72 | green-fox-academy/ZaitzeV16 | /python_solutions/week-02/day-1/functions/greet.py | 356 | 4.28125 | 4 | # - Create a string variable named `al` and assign the value `Green Fox` to it
# - Create a function called `greet` that greets it's input parameter
# - Greeting is printing e.g. `Greetings dear, Green Fox`
# - Greet `al`
al = "Green Fox"
def greet(name: str):
print("Greetings dear, {}".format(name))
if __... |
36ae7ea8ec3b65d1a9060aacf1e1c1d42d9e69ab | green-fox-academy/ZaitzeV16 | /python_solutions/week-01/day-4/draw_chess_table.py | 316 | 3.609375 | 4 | # Crate a program that draws a chess table like this
#
# % % % %
# % % % %
# % % % %
# % % % %
# % % % %
# % % % %
# % % % %
# % % % %
for i in range(8):
if i % 2 == 0:
message = "{1}{0}{1}{0}{1}{0}{1}{0}"
else:
message = "{0}{1}{0}{1}{0}{1}{0}{1}"
print(message.format(" ", "%"))
|
980ae2df756e67e10c9474c07a5ad3dd54eda733 | takwas/python_dev | /PalindromeChecker.py | 988 | 4.09375 | 4 |
import sys
from math import ceil
# Checks if a given word is palindromic or not
# accepts a word from the user, to process
def get_word():
word = raw_input("Please type in a word for me to process (and hit ENTER)");
return word
# checks if two given letters are the same
# returns True if so; False otherwise
def... |
d591cbf39e6a63369d5c674941a8994c8d87ffd3 | vincentt117/coding_challenge | /lc_merge_sorted_array.py | 1,577 | 4.125 | 4 | # Merge Sorted Array
# https://leetcode.com/explore/interview/card/microsoft/47/sorting-and-searching/258/
# Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
# Note:
# The number of elements initialized in nums1 and nums2 are m and n respectively.
# You may assume that ... |
ac09a950b5927bbd0190b730f40ba8552e5e9a64 | vincentt117/coding_challenge | /lc_prisoners_after_n_days.py | 567 | 3.53125 | 4 | # https://leetcode.com/explore/challenge/card/july-leetcoding-challenge/544/week-1-july-1st-july-7th/3379/
# Optimal solution
# Used solutions
class Solution:
def prisonAfterNDays(self, cells: List[int], N: int) -> List[int]:
if N == 0:
return cells
repeat = {}
for i in range(1, ... |
be2c7f6a145abfe0439bf23df7179e9709fa30da | vincentt117/coding_challenge | /lc_remove_nth_node_from_end_of_list.py | 1,119 | 3.78125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
if not head.next:
... |
8f9fb85bd42b6d698e8e63afad3cce780fb132ad | vincentt117/coding_challenge | /lc_hammering_distance.py | 570 | 4.0625 | 4 | # https://leetcode.com/problems/hamming-distance/description/
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
binX = ""
binY = ""
hammerDist = 0
while x or y:
if x % 2 != y % 2:
hammerDist += 1
x //= 2
y //= 2
re... |
408bc420d3940ebec879db933c3974ebd0fb3ec3 | vincentt117/coding_challenge | /newtons_method_for_sqrt.py | 202 | 3.671875 | 4 | # From: https://stackoverflow.com/questions/15390807/integer-square-root-in-python
def isqrt(n):
x = n
y = (x + 1) // 2
while y < x:
x = y
y = (x + n // x) // 2
return x |
2d8988baedd00b46718268d1b13aaa05a908dd44 | vincentt117/coding_challenge | /lc_power_of_three.py | 659 | 4.1875 | 4 | # 326. Power of Three
# https://leetcode.com/problems/power-of-three/description/
# Given an integer, write a function to determine if it is a power of three.
# Example 1:
# Input: 27
# Output: true
# Example 2:
# Input: 0
# Output: false
# Example 3:
# Input: 9
# Output: true
# Example 4:
# Input: 45
# Output: ... |
d2f94f7c22721ca6909d48cc37915cab014ddec9 | vincentt117/coding_challenge | /lc_odd_even_linked_list.py | 1,152 | 4 | 4 | # https://leetcode.com/problems/odd-even-linked-list/description/
def oddEvenList(head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next:
return head
oddTail = head
evenHead = head.next
evenTail = head.next
oddTail.next = head.next.next
... |
efacfad1fcb39b7dcbb4dd612eb47e8467c4bf73 | vandeldiegoc/holbertonschool-higher_level_programming | /0x0B-python-input_output/1-number_of_lines.py | 239 | 3.625 | 4 | #!/usr/bin/python3
"""module"""
def number_of_lines(filename=""):
"""return line number"""
line_number = 0
with open(filename) as readf:
for read_line in readf:
line_number += 1
return line_number
|
6361feb1a23baa39a7170a438e9b662a8143914f | tiredcoffee/Dialogue-Randomizer-CC | /listMapDirs.py | 1,402 | 4.03125 | 4 | import os
import pathlib
'''
For the given path, get the List of all files in the directory tree
'''
def getListOfFiles(dirName):
# create a list of file and sub directories
# names in the given directory
listOfFile = os.listdir(dirName)
allFiles = list()
# Iterate over all the entries
for entry in listOfFil... |
1dcf84afb413cad718459149f29b7eead1487950 | RevanthR/AI_Assignments | /assignment1.py | 703 | 3.703125 | 4 |
for num in range (1,30):
if num%5==0:
print(num)
population={"shangai":17.8,"istanbul":13.3,"karachi":13.0,"mumbai":12.5}
print(population)
animals = {'dogs': [20, 10, 15, 8, 32, 15], 'cats': [3,4,2,8,2,4], 'rabbits': [2, 3, 3], 'fish': [0.3, 0.5, 0.8, 0.3, 1]}
animals= {'dogs': [20, 10, 15, 8, 32, 1... |
d290e201bd2f17605c6702b8b8cb8dc4006c87b8 | duygugencdogan/Developer_Student_Club | /basithesapmakinesi.py | 547 | 3.53125 | 4 | #fonksiyonları oluşturmak
def toplama(param1, param2):
sonuc = param1 + param2
return sonuc
def cikarma(param1, param2):
sonuc = param1 - param2
return sonuc
def carpma(param1, param2):
sonuc =param1 * param2
return sonuc
def bolme(param1, param2):
sonuc = param1/param2
retur... |
4d4ca6e262a9c27c3a6bf4297d598eb0da2589cb | liangy2001/StockPricePrediction | /old_files/old_linear_models.py | 2,484 | 3.6875 | 4 | import numpy as np
class LinearRegression(object):
def __init__(self, eta=0.1, n_iter=50):
self.eta = eta # learning rate
self.n_iter = n_iter # iterations
def fit(self, X, y):
"""Model training"""
X = np.insert(X, 0, 1, axis=1) # insert x0 into the first column
se... |
e7a9d1610e56497af451d3601dc900f31c9c4797 | liupu126/project | /Scripts/python/download.bak.py | 495 | 3.8125 | 4 | #! python
"""
Download by line from text file:
Usage: download.py <download_list> <save_directory>
"""
import sys
import urllib
download_list = sys.argv[1]
save_directory = sys.argv[2]
with open(download_list,'r') as f:
urls = [line.strip() for line in f]
print(urls)
i = 0
for url in urls:
i = i + 1
... |
9281e896a60cfa26ef19185971c84b694854a02d | bingzhong-project/leetcode | /algorithms/symmetric-tree/src/Solution.py | 1,354 | 4.0625 | 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 isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
def symmetric(paths):
... |
38d97ada99cfa9a7a468e7a8cf592d2bf45184d2 | bingzhong-project/leetcode | /algorithms/convert-sorted-array-to-binary-search-tree/src/Solution.py | 654 | 3.75 | 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 sortedArrayToBST(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
def construct(array, lef... |
cbe7843c1643b59e8b1d7b679ae6786a5792963f | bingzhong-project/leetcode | /algorithms/add-two-numbers/src/Solution.py | 1,394 | 3.828125 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
res_node = None
node... |
2a4366765bc569e65d0ff45c8a1c159673d1f4b0 | bingzhong-project/leetcode | /algorithms/surrounded-regions/src/Solution.py | 1,021 | 3.609375 | 4 | class Solution:
def solve(self, board):
"""
:type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead.
"""
def dfs(board, i, j):
if i > len(board) - 1 or i < 0 or j > len(board[-1]) - 1 or j < 0:
return
... |
77fe9c46814a79e8d5e3221fa1be0d1eefe0491a | bingzhong-project/leetcode | /algorithms/queue-reconstruction-by-height/src/Solution2.py | 450 | 3.546875 | 4 | import collections
class Solution:
def reconstructQueue(self, people: 'List[List[int]]') -> 'List[List[int]]':
people_map = collections.defaultdict(list)
for p in people:
people_map[p[0]] += [p[1]]
height = sorted(list(people_map.keys()), reverse=True)
queue = []
... |
954dfe4a40ec6e992bcfe25662bb2776f81aea73 | bingzhong-project/leetcode | /algorithms/detect-capital/src/Solution.py | 559 | 3.671875 | 4 | class Solution:
def detectCapitalUse(self, word: 'str') -> 'bool':
def is_upper(word):
return ord(word) >= ord('A') and ord(word) <= ord('Z')
upper_count = 0
for s in word:
if is_upper(s):
upper_count += 1
if upper_count == len(word):
... |
e167d2cedecf91f435ff8d9c3f4182fd1242f9e2 | bingzhong-project/leetcode | /algorithms/validate-binary-search-tree/src/Solution.py | 731 | 3.9375 | 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 isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
def dfs(node, min_val, max_val):
... |
1856bfafa817a69ba9cbe6759bfae0c6c2c15dd6 | bingzhong-project/leetcode | /algorithms/reorganize-string/src/Solution.py | 1,006 | 3.625 | 4 | import collections
import heapq
class Solution:
def reorganizeString(self, S: str) -> str:
counter = collections.Counter(S)
heap = []
for string, count in counter.items():
heapq.heappush(heap, (-count, string))
res = ""
while heap:
count, string = he... |
00414bf31e9037322709f177f6f5bb4f42ce69e3 | bingzhong-project/leetcode | /algorithms/find-first-and-last-position-of-element-in-sorted-array/src/Solution.py | 948 | 3.625 | 4 | class Solution:
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
def search(array, target, start, end, result):
if start > end:
return
mid = int((start + end) / 2)
... |
725ef1417202095873e39fd87f075fc126c28b01 | bingzhong-project/leetcode | /algorithms/remove-duplicates-from-sorted-list/src/Solution.py | 559 | 3.75 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
node = head
pre_node = ListNode(-1)
... |
378c17f2f94c1d14c192a4c5b351770cfb6b34c1 | bingzhong-project/leetcode | /algorithms/base-7/src/Solution.py | 341 | 3.5 | 4 | class Solution:
def convertToBase7(self, num: 'int') -> 'str':
if num == 0:
return '0'
negative = num < 0
num = abs(num)
res = ""
while num != 0:
div, mod = divmod(num, 7)
res = str(mod) + res
num = div
return "-" + res ... |
d09f34004e14f8595e722e640cb84569729ab82b | bingzhong-project/leetcode | /algorithms/find-mode-in-binary-search-tree/src/Solution2.py | 1,270 | 3.640625 | 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 findMode(self, root: 'TreeNode') -> 'List[int]':
if root is None:
return []
self.prev_num = None
self.num_... |
23a875946858774b10646f90b06514ea9bd65c3d | bingzhong-project/leetcode | /algorithms/implement-rand10-using-rand7/src/Solution.py | 501 | 3.578125 | 4 | import random
def rand7(self):
return random.randint(1, 7)
class Solution:
def rand10(self):
"""
:rtype: int
"""
bin_str = ''
for _ in range(4):
bin_str += self.rand()
res = int(bin_str, 2)
return res if res > 0 and res <= 10 else self.rand... |
019380dd2589ebfd3d5f01dcd9a75d2e0fb4975d | bingzhong-project/leetcode | /algorithms/matchsticks-to-square/src/Solution.py | 727 | 3.546875 | 4 | class Solution:
def makesquare(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
def dfs(nums, sides, index=0):
if index == len(nums):
return True
for i in range(4):
if sides[i] - nums[index] < 0:
... |
40254374814f52d4665e36d3d87e0600ff7ce2b5 | bingzhong-project/leetcode | /algorithms/sort-list/src/Solution.py | 1,630 | 3.984375 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def sortList(self, head):
"""
归并排序
:type head: ListNode
:rtype: ListNode
"""
def middle(node):
slow = node
... |
f6069de39a257f7dfa45362e2524bd4fef106c78 | bingzhong-project/leetcode | /algorithms/two-sum-iv-input-is-a-bst/src/Solution.py | 1,117 | 3.796875 | 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 findTarget(self, root: 'TreeNode', k: 'int') -> 'bool':
def search(root, target):
if root is None:
return ... |
7e1a70390785938f7cf3c8dcb2a44158debb5ec5 | bingzhong-project/leetcode | /algorithms/subsets/src/Solution.py | 697 | 3.53125 | 4 | class Solution:
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
def dfs(nums, level, path, res):
if level == len(nums):
return
for i in range(len(nums)):
num = nums[i]
if n... |
b8485569fbb3eccc4f63a907af37d294ef5d8138 | RafaelAparecidoSilva/Projeto_Python_Security_DIO | /Desenvolvimento_Ferramentas/verificador_telefone.py | 259 | 3.59375 | 4 | import phonenumbers as ph
from phonenumbers import geocoder
# phone = input('Digite um número de telefone no formato "+551199998888": ')
phone = '+551239468908'
phone_number = ph.parse(phone)
print(geocoder.description_for_number(phone_number, 'pt'))
|
5d178f1286fc1507675365666a1497426e39f97d | Litox-x/itechart_studentslab | /homework4/iteration.py | 1,188 | 3.53125 | 4 | import numpy
import os
import math
class tribon:
def __iter__(self):
a=[0,0,1]
print(a[0])
print(a[1])
print(a[2])
k=3
while k<=35:
a[0],a[1],a[2]=a[1],a[2],a[1]+a[2]+a[0]
k+=1
yield a[2]
import math
class leib(... |
e4216a7f86a3d561a1d68240942799919fcb3e5b | MarketaR0/up_ii_calculator | /src/Calculator.py | 2,774 | 4.15625 | 4 | from src.FunctionManager import FunctionManager
from src.BasicFunctions import add, subtract, multiply, divide
# Runs the calculator.
def calculate():
func_manager = FunctionManager()
# Allows user to choose operation.
func_manager.show_functions()
user_choice = int_input(len(func_manager.functions))... |
bd16526e8c4f22f16c2c913cbebdda455a405574 | rucyang/course_python | /slide/src/finder.py | 477 | 3.71875 | 4 | # coding: utf-8
def first_index_of(sorted_name_list, name, start=0):
'''获取排序列表sorted_name_list中指定名称元素的位置
如果元素name在sorted_name_list中存在,则返回其下标,
下标从0开始计数;如果不存在,则返回-1.
>>> first_index_of([1,2,3], 1)
0
>>> first_index_of([1,2,3], 5)
-1
'''
try:
return sorted_name_list.index(na... |
3d55f727ed3a28117400e82652900600f7ddeaad | brightbird/amazon-scraper | /tests.py | 5,425 | 3.515625 | 4 | #!/usr/bin/env python
"""Tests for Review and Product in scrape
TODO:
Add tests for Product with no reviews.
Add test for review with anonymous author.
Make a mock set of .html files with Amazon links replaced with links to
local files.
"""
import os
from os import path
import unittest
import scrape
clas... |
5b814ec7b9ec38f1e6222f7b1c75dd6b9dbe7105 | moni212/python-Assignment | /Assignment 4 python/Ass4.py | 132 | 3.875 | 4 | celsius = int(input("Enter temperature in celsius: "))
fahrenheit = (celsius * 9/5) + 32
print('fahrenheit : %0.2f' %(fahrenheit)) |
197c0e5522e1614783aa53f1c3ca600604f365c9 | parivgabriela/Coursera | /Python-DB/connect_sqlite3.py | 1,274 | 3.640625 | 4 | import sqlite3
import hashlib
conn =sqlite3.connect(":memory")
cursor=conn.cursor()
#creo la tabla
cursor.execute=("""CREATE TABLE currency
(ID integer primary key, name text, symbol text)""")
#inserto los valores
cursor.execute("INSERT INTO currecy VALUES (1, 'Peso (ARG)','$')")
cursor.execute("... |
71c47b1afc0e8f538192f61d14f796f424d09793 | code-tamer/Library | /Business/KARIYER/PYTHON/Python_Temelleri/functions.py | 1,347 | 3.53125 | 4 | # def sayHello():
# print('Hello')
# sayHello()
# def sayHello(name):
# print('Hello ' + name)
# sayHello('İlker Batu')
# def sayHello(name = 'user'):
# print('Hello ' + name)
# sayHello()
# def sayHello(name = 'user'):
# return 'Hello ' + name
# msg = sayHello('İlker Batu')
# print(msg)
# d... |
957ba2156cc3367b5e12ec89111cb96a40a61110 | code-tamer/Library | /Business/KARIYER/PYTHON/Python_Temelleri/if-elif.py | 430 | 3.890625 | 4 | # x = 20
# y = 20
# if x > y:
# print('x y den büyüktür')
# else:
# print('y x ten büyüktür')
# if x > y:
# print('x y den büyüktür')
# elif(x == y):
# print('x y eşit')
# else:
# print('y x ten büyüktür')
# x = int(input('x: '))
# y = int(input('y: '))
# if x > y:
# print('x y den büyüktür'... |
4f87ad3fa203819f633ba41704fd9d2051dd58de | code-tamer/Library | /Business/KARIYER/PYTHON/Python_Temelleri/string-methods-demo.py | 2,311 | 4.0625 | 4 | website = "http://www.sadikturan.com"
course = "Python Kursu: Baştan Sona Python Programlama Rehberiniz (40 Saat)"
# 1 - ' Hello World ' karakter dizisinin baştaki ve sondaki boşluk karakterlerini silin.
result = ' Hello World '.strip()
result = ' Hello World '.lstrip()
result = ' Hello World '.rstrip()
# ya da we... |
b7b722ea25464d2aa3709617eaadcc51acb56853 | code-tamer/Library | /Business/KARIYER/PYTHON/Python_Temelleri/comprasion-demo.py | 1,307 | 4 | 4 | # 1- Girilen 2 sayıdan hangisi büyüktür?
# a = int(input('a: '))
# b = int(input('b: '))
# result = (a > b)
# print(f'a: {a} b: {b} den büyüktür: {result}')
# 2- Kullanıcıdan 2 vize (%60) ve final(%40) notunu alıp ortalamasını hesaplayınız.
# vize1 = float(input('1. vize : '))
# vize2 = float(input('2. vize : '))
... |
d3323c6dca77f56a1f93f647e52ff3768ff9fc65 | amartinazzo/coursework | /machine-learning/coin-flipping.py | 1,443 | 3.640625 | 4 | import matplotlib.pyplot as plt
import numpy as np
n_coins = 1000
n_flips = 10
runs = 100000
plot = True
# heads = 1
# tails = 0
def toss_coins():
min_heads = 10
rand = np.random.randint(n_coins)
tosses = np.random.randint(2, size=(n_coins, n_flips, runs))
coin_1 = tosses[0,:,:]
coin_rand = tosses[rand,:,:]
... |
197a064543d7fb8db350732e727ad18115a478a7 | RiazAdil/python-files | /graph.py | 166 | 3.6875 | 4 | import matplotlib.pyplot as plt
x=[1,2,3,10,12,15]
y=[5,10,15,23,26,4]
plt.plot(x,y)
plt.xlabel("X Axis")
plt.ylabel("Y Axis")
plt.title("My First Graph")
plt.show() |
0685ce37fc9708c2a9d06217e77ffef0690f38a7 | frankzappasmustache/IT121_Python | /assignments/Lab_3b_Phone_Book_Look_up /phoneBookLookUp.py | 3,105 | 4.53125 | 5 | """
Project Name: IT121_Python
Sub-project: Labs
File Name: phoneBookLookUp.py
Author: Dustin McClure
Lab: Lab 3b Phone Book Look-up
Modified Date: 10/21/2020
Python Program that asks for name/phone number/email,
adds them to a dict, and then provides a lookup function for the user to
... |
50fec7b93c83bbb4967e7c4b9e1ea253e32e5554 | D0nmoses/newslist | /app/tests/test_news_article.py | 672 | 3.78125 | 4 | import unittest
from app.models import NewsArticle
import datetime
class NewsArticleTest(unittest.TestCase):
'''
Test Class to test the behaviour of the NewsArticle class
'''
def setUp(self):
'''
Set up method that will run before every Test
'''
self.new_article = NewsA... |
617a3a264b5b7a35f4c700f273808c530acea661 | NiravReddi/machine-learning-for-salary-estimation | /python_simple_linear_regression.py | 742 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 30 20:02:16 2020
@author: MY PC
"""
import pandas as pd
import numpy as np
from matplotlib import pyplot as mt
#importing dataset
dataset=pd.read_csv("Salary_Data.csv")
x=dataset.iloc[:,:-1].values
y=dataset.iloc[:,1].values
#missing values
#categorisi... |
653b2f52a94b0956de5bae98721986fbf72a8d1e | xuxin8911/MyTools | /unit_conversion.py | 1,079 | 3.609375 | 4 | #!/usr/bin/python
#coding:utf-8
"""
@author: xuxin
@contact: xuxin8911@126.com
@software: PyCharm
@file: unit_conversion.py
@time: 2018/9/1 17:35
@python version: 3.6
"""
import re
def unit_conversion(string):
'''
将TB GB MB KB、 t g m B、 bytes等转换为MB,保留一位小数, 并去掉结尾单位
:param old_data:
:return:
'''
... |
2411e01f551aece6ff7370d75808260907b7eb84 | ShengHow95/basic-algorithm-examples | /find_first_occurrence.py | 702 | 3.546875 | 4 | A = [-14, -10, 2, 10, 10, 12, 12, 14, 16, 20, 30, 55, 105]
target = 10
def find_first_iterative(A, target):
for i in range(len(A)):
if A[i] == target:
return i
else:
return None
def find_first_binary_search(A, target):
low = 0
high = len(A) - 1
while low ... |
07e5623ec265ae6ac88f283918d32bb6aa23ddb6 | lizhuoyou/Python-Tools | /File-oriented/createFile.py | 330 | 3.5 | 4 | #this is used to make new files easily
def makePythonFile(name):
new = open(str(name)+'.py','w')
new.close()
def makeTextP(name):
new = open(str(name)+'.txt','w')
new.close()
amount = int(input('How many open:'))
usedName = input('name:')
for x in range(1,amount+1):
makePythonFile(usedName... |
000f23ea08180197ae4e666159a3100d689b1e9e | NicolaBenigni/PythonExam | /Simulation.py | 2,517 | 4.125 | 4 | # Import necessary libraries
from matplotlib import pyplot as plt
from random import randint
# Import the file "Roulette" where roulette and craps games are defined
import Roulette
### This file tests whether roulette and craps game works. Moreover, it simulates awards and profit distribution
### for 1000 crap games
... |
edb40818eb9f8ba82fb01488c6c4d4f15439a160 | CaptainNabla/it_talents_competition | /data/transformation.py | 3,323 | 3.765625 | 4 | def compute_elo(elo_challenger, elo_opponent, winner):
'''Function for computation of ELO score.
Input:
* elo_challenger: Elo score of challenger.
* elo_opponent: Elo score of opponent.
* winner: String which indicates winner. Allowed values are
... |
46c02307733b98f97a90feee54e4267d259a816c | KNarotam/NetworksProject | /FTPClient.py | 13,417 | 3.640625 | 4 | # Authored by Kishan Narotam (717 931)
import socket
import sys
import os
import time
from time import sleep
from os import walk
# Creating the socket for the client
s = socket.socket()
# Send function: for message and reply messages
def send(message = ''):
# Using the bytes function, we use the "source" which i... |
325628121e6010bcf26bb007217b2d9d953b4b4f | jonathadd27/AritmatikaSederhanaPert1 | /AritmatikaSederhana.py | 963 | 4.1875 | 4 | #Program Hello World !!
print("Hello World")
print("Saya sedang belajar bahasa pemrograman Python")
print("")
print("")
print("Berikut program latihan Aritmatika sederhana dengan inline variable Python")
print("")
print("")
#Program Aritmatika Dasar
bil1 = 25
bil2 = 50
penjumlahan = bil1 + bil2
pengurangan ... |
1445fc64e2947eb1bae26ed8931d92af5fa01f39 | opolaoye/Coursera_Capstone | /Capstone_Project.py | 6,641 | 3.5 | 4 | #### Business Problem
We learned how New York City and the city of Toronto can be segmented and clustered around their neighborhoods. Both cities are very diverse and are the financial capitals of their respective countries.One of the ideas would be to compare the neighborhoods of the two cities and determine how sim... |
ad77878d75e0aaa0f917ddc453b93b0cf6c02f8f | Devang-25/acm-icpc | /project-euler/p199.py | 655 | 3.625 | 4 | # Descartes's theorem
from math import sqrt
from collections import defaultdict
def normalize(k1, k2, k3):
return tuple(sorted([k1, k2, k3]))
K = 3 - 2 * sqrt(3)
R = 1 / (3 - 2 * sqrt(3))
covered = 3
ways = { (1, 1, 1) : 1, (K, 1, 1) : 3 }
for _ in range(10):
new_ways = defaultdict(lambda: 0)
for ks, way ... |
986a5af9a51911eaf0e2aa91ce2aae0be8570a54 | Devang-25/acm-icpc | /project-euler/p203.py | 776 | 3.953125 | 4 | def is_prime(n):
d = 2
while d * d <= n:
if n % d == 0:
return False
d += 1
return True
def exponent(p, n):
result = 0
while n > 0:
n //= p
result += n
return result
def solve(n):
primes = [p for p in range(2, n) if is_prime(p)]
frees = set()... |
d67dd1d3aea99cc216d3e52e8c23790ce855b0ca | Devang-25/acm-icpc | /project-euler/p152.py | 2,142 | 3.53125 | 4 | import random
from collections import defaultdict
from fractions import gcd
from functools import reduce
def is_prime(n):
d = 2
while d * d <= n:
if n % d == 0:
return False
d += 1
return True
def lcm(a, b):
return a // gcd(a, b) * b
def check(LCM, mod, candidates, non_emp... |
ded39786da06e31658d722bec19d720356cc50ac | ShivamPansuria07/python-modules | /Level1-Module2/_03_more_gui_apps/_c_calculator.py | 224 | 3.84375 | 4 | """
Create a simple calculator app
"""
import tkinter as tk
# TODO Make a calculator app like the one shown in the calculator.png image
# located in this folder.
# HINT: you'll need: 2 text fields, 4 buttons, and 1 label
|
a3258932dc63aba4e3991745592c933e53fd444e | sc1f/algos | /sorting.py | 615 | 4.1875 | 4 | def mergesort(nums):
if len(nums) <= 1:
# already sorted
return
# split into 2
mid = len(nums) // 2
left = nums[:mid]
right = nums[mid:]
# recursively split
mergesort(left)
mergesort(right)
# start merging
merge(left, right, nums)
return nums
def merge(left, right, nums):
index = 0
while left and ... |
42084376ce7e7706f63ab6bf5176722679478934 | rishabh-in/RandomProblems | /railwayPlatform.py | 585 | 3.515625 | 4 | def minPlateform(arr, dep, n):
arr = sorted(arr)
dep = sorted(dep)
result = 1
platformNeeded = 1
i = 1
j = 0
while i < n and j < n:
if(arr[i] <= dep[j]):
platformNeeded += 1
i += 1
if(result < platformNeeded):
result += 1
e... |
b40235fc71c87f64e3d87e2d2519c02f38728135 | torijasuta/Advent-Of-Code | /2019/day4.py | 961 | 3.921875 | 4 | input_val_min = 193651
output_val_max = 649729
part_two = True
def has_double_digit(digit_list):
truth = False
for i in range(0, len(digit_list) - 1):
if digit_list[i] == digit_list[i + 1]:
if part_two is True:
if digit_list.count(digit_list[i]) == 2:
t... |
a8d863b3742bed49a5665000569b20ea1b037a25 | leonardocollares/python-tkinter-weather-app | /weather.py | 3,155 | 3.609375 | 4 | import tkinter as tk
import requests
from tkinter.constants import LEFT
def format_response(weather):
try:
place = (
weather["location"]["name"] # city
+ ", "
+ weather["location"]["country"] # country
)
# If the key "forecast" exist, the request was ... |
d388be010509b5f4afb69817d29edc9cb94f62ad | csulva/Rock_Paper_Scissors_Game | /rock_paper_scissors_game.py | 2,174 | 4.25 | 4 | import random
# take in a number 0-2 from the user that represents their hand
user_hand = input('\nRock = 0\nPaper = 1\nScissors = 2\nChoose a number from 0-2: \n')
def get_hand(number):
if number == 0:
return 'rock'
elif number == 1:
return 'paper'
elif number == 2:
return 'scisso... |
6a3fd5acdb5611a303acb941fae6fed61f9ae51b | wang-arthur/project-euler | /Problem071.py | 522 | 3.859375 | 4 | '''
By listing the set of reduced proper fractions for d <= 1,000,000 in ascending order of size,
find the numerator of the fraction immediately to the left of 3/7.
'''
closest = (2, 5)
for d in range(8, 1000001):
n = d * 3 / 7
if n * 7 == 3 * d:
continue
# is n/d closer than the previous pair n'/d' pair?
# i... |
1ff69ba69baddc5fdf85890f0771b89838d54e9d | wang-arthur/project-euler | /Problem114.py | 1,449 | 3.71875 | 4 | '''
A row measuring seven units in length has red blocks with a minimum length of three units placed on it,
such that any two red blocks (which are allowed to be different lengths) are separated by at least one black square.
There are exactly seventeen ways of doing this.
How many ways can a row measuring fifty unit... |
a0d5e506fda1eb6516c6427d0a246bf8256c75d9 | Skelmis/Traffic-Management-Simulator | /cars.py | 1,094 | 4.3125 | 4 | # A class which stores information about a specific car
class Car:
name = None
# Which road did the car enter from
enter = None
# Which direction would the car like to go in
direction = None
def __init__(self, name, enter, direction):
self.name = name
self.enter = enter
... |
9ce9bc309432eb9a565348e9e52af0d401b23102 | amirmasoud1420/maktab52_python | /hw7/t1.py | 582 | 3.671875 | 4 | from primedec import *
class MulPrime:
@staticmethod
def is_prime(n):
for i in range(2, n // 2 + 1):
if n % i == 0:
return False
return True
@string_p
@remainder(5)
@cache(max_size=5)
def __call__(self, a, b):
if not (isinstance(a, int) and... |
b17c6c396ccb33a0060c72109931d0282bb586a1 | Alegp/Python | /comparador.py | 410 | 4.09375 | 4 | #coding: utf8
valor1 = input ("Escriba un numero: ")
valor2 = input ("Escriba un numero: ")
if (valor1 == 0) or (valor2 == 0):
print "Error: hay uno o mas ceros"
else:
if (valor1 > valor2):
mayor = valor1
menor = valor2
else:
if (valor2 >= valor1):
mayor = valor2
menor = valor1
if (mayor % menor == 0)... |
e9c921d613bbcfaa210c5122079f495f226ca3a5 | Alegp/Python | /calculo-area.py | 582 | 3.84375 | 4 | #coding: utf8
import os
os.system("clear")
from math import pi
print """
Selecciona una forma:
a) Triangulo
b) Circulo
"""
forma=raw_input ("Indica una forma: ")
if (forma != "a") and (forma != "b"):
print "Error: esa opcion no existe"
if (forma == "a"):
base = input ("Indica la base... |
127468695329d354698ee33bc925f6373d420ebb | joelwitherspoon/automatetheboringstuff | /ch4/commacode.py | 425 | 3.703125 | 4 | def commacode(commalist):
try:
if commalist is None:
print("There is nothing in this list")
else:
for idx in range(len(commalist)-1):
print(commalist[idx],end=',')
print('and ' + commalist[-1])
except IndexError:
print("IndexError: Can'... |
1d289487520f27da90d218e982bc43b3c8adf512 | PHW0116/python | /20_02_05 list.py | 659 | 3.84375 | 4 | import random as r
grade = [0, 0.51, -2, 0.3, -4]
result = 0
print(grade[0])
print(grade[1])
print(grade[2])
print(grade[3])
print(grade[4])
print('--------')
for x in range(5):
result = result + grade[x]
print('총 합은 : ', result)
print('평균은 :', result/5)
print(r.choice(grade))
print('--------')
... |
22e8fd98a6718953b2fb50463e1a9a819f286907 | PHW0116/python | /20_02_14_터틀런.py | 1,164 | 3.5625 | 4 | import turtle as t
import random as r
#악당거북이
te = t.Turtle() #새 거북이 만드는 코드
te.shape('turtle')
te.color('blue')
te.speed(0)
te.up()
te.goto(0, 200)
#먹이
ts = t.Turtle()
ts.shape('turtle')
ts.color('blue')
ts.up()
ts.speed(0)
ts.goto(0,-200)
def turn_right():
t.setheading(0)
def turn_up():
... |
fb73eea7cf6499b72490c0b2d4cb6da72a9cc2ac | real-mielofon/Algorithms_I | /Merge Sort/merge.py | 1,172 | 3.78125 | 4 | '''
Created on 18.03.2012
@author: Alexey
'''
import random
def merge(list1, list2):
result = []
i,j = 0,0
while ((i < len(list1)) or (j < len(list2))):
if (j >= len(list2)) or ( (i < len(list1)) and (list1[i] < list2[j])):
result.append(list1[i]);
i = i+1
else:
... |
b9f33a80b4f2c8cd596e1ea77a2e62a9bbfffbc8 | thomas6724/Web-scraping | /# input code version log/Webscraping_inputV2.py | 3,512 | 3.546875 | 4 | from urllib.request import urlopen as url_req
from bs4 import BeautifulSoup as soup
import constants
import time
import sys
def input_code():
while True:
user_input = input("Please enter something to search: ")
user_search = user_input.replace(' ', '+')
print(user_search)
... |
ecc1e51f73d5063187d7eb1da163df733749a631 | wyattyhh/Little-Simulated-System | /Database.py | 1,321 | 3.546875 | 4 | import sqlite3, random
# Randomly generate 6 characters from given characters
def generateID():
characters = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM0123456789@_#*-&"
results = ""
for n in range(6):
x = random.choice(characters)
results += x
return(results)
# Genertate ran... |
fba919a1d2a61f14e89b0a8ae31f96b6eeb427fc | Ivy010321/fcp1 | /Solutions/week3/roots.py | 6,544 | 4.625 | 5 | #!/usr/bin/env python
#
# Author: Oscar Benjamin
# Date: Feb 2021
# Description:
# Command line script to find integer roots of polynomials with
# integer coefficients.
#-------------------------------------------------------------------#
# #
# ... |
2409661e66fda76f7c9b094ca42c453337d66bfc | chrispalmo/code-snippets | /python/pickle_reader.py | 1,177 | 3.640625 | 4 | #!/usr/bin/python
'''
Above "shebang": if you have installed many versions of Python, then
#!/usr/bin/env ensures that the interpreter will use the first installed
version on your environment's $PATH. Used for unix-based operating systems.
'''
import argparse
import pickle
import numpy
def pickle_reader(filename, ... |
91a2347e262245223ffd5c42549c56f3e45f4628 | nathanielcrosby/sunimage2stl | /sunimage2stl/makeMovie.py | 1,883 | 4.0625 | 4 | import matplotlib.pyplot as plt
import os
import imageio
def make_movie(files, output, fps=10, **kwargs):
'''
uses the imageio library to take the jpegs created before and save them to a string
of images that is spaced at a certain interval (duration)
Parameters:
files : the array of all the images
output ... |
ab4771d2cfc2bd720eb29c9af8b07c5671efccdc | higorrodrigues8/python-Tkiniter | /Tkinter Grid/estudo-1.py | 788 | 3.609375 | 4 | #coding: utf8
#GERENCIADOR GRID
from tkinter import * #ou Tkinter em verões -3x
from functools import *
janela = Tk()
#___________________________________________________Labels
lb1 = Label(janela, text="Linha 1", bg="lightblue")
lb1.grid(row="1", column='1')
lb2 = Label(janela, text="Linha 2", bg="lightgreen")
lb2... |
018eb9293344a4d8ab70dea29616c4a16f6f9324 | Jadomican/EntAppDev2 | /PythonLab/money_converter.py | 1,641 | 4.0625 | 4 | #Jason Domican EAD2 exercise
# Dictionary of euro-to-x exchange rates
euro_rates = {'USD': 1.2, 'CAD': 1.0, 'GBP': 0.85}
def convert_from_euro(value, to_currency):
return value * euro_rates[to_currency]
def convert_to_euro(value, from_currency):
return value * (1 / euro_rates[from_currency])
print(convert_... |
bbdf6acebf8fc6529849e485e78352babf3f6445 | vaughnsten/Python-Developer | /dictionary.py | 368 | 3.828125 | 4 | #dict = {"Name":"Vaughn " "Sten " "Clausen ", "Surname":"Villegas " "Reyes " "Iguban "}
#print(dict["Name"])
#print(dict["Surname"])
cars = {'name':'Honda', 'model':2013, 'color':'Yellow', 'Air bags': True}
print(cars)
print(len(cars))
cars2 = {'name':'Toyota', 'model':2015, 'color':'Blue', 'Air bags': True}
p... |
7aeccb6a52b37690d114a65e8a16a01779dcb9cd | ibrohimkhan/dsaa_projects | /project3/problem_7.py | 1,933 | 3.609375 | 4 | from collections import defaultdict
class RouteTrieNode:
def __init__(self, handler=None):
self.handler = handler
self.children = defaultdict(RouteTrieNode)
class RouteTrie:
def __init__(self, handler=None):
self.root = RouteTrieNode(handler)
def insert(self, route, handler):
... |
62a5dfce0837380c815b71cbc284fc0e590f0a5e | ibrohimkhan/dsaa_projects | /project3/problem_3.py | 3,442 | 3.609375 | 4 | class Heap:
def __init__(self):
self.cbt = []
self.next_index = 0
def _up_heapify(self):
child_index = self.next_index
while child_index >= 1:
parent_index = (child_index - 1) // 2
parent_element = self.cbt[parent_index]
child_element = self.c... |
92439e7c1286c56a4a7335f42c496b5e97a49653 | efuen0077/Election_Analysis | /Python_prac.py | 2,450 | 4.21875 | 4 | #counties = ["Arapahoe","Denver","Jefferson"]
#if counties[1] == 'Denver':
#print(counties[1])
#temperature = int(input("What is the temperature outside? "))
#if temperature > 80:
# print("Turn on the AC.")
#else:
# print("Open the windows.")
#What is the score?
#score = int(input("What is your test score?... |
30e74410973bda894c23e06bf1f1f8c1c1c2de9c | Minzhe/NaturalLanguageProcessingWithPython_Note | /3.Processing.Raw.Text.py | 6,926 | 3.578125 | 4 | ### Accessing Text from the Web and from Disk
import nltk
from urllib.request import urlopen
import re
url = "http://www.gutenberg.org/files/2554/2554.txt"
raw = urlopen(url).read()
type(raw)
len(raw)
raw[:75]
tokens = nltk.word_tokenize(raw)
type(tokens)
len(tokens)
tokens[:10]
text = nltk.Text(tokens)
type(text)
t... |
c40e1dd00bc0d3dba36647357d6c7bb386bef236 | khushi02/TicTacToe | /main.py | 342 | 3.65625 | 4 | game = [[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
def game_board(game_map, player=0, row=0, col=0, display=False):
if not display:
game_map[row][col] = player
print(" 0 1 2")
for count, row in enumerate(game_map):
print(count, row)
return game_map
gam... |
9b9f9792f766dcd2ab7f097bbd5a9a34a502e92d | YXChen512/LeetCode | /28_strStr.py | 1,576 | 3.734375 | 4 | class Solution(object):
def __init__(self):
self.solution = None
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
# Use pytho dictionary
if haystack == '' and needle == '':
return 0
... |
7730322e90038bd77aa67794c77189c8b5362762 | YXChen512/LeetCode | /2_addTwoNumbers.py | 2,956 | 4.0625 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def Digitize(self):
# Exceptions
if self.val < 0:
print("Input is NOT non-negative")
return None
if type(self.val) is not int:
... |
e4f5ab3e97f7f165e9093f4d892188899a8d23dc | YXChen512/LeetCode | /19_removeNodeFromEnd.py | 1,373 | 4.0625 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def __init__(self):
self.solution = None
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
... |
4eb7391ada3eedb538973ece8b7b3f40672c7556 | YXChen512/LeetCode | /29_divideTwoIntegers.py | 1,084 | 3.765625 | 4 | class Solution(object):
def divide(self, dividend, divisor):
"""
:type dividend: int
:type divisor: int
:rtype: int
"""
if divisor == 0:
return sys.maxint
if dividend == 0:
return 0
if (dividend>0 and divisor >0) or (dividend <... |
6b8873ca6d0f79a523a515db232ddd72984f09fd | StefanRobb/Data-Analysis | /20027476_CMPE251_FinalProjectScripts.py | 1,679 | 3.546875 | 4 | #!/usr/bin/env python
# coding: utf-8
# Code for a data analysis project on presidential speeches and adtempting to predict intelligence scores of the speeches based on word frequency.
# Extracts all the filler words and counts word frequencies.
# @author Stefan Robb
# In[1]:
import nltk
import pandas as pd
from n... |
2d9bef74bb7020a2a81d6c5f410963a7c77f34ed | andrewnagere/PrakAlpro_LinkVideo | /Tugas Video 3.py | 725 | 3.53125 | 4 | #Nama: Andrew Christian Nagere
#NIM: 71200641
#Materi: Modular Programming (fungsi)
#Sumber: https://core.ac.uk/download/pdf/45375438.pdf
'''SOAL:Buatlah fungsi perkalian dua bilangan bulat!
input: memasukkan bilangan yang akan di operasikan(2 bilangan bulat)
proses:
1. deklarasi fungsi (penggunaan fungsi def)
2. dek... |
0aff92de175173679abce2816eb72ac2d5c32080 | as-iF-30/My-Python | /Minion.py | 396 | 3.671875 | 4 | def minion_game(string):
V = ['A', 'E', 'I', 'O', 'U']
c = 0
v = 0
for i in range(len(string)):
if(string[i] not in V):
c+=(len(string)-i)
else:
v+=(len(string)-i)
if(c==v):
print("Draw")
elif(c>v):
print("stuart",c)
else:
pri... |
ba969e36a60c6431ba136785839cbe9b600f3531 | as-iF-30/My-Python | /W31.py | 265 | 3.578125 | 4 | def progression(l=[]):
if len(l) == 1 or len(l) == 2:
return True
a = l[2] - l[1]
for i in range(3, len(l)):
if l[i] - l[i - 1] == a:
pass
else:
return False
return True
print(progression([7,3,-1,-5])) |
8fc54025502851302717169b954343b55c0c9918 | as-iF-30/My-Python | /swapLU.py | 524 | 3.984375 | 4 | # def swap_case(s):
# l = []
# for i in s:
# if(i.islower()):
# i = i.upper()
# elif(i.isupper()):
# i = i.lower()
# l.append(i)
# s = ''.join(map(str,l))
# # s = ''.join([str(i) for i in l])
# print(s)
def change(x):
if str.islower(x):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.