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 |
|---|---|---|---|---|---|---|
cf45171673734fa4746a0bd594c0cdff58def744 | PnuLikeLion9th/Summer_algorithm | /kangwook/5주차/숫자의 합.py | 87 | 3.6875 | 4 | n = input()
nums = input()
total = 0
for i in nums :
total += int(i)
print(total) |
b233ec011a579c4284ca1ac21ef5ec35514a4dd1 | Bhavit1008/Assignments | /DiamondProblem.py | 376 | 3.734375 | 4 | r=6
c = 0
for i in range(r):
for j in range(i):
c +=1
if(j!=0):
print("* "+str(c),end=" ")
else:
print(c,end=" ")
print()
c = c + 1
for i in range(r,0,-1):
for j in range(i-1):
c -=1
if(j!=0):
print("* "+str(c),end=" ")
... |
8fc472a7c947b25214855f37d29f5a0c18f4ef9e | UprightMan/os | /lab5.py | 4,485 | 3.703125 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
# simulacija rasproređivanja SCHED_RR
import time
''' Primjer osnovna korištenja klasa u Pythonu '''
class Dretva:
def __init__ ( self, trenutak_pojave, broj, prioritet, trajanje ):
self.t = trenutak_pojave # kada se dretva pojavljuje
self.id = ... |
edbc80e91c8a9ad244bee62bcfe3809a3dce876a | ethanpierce/DrZhao | /LinkedList/unitTestLinkedList.py | 644 | 4.15625 | 4 | from linkedlist import LinkedList
def main():
#Create list of names
listOfNames = { "Tom", "Harry","Susan","Ethan","Willy","Shaina"}
#Create linkedlist object
testinglist = LinkedList()
#Test insertion method
for name in listOfNames:
testinglist.insert(name)
#Test size of list
... |
7997e5f1519754ae490ed5be635af0f20daa6c09 | LucasAccorsi/projetos | /Bissecao.py | 683 | 3.578125 | 4 | import math
def mod(x):
if (x < 0):
return x * -1
else:
return x
def f(x):
return (math.pow(x, 3)+(4*math.pow(x, 2))-10)
def bissecao(a, b, TOL, N):
i = 1
fa = f(a)
while (i <= N):
#iteracao da bissecao
p = a + (b-a)/2
fp = f(p)
print (mod(f(p)))
#condicao de parad... |
be5aab16256ec880a684a9964cd9b792eebdbbeb | dominik3131/PSI | /Perceptron/perceptronTest.py | 648 | 3.5625 | 4 | import random
from perceptron import *
number_of_ages = 10
a_of_line = 3.2
b_of_line = 4
def initData(number_of_points):
data = [[random.randrange(-50,50 )for i in range(number_of_points)],[random.randrange(-50,50 ) for i in range(number_of_points)]]
t=[up(i,data[0][i],data[1][i]) for i in range(number_o... |
0791baea2a9b01b6ffd2b6369478d7160e174fda | markuskodes/Puzzles | /Linked_List_Problems/flattenDoublyLinkedList.py | 1,493 | 3.953125 | 4 | """
# Definition for a Node.
class Node:
def __init__(self, val, prev, next, child):
self.val = val
self.prev = prev
self.next = next
self.child = child
"""
from typing import Union
class Solution:
def flatten(self, head: 'Node') -> 'Node':
def desce... |
97fc123c1a6beb45aa2893c0c4a8d21bfc41b174 | dvcolin/Sprint-Challenge--Data-Structures-Python | /reverse/reverse.py | 2,387 | 4.1875 | 4 | class Node:
def __init__(self, value=None, next_node=None):
# the value at this linked list node
self.value = value
# reference to the next node in the list
self.next_node = next_node
def get_value(self):
return self.value
def get_next(self):
return self.nex... |
72af330f07d308f48dabe41458ec5311616dc983 | Gintmgg/Learn-Python | /grammar/type.py | 634 | 3.5 | 4 | # -*- coding: utf-8 -*-
intA = 1
floatB = 0.1
print '\tintA => {0}\n\tfloatB => {1}'.format(intA, floatB)
my_arr = ['a', 'b', 'c']
strA = 'abc'
strB = '1233abcde'
if strA in strB:
print 'strA in strB'
else:
print 'strA not in strB'
for item in my_arr:
print 'item => {0}'.format(item)
for item in ra... |
689fefe9dc95a94161bd77e305c4625a89ae9ca0 | NovelLab/stobu | /stobu/utils/filepath.py | 923 | 3.859375 | 4 | """Utility module for file paths."""
# Official Libraries
import os
__all__ = (
'basename_of',
'filenames_with_number',
'is_exists_path',
'new_filename_by_input',
)
# Main
def basename_of(filepath: str) -> str:
assert isinstance(filepath, str)
return os.path.splitex... |
d2b876794851d245f9e4ad93db9fde8058a482bd | xtompok/uvod-do-prg | /cv04/pole.py | 1,155 | 3.796875 | 4 | from math import sqrt
N = 100
def get_primes(N):
""" Vrací seznam prvočísel menších rovno N """
nums = list(range(N+1))
prime = 2
while prime <= N:
if nums[prime] == None:
prime += 1
continue
n = prime*2
while n <= N:
nums[n] = None
... |
59fe9692e1ae92edeac5d2147376249ae1aca9e0 | xtompok/uvod-do-prg | /cv01/area.py | 379 | 3.703125 | 4 | import math
atype = input("Zadej typ útvaru(čtverec, kruh): ")
if atype == "čtverec":
side = float(input("Zadej délku strany: "))
area = side**2
print("Plocha je {:.2f}".format(area))
elif atype == "kruh":
r = float(input("Zadej poloměr: "))
area = math.pi * r * r
print("Plocha je {:.2f}".forma... |
d9fff09e6637b25d02dbc8eab39abcf468a7031b | coach-wang/target_offer | /test30_包含min函数的栈.py | 893 | 3.5625 | 4 | class Solution:
def __init__(self):
self.m_data = [] #数据栈
self.m_min = [] #辅助栈
def push(self, node):
# write code here
self.m_data.append(node)
if len(self.m_min) == 0 or node < self.m_min[-1]:
self.m_min.append(node)
else:
... |
464a030ee6dace5871ddfce5e6385e631991406f | coach-wang/target_offer | /test28_对称的二叉树.py | 711 | 3.953125 | 4 | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isSymmetrical(self, pRoot):
# write code here
#if not isinstance(pRoot, TreeNode):
#return False #输入为空也算对称?
return self.is_Symmetrical(... |
4b5b1c4d7fda995e456731b4d1876b9cff38e014 | coach-wang/target_offer | /test35复杂链表的复制.py | 1,238 | 3.71875 | 4 | # class RandomListNode:
# def __init__(self, x):
# self.label = x
# self.next = None
# self.random = None
class Solution:
# 返回 RandomListNode
def Clone(self, pHead):
# write code here
if not pHead:
return None
self.CloneNodes(pHead)
self.Co... |
07cdf4e57fb657e6f67ec5624a72afa68186d25f | coach-wang/target_offer | /test03_数组中重复的数字.py | 1,064 | 3.5625 | 4 | '''
排序一个长度为n的数组需要O(nlogn)的时间
使用哈希表可以使时间复杂度减小到O(n),但需要O(n)的空间复杂度
这里要特别注意~找到任意重复的一个值并赋值到duplication[0]
函数返回True/False
'''
class Solution:
def duplicate(self, numbers, duplication):
if len(numbers) == 0:
print('数组为空')
return False
n = len(numbers)
for i in numbers:
... |
9973e9c14e6a8953f5d4ae68fb9bbeb0ccfee2ea | Vapb/Titanic | /wiki_titanic_Passagers_webscrap.py | 1,490 | 3.90625 | 4 | # This python file extract data about the passengers of Titanic from the Wikipedia.org sources.
# There is 3 relevant tables about the passengers
# 0 First Class, 1 Second Class, 2 Third Class
import bs4 as bs
import urllib.request
import csv
import FuntionCSV as fc
sauce = urllib.request.urlopen('https://en.wikipe... |
e2ebccc02d255ddb26826cab8ad2f76aa2ab3a0c | tadeograch/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/tests/6-max_integer_test.py | 859 | 3.953125 | 4 | #!/usr/bin/python3
"""Unittest for max_integer([..])
"""
import unittest
max_integer = __import__('6-max_integer').max_integer
class TestMaxInteger(unittest.TestCase):
def test_list(self):
"""Test the function with diferent cases"""
self.assertEqual(max_integer([1, 5, -7, 6, -4 , 10]), 10)
... |
1041fe53fa1dbc0a91f0602f20530a4608656069 | tadeograch/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/0-add_integer.py | 483 | 4.3125 | 4 | #!/usr/bin/python3
"""
0. Integers addition
A function that adds 2 integers
add_integer(a, b)
"""
def add_integer(a, b=98):
"""
Function that add two integers
"""
if not type(a) is int and not type(a) is float:
raise TypeError("a must be an integer")
if not type(b) is int and not type(b) ... |
551cdae590ee4fa45d946c1433873c0bac01134e | tadeograch/holbertonschool-higher_level_programming | /0x10-python-network_0/6-peak.py | 777 | 4 | 4 | #!/usr/bin/python3
'''Technical interview preparation'''
def find_peak(list_of_integers):
'''Finds a peak in a list of unsorted integers'''
n = len(list_of_integers)
if n == 0:
return None
if n == 1:
return list_of_integers[0]
if n == 2:
if(list_of_integers[0] >= list_of_i... |
c325f6fcbdda1be6e52761d98d59666f32df609f | raoulsuli/Formal-Languages-and-Automata | /Regex-to-DFA/tests/generate_random_input.py | 745 | 3.65625 | 4 | import random
from math import sqrt
alphabet = ['a', 'b', 'c', 'd']
def generate_regex(max_len = 100, i = 1):
if i > max_len:
return random.choice(alphabet)
op = random.choices(population=[1,2,3,4], weights=[0.15, 0.15, 0.5, 0.2], k=1)[0]
if op == 1:
return generate_regex(max_l... |
86a5b887048ce2cd40cceccec49b7fd753f4b562 | danielleyo/lab-08-for-loops- | /large.py | 171 | 4.34375 | 4 | largest = 0
for i in range(1, 5, 1):
num = int(input("Please enter a number "))
if (num > largest):
largest = num
print("The largest number is ",largest)
|
35735d9cc75bbc6d3158ee0aaa785ad28df44245 | leichongxiang/sa_dev | /python/other/my_yield.py | 178 | 3.71875 | 4 | #!/usr/bin/env python
def func(n):
for i in range(n):
return i
def func2(n):
for i in range(n):
yield i
print func(3)
f = func2(3)
print f
print f.next()
print f.next()
|
e8fcdb746e6e826b44098eeb814b81009deef2e4 | leichongxiang/sa_dev | /python/py_basic/sort/selectsort.py | 428 | 3.875 | 4 | #!/usr/bin/python
def select_sort(lists):
count = len(lists)
if count < 2:
return lists
for i in range(0, count):
min = i
for j in range(i+1,count):
if lists[min] > lists[j]:
min = j
lists[min],lists[i] = lists[i],lists[min]
return lists
if ... |
20d42fc795112739fc0303a1be7aa4227cdfec3b | karthikch25/PlantGrowthAnalysisML-IP | /PROJECT_EXECUTION/SERVER/exp.py | 4,254 | 3.828125 | 4 | from tkinter import filedialog
from tkinter import*
import tkinter as tk
from file1 import *
import tkinter.font as font
from PIL import Image, ImageTk
#import VotingClassifier as vote
#from DataSupport import *
#voteClassifier = vote.model(x_train,y_train)
#vote.test(voteClassifier,x_test,y_test)
def o... |
14f28949cb4dd5a87eb809b6e1312a03aee19515 | mc-hammertimeseries/cs207project | /timeseries/timeseries.py | 12,009 | 3.625 | 4 | import itertools
import reprlib
import numpy as np
from .lazy import *
import operator as op
import numbers
import math
import pype
class TimeSeries:
"""
A class to store time series data. Supports time series data of any type, including mixed type.
Supports all sequence operations (__getitem__, __setitem... |
e6862a36dc275e9f6e46d18628802b72f3c57cf8 | nagarajuiitm/PythonCorseJohn | /ReturnValues.py | 372 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Nov 28 10:21:14 2019
@author: SNR
"""
def allowed_dating_age(my_age):
girls_age = my_age / 2 + 7
return girls_age;
Buckys_limit = allowed_dating_age(27)
Creepy_joe_limit = allowed_dating_age(40)
print("Bucky can date girls" , Buckys_limit, "or older")
print("Creepy ... |
30d9b63f8e3c8a0ea04d251426ff50b380ce4aad | nagarajuiitm/PythonCorseJohn | /map.py | 255 | 4 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Dec 4 14:32:31 2019
@author: SNR
"""
income = [10, 30, 75]
def double_money(dollars):
return dollars * 2
new_income = list(map(double_money, income))
print(new_income)
for x in income:
print(x * 2) |
4c67ebbcffc998a06657025e331ee2f8f3ff1f82 | nagarajuiitm/PythonCorseJohn | /YouAreTheOnlyException.py | 482 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Dec 2 11:27:09 2019
@author: SNR
"""
while True:
try:
number = int(input("What is your favourite number?\n"))
print(18/number)
except ValueError:
print("Make sure and a enter number")
except NameError:
print("Don't enter a name")
... |
85ba69ba91797762a3090c21753558ef71bba8d8 | praveenit219/py_learnings | /practise/basics/multithreading.py | 516 | 4.03125 | 4 | from time import sleep
from threading import *
class Hello(Thread):
def run(self):
for i in range(500):
print('Hello')
class Hi(Thread):
def run(self):
for i in range(500):
print('Hi')
t1 = Hello()
t2 = Hi()
#t1.run()
#t2.run()
t1.s... |
6e2e8a39069313426c3e97c5c8349b9b35396533 | ag17sep/Chess_AlphaZero | /Chess_AI/MCTS/MCTS_Main.py | 7,082 | 3.578125 | 4 | import numpy as np
import copy
import chess
from Chess_AI.MCTS.self_play import start
"""
This file contains the implementation for the Monta Carlo Tree Search Algorithm, but modified for AlphaZero
Firstly, the UCB(Upper Confidence Bound) equation (V + C*sqrt( ln(N) / n) ) that is used to determine what nod... |
d24d2dd097d3be88b22f0b337ba3b5a162e29622 | roottor38/Algorithm | /programmers/python/최대공약수와회소공배수/solution.py | 611 | 3.609375 | 4 | # def solution(n, m):
# answer = []
# for i in range(n, 0, -1):
# if m%i == 0 and n%i == 0:
# answer.append(i)
# break
# a= (n*m)//answer[0]
# answer.append(a)
# return answer
def solution(n, m):
answer = []
test = []
for i in range(n, 0, -1):
... |
ff536936f86e91fd6e9b026ddc30ff2dad98576b | JiHounHuh/CS170Proj1 | /proj1.py | 3,852 | 3.515625 | 4 | import sys
import copy
from copy import deepcopy
import queue
import math
GOALSTATE = [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '0']]
INITIALSTATE = [['4', '1', '2'], ['8', '3', '6'], ['5', '7', '0']]
PUZZLETYPE = 8
MAXSIZE = (math.sqrt(PUZZLETYPE + 1))
#class PriorityQueue(problem):
# print("help")
# def __... |
9eb451b3e73f525ddfb026ed33c6940bcd9cd39a | hadaszibalazs205/While-ciklus | /ciklus2.py | 298 | 3.703125 | 4 | #Készíts egy programot, amely egymásba ágyazott ciklusok segítségével rajzolja ki egy 5 x 5-ös mezőben az alábbi alakzatot!
sor = 0
while sor < 5:
oszlop = 0
print('O', end='')
while oszlop < 5:
print('.', end='')
print('')
sor= sor +1
oszlop = oszlop +1 |
0725747b9015941bac5f87ff3c5a9372ab9fd5cc | uoshvis/py-data-structures-and-algorithms | /sorting_and_selection/selection.py | 1,527 | 4.15625 | 4 | # An example of prune-and-search design pattern
import random
def binary_search(data, target, low, high):
"""Return True if target is found in indicated portion of a Python list.
The search only considers the portion from data[low] to data[high] inclusive.
"""
if low > high:
return False ... |
e1fa858c23332c238c026a61768a35b3e27f51a4 | uoshvis/py-data-structures-and-algorithms | /object_oriented_programming/range_class_alternative.py | 1,870 | 3.875 | 4 | class Range:
"""A class that mimic's the built-in range class."""
def __init__(self, start, stop=None, step=None):
"""Initialize a Range Instance
Semantics is similar to built-in range class
"""
if step == 0:
raise ValueError('step cannot be 0')
if start < 0... |
dd8b2ba532434cc9d34c992565076a35489f0920 | uoshvis/py-data-structures-and-algorithms | /text_processing/patternMatching.py | 5,880 | 3.609375 | 4 | # Brute Force
# worst-case running time is O(nm)
def find_brute(T, P):
"""Return the lowest index of T at which substring P begins (or else -1)."""
n, m = len(T), len(P) # introduce convenient notations
for i in range(n-m+1): # try every potential starting index within T
... |
84087082a23352a642008e2b7823e77a86736211 | ChandhiniG/Algorithms | /WK4- Divide and Conquer/inversions.py | 936 | 3.75 | 4 | # Uses python3
import sys
def get_number_of_inversions(a, b, left, right):
[count, result] = mergesort(a)
return count
def mergesort(a):
if len(a)==1:
return [0,a]
mid = len(a)//2
left = mergesort(a[0:mid])
right = mergesort(a[mid:])
return merge(left, right)
def merge(left, right... |
7b34862abe781dff545fc5178ba839442ae8c18d | mdasadul/leetcode | /124.py | 932 | 3.546875 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
global_max= - float('inf')
def maxPathSum(self, root):
"""
:type root: TreeNode
:rtype: int
... |
2f5c656af1a84353a1519fd9ba52e1527cfbc507 | mdasadul/leetcode | /1008.construct-binary-search-tree-from-preorder-traversal.py | 937 | 3.78125 | 4 | #
# @lc app=leetcode id=1008 lang=python3
#
# [1008] Construct Binary Search Tree from Preorder Traversal
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def bstFrom... |
f387997bcd2a7fc6c45d6584881f67d4ac3072ab | mdasadul/leetcode | /ginterview.py | 579 | 3.515625 | 4 | class Solution(object):
def planting(self, nums, k):
l = len(nums)
steps = 0
n=k
while l>1:
steps += l
k = n
trees = 0
i = 1
while( l>1 and (k-nums[l-i])>=nums[l-i-1]):
... |
4d160618ef4c8a631fc55362cb99620f408ecb7e | mdasadul/leetcode | /905.sort-array-by-parity.py | 353 | 3.5625 | 4 | #
# @lc app=leetcode id=905 lang=python3
#
# [905] Sort Array By Parity
#
class Solution:
def sortArrayByParity(self, A: List[int]) -> List[int]:
even =[]
odd = []
for item in A:
if item%2 ==0:
even.append(item)
else:
odd.append(item)
... |
8a2fb657761ab1ec0b41c5258c1b723fef23181a | mdasadul/leetcode | /535.encode-and-decode-tiny-url.py | 953 | 3.53125 | 4 | import string
class Codec:
urltocode ={}
codetourl ={}
def encode(self, longUrl):
"""Encodes a URL to a shortened URL.
:type longUrl: str
:rtype: str
"""
while longUrl not in self.urltocode:
code = ''
for _ in range(6):
... |
41584d826ffb68b152bdd927c0a33e89fe01da01 | mdasadul/leetcode | /92.py | 1,210 | 3.796875 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseBetween(self, head, m, n):
"""
:type head: ListNode
:type m: int
:type n: int
:rtype: ListNode
... |
2f7055518e69ff18921a7f4de31333071c147aa4 | mdasadul/leetcode | /105.construct-binary-tree-from-preorder-and-inorder-traversal.py | 668 | 3.78125 | 4 | #
# @lc app=leetcode id=105 lang=python3
#
# [105] Construct Binary Tree from Preorder and Inorder Traversal
#
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def buildTree(self, preord... |
9304041c720b3747dec0b3ed464a9475f7dbc30c | mdasadul/leetcode | /142.linked-list-cycle-ii.py | 549 | 3.625 | 4 | #
# @lc app=leetcode id=142 lang=python3
#
# [142] Linked List Cycle II
#
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
while head:
head.va... |
aa1e827b85decaba80e4715e44b7f4c0bd78404e | ioane-gh/sorting-algorythms | /linear sort.py | 323 | 3.625 | 4 | def linear_sort(arr):
for i in range(1, len(arr)):
n = 0
while i-n >= 0:
if arr[i-n] < arr[i-n-1] and i-n-1 != -1:
arr[i-n-1], arr[i-n] = arr[i-n], arr[i-n-1]
else:
break
n += 1
return arr
print(linear_sort([3, 7, 1, 8, 12, 0... |
cc8fc1f0e3c78e1e110d669e87f3e6a40b0cfbe4 | chandanadasarii/CrackingTheCodingInterview | /Sorting/selection_sort.py | 453 | 3.828125 | 4 | # Selection Sort
# works well for small files, elements with bigger values and smaller keys
# Takes n^2/2 comparisions and n swaps.
# Time complexity O(n^2)
def selection_sort(A):
for i in range(len(A)-1):
min = i
for j in range(i+1, len(A)):
if A[j] < A[min]:
min = j... |
dfc0def94b485376d50ea2cc3412d06b2ce52b08 | chandanadasarii/CrackingTheCodingInterview | /Graphs/graph.py | 2,143 | 4.0625 | 4 | from collections import defaultdict
class Graph():
def __init__(self):
self.graph = defaultdict(list)
# adjacent list
def addEdge(self, vertex, edge):
self.graph[vertex].append(edge)
def depth_first_search_traverse(self, vertex, visited):
visited.add(vertex)
print(ve... |
fc2d73ae73eb21a5db0c385f7ec405f8df922c14 | chandanadasarii/CrackingTheCodingInterview | /CrackingTheCodingInterview/TreesAndGraphs/listOfDepths.py | 1,417 | 3.671875 | 4 | from Tree import BinaryTreeNode
def listOfDepths(treenode, treelists, level=0):
if treenode is None:
return
if len(treelists) == level:
treelists.append([])
treelists[level].append(treenode.data)
listOfDepths(treenode.left, treelists, level+1)
listOfDepths(treenode.right, treelist... |
c1741541cb03ce6173ef6466e288f66ea50c9ca3 | chaitanya472/PythonCode | /BlueBeltTest.py | 1,970 | 3.921875 | 4 | import random
Riddles =["""I am a fruit. I am tasty and provide lots of energy.
You can also find me in a calendar. What am I?""", """What can travel around
the world while staying in a corner""", """What can you hear but not touch or
see and yet control""", """It can be cracked, It can be made, It can be told,
it can ... |
2f303c0ff3356acb8a1108bc29cea12c2d6f5130 | chaitanya472/PythonCode | /DrawAdventureGame.py | 2,900 | 3.953125 | 4 | import turtle, sys
draw= turtle.Turtle()
draw.right(90)
def retry():
restart = raw_input("Would you want to play again yes or no: ")
if (restart == "yes"):
print("Restarting game")
draw.reset()
draw.right(90)
play(100, 50)
if (restart == "Yes"):
print("Restarting gam... |
83131dbd46eeaebc85af2497cd4e79f6b11e41d3 | mimi1987/Codingame | /chuck_norris.py | 1,404 | 3.71875 | 4 | ###################################################################
# Just works 50 % a the moment #
# #
# #
################################################... |
0d6fbb979eab2028a034478021b8b7e29ce5f013 | alexcrevel/Exercices | /Petits_exos/divisible.py | 302 | 3.921875 | 4 | while True:
try:
user_number = int(input("Entrer un nombre positif : "))
count = 0
number_divised = user_number
while (number_divised > 2):
number_divised = number_divised // 2
count += 1
print(count)
break
except ValueError:
print("Données erronées") |
f9592c3de0d60f7ea536a045ec8efcd40cce6a96 | alexcrevel/Exercices | /Petits_exos/diviseurs_propres.py | 517 | 3.90625 | 4 | while True:
try:
user_number = int(input("Entrer un nombre positif : "))
count = 2
number_divised = user_number
list = []
while (count < user_number):
if (user_number % count == 0):
list.append(count)
count += 1
if (len(list) == 0):
print("Aucun diviseur propre"... |
a7ef820167ac26d4acb0f8b0bd33598cb72ab019 | tommyliu9/Minimax-Recursive-Iterative-Strategy | /stonehenge.py | 14,394 | 3.96875 | 4 | """
Game of Stonehenge
"""
from game import Game
from game_state import GameState
"""
Represents one cell of the board
"""
class Cell:
"""
Initialize a new Cell
"""
def __init__(self, value):
"""
Initialize a new Cell
"""
self.value = value
self.claim = None
... |
c7fe77044a5de1c1a641b9f569a67adc768718e9 | USF-Computer-Networking/python-dns-project-ampanisales | /dnsproj.py | 2,277 | 4.0625 | 4 | """ dnsproj.py
Author: Anthony Panisales
- Finds DNS resource records from a domain name
- Finds the hostname of an IP address
- Example usage: python dnsproj.py -a yahoo.com
- Example usage: python dnsproj.py -p 8.8.8.8
- Code for DNS queries inspired by this source:
https://www.adampalmer.me/io... |
f728a10b28e3cb8a92eceb57c2dd75999d21b732 | ap3526/ballLaunchingGame | /block.py | 860 | 3.5 | 4 | #Code created by Akash Patel CS-172-C Lab Section 069
from drawable import *
import pygame
class block(drawable):
def __init__(self, x, y):
super().__init__(x, y)
self.visible = True
def draw(self, surface):
#only draw if visible is true
#draws a filled rectangle then a bl... |
738f7bc82eda276d5cedb692056275a810667b68 | GOyan93/100-Days-of-Code | /Day 18 - Turtle/Challenges/Challenge_5.py | 474 | 3.65625 | 4 | import turtle as t
import random
tim = t.Turtle()
canvas = t.Screen()
direction = 0
passes = 100
tim.speed(15)
canvas.colormode(255)
def random_colour():
r = random.randint(0, 255)
g = random.randint(0, 255)
b = random.randint(0, 255)
random_colour = (r, g, b)
return random_colour
for one_pass i... |
3eafd06214a23c8b96a7fb321a063915bf0d8daf | GOyan93/100-Days-of-Code | /Day 23 - Capstone Project (Frogger)/level_tracker.py | 591 | 3.640625 | 4 | from turtle import Turtle
class LevelTracker(Turtle):
def __init__(self):
super().__init__()
self.level = 1
self.penup()
self.hideturtle()
self.goto(-270, 270)
self.color("black")
self.write(f"Level: {self.level}", align= "center", font= ("arial", 10))
d... |
d366eaf3acbf69da805f4f546fe95b36d84f8829 | GOyan93/100-Days-of-Code | /Day 23 - Capstone Project (Frogger)/main.py | 1,754 | 3.640625 | 4 | import turtle as t
import time
import player_turtle
import level_tracker
from car import Car
WIDTH = 600
HEIGHT = 600
TOP_BORDER = HEIGHT/2
BOTTOM_BORDER = (WIDTH/2) * -1
LEFT_BORDER = (WIDTH/2) * -1
RIGHT_BORDER = WIDTH/2
canvas = t.Screen()
canvas.tracer(0)
canvas.setup(width=WIDTH, height=HEIGHT)
canvas.title("Tur... |
ac1dbc3d5be3fcf1cb6ec271833e8a19af1f6af6 | abmport/Python | /1Semestre/inverter_numero.py | 265 | 4.15625 | 4 | num = int(input("Escolha um número de três dígitos para o invertermos: "))
print("O número escolhido é: ",num)
p1=num%10
p2=num//10
p2=p2*11
p2=p2%10
p3=p1+p2*10
p3=num-p3
p3=p3//100
print("O número invertido é: ",p1,p2,p3)
input ()
|
4f4ef714a358c4f19f0ea3632c55dd3c6b8b3113 | abmport/Python | /2Semestre/ExercicioExcecao3.py | 422 | 3.546875 | 4 | def inserir_nome(lista_nomes, nome):
lista_nomes.append(nome)
def busca_nome(lista_nomes, indice):
try:
if indice >= len(lista_nomes):
raise IndexError
except IndexError:
return "Indice inexistente!"
else:
return lista_nomes[indice]
lista_nomes = []
inserir_nome(lis... |
6c5ae57a73f3852983d173b3562ade7131d6ce1b | abmport/Python | /2Semestre/AC02/ac02.py | 610 | 3.5 | 4 | # ABNER DE MELO PORTO - RA: 1800074
# JOSÉ ALVES DE OLIVEIRA - RA: 1902135
def calculo_salario(lista):
for i in lista:
if i == 'DESENVOLVEDOR':
if lista[2] >= 3000:
desconto = lista[2]*0.2
else:
desconto = lista[2]*0.1
if i == 'ANALISTA':
... |
f2e78992224a652b359aa0d28c9ef5e0b2b22a0e | abmport/Python | /2Semestre/def_media.py | 161 | 3.703125 | 4 | def media(n1, n2, n3):
resp = (n1+n2+n3)/3
print('{:.2f}'.format(resp))
n1 = float(input())
n2 = float(input())
n3 = float(input())
media(n1, n2, n3)
|
0c58fa19c6e67225483f70de44b3601608132f1c | abmport/Python | /1Semestre/IMC.py | 306 | 3.8125 | 4 | peso=float(input())
altura=float(input())
imc=peso/(altura*altura)
if imc<20:
print ("Abaixo do Peso")
else:
if imc<=25:
print ("Normal")
elif imc<=30:
print ("Excesso de peso")
elif imc<=35:
print ("Obesidade")
else: print ("Obesidade Mórbida")
|
a700004e5e94128e2ef94bb4303e70ab81cfc99b | abmport/Python | /2Semestre/Excecoes.py | 338 | 3.875 | 4 | try:
a = int(input("Digite o 1º número: \n"))
b = int(input("Digite o 2º número: \n"))
c = a/b
except ZeroDivisionError:
print ("Ops, O segundo nº não poder ser 0! :)")
except ValueError:
print ("Ops, Você não informou o número! :)")
except Exception:
print ("Ops, Algo deu errado :(")
else:
... |
cc9725c5396578e13861b547fcbd7382b9caba2a | abmport/Python | /2Semestre/POO/aula07_ex2.py | 957 | 3.875 | 4 | class Produto:
def __init__(self, descricao, valor):
self.descricao = descricao
self.valor = valor
class Cliente:
def __init__(sel, nome):
sel.nome = nome
class Carrinho:
def __init__(self, cliente):
self.cliente = cliente
self.produtos = []
def adicionar_pro... |
6ec98e619d3f7d1db184278389eb244c2c9dec4d | abmport/Python | /2Semestre/Banco de Dados - ORM/atividade_presenca_16.05.py | 2,023 | 3.671875 | 4 | import sqlalchemy
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import Session
# Criar Conexão com Banco SQLITE
# caso o arquivo não exista, ele será criado
engine = sqlalchemy.create_engine("sqlite:///server.db")
connection = engine.connect... |
883c77c0a30517375a70ddc44f62ba3b893ede8f | Insper/design-de-software-exercicios | /challenges/todo-mundo-odeia-o-chris/solution.py | 135 | 3.796875 | 4 | nome = input("Digite seu nome: ")
if nome == "Chris":
print ("Todo mundo odeia o Chris")
else:
print ("Olá, {0}".format(nome)) |
369c16313930658192021657e412e7220a91736a | Insper/design-de-software-exercicios | /pages/introducao/raw/introducao/operadores_simples.py | 178 | 3.65625 | 4 | print('Usando alguns operadores numéricos:')
print(2 + 3)
print(2 - 3)
print(2 * 3)
print(2 ** 3)
print(7 / 3)
print(7 // 3)
print(7 % 3)
print((1 + 2) * (-3 - 2))
|
2aa6975a864835ddd846e8b0a5b9de271bb17dd0 | Insper/design-de-software-exercicios | /challenges/preco-da-passagem/solution.py | 130 | 3.609375 | 4 | dist = int(input())
if dist <= 200:
print('{0:.2f}'.format(dist*0.5))
else:
print('{0:.2f}'.format(100 + (dist-200)*0.45)) |
52e106f84a33335ad88ac2ccfca2429952a099e1 | Insper/design-de-software-exercicios | /challenges/classifica-faixas-etarias/solution.py | 496 | 3.578125 | 4 | def agrupa_por_idade(nomes_idades):
por_faixa = {
'criança': [],
'adolescente': [],
'adulto': [],
'idoso': [],
}
for nome, idade in nomes_idades.items():
if idade <= 11:
por_faixa['criança'].append(nome)
elif idade <= 17:
por_faixa['ado... |
ea9cd9d32cc620aeec6edce292f012ef08aa203d | Insper/design-de-software-exercicios | /pages/arquivo/raw/arquivo/exemplo_json.py | 796 | 3.78125 | 4 | import json
with open('alunos.json', 'r') as arquivo_json:
texto = arquivo_json.read()
print(texto)
# Para verificar que é realmente um texto (string),
# vamos usar um fatiamento:
print(texto[:15])
# Criando um dicionário a partir das informações no texto
dicionario = json.loads(texto)
# Para verificar que é um... |
1afe404c80def926b0453a33606c3c0d0b5883a0 | Insper/design-de-software-exercicios | /challenges/todos-os-bigramas-de-uma-string/solution.py | 177 | 3.65625 | 4 | def acha_bigramas(palavra):
lista = []
for i in range(1,len(palavra)):
if palavra[i-1]+palavra[i] not in lista:
lista.append(palavra[i-1]+palavra[i])
return lista |
4050a7794bd60e50db27571dad9fb1fa6e46d194 | Insper/design-de-software-exercicios | /challenges/calcula-angulo-de-refracao/tests.py | 1,987 | 4 | 4 | '''
A lei de Snell-Descartes define que a relação entre o ângulo de incidência e o ângulo de refração de um raio de luz atravessando de um meio para o outro é inversamente proporcional a razão dos índices de refração dos meios, que é dado pela seguinte fórmula:
n1/n2 = sen(theta2)/sen(theta1)
Faça um pro... |
40ffcf72e6fefac1d143fb25ef1371c976fc1c3d | Insper/design-de-software-exercicios | /traces/soma-das-entradas/code.py | 311 | 3.9375 | 4 | # Função que soma dois números.
def soma(x, y):
z = x + y
return z
# Lendo os dois números.
a = input('Entre com o primeiro número: ')
b = input('Entre com o segundo número: ')
c = int(a)
d = int(b)
# Somando os dois números.
e = soma(c, d)
print('A soma dos dois números é: {0}'.format(e))
|
99946ab7df6605f55564bc2565b1db397374b797 | Insper/design-de-software-exercicios | /pages/arquivo/raw/arquivo/with_open.py | 217 | 3.796875 | 4 | # Abre um arquivo para a leitura.
with open('arquivo_texto.txt', 'r') as arquivo:
conteudo = arquivo.read()
# Quando sai do bloco do 'with', fecha o arquivo automaticamente.
# Imprime o conteúdo
print(conteudo)
|
8d4ab07d999f2e6b511ca6c52d424eea4b19c8df | Insper/design-de-software-exercicios | /traces/lista-de-contatos/code.py | 204 | 3.796875 | 4 | telefones = {"Fulano": "99999-1111", "Sicrano": "99999-2222", "Beltrano": "99999-3333"}
nome = input("Digite um nome: ")
telefone = telefones[nome]
print("Telefone de {0} é: {1}".format(nome, telefone))
|
5fa509c06ee70d1bdffa9688614b2564f89ccb8c | Insper/design-de-software-exercicios | /pages/input/raw/input/tipos.py | 263 | 3.734375 | 4 | # Converte para inteiro.
print(int(3.14))
# Converte para float.
print(float(4))
# Converte para string.
print(str(123))
# Converte de string para int.
print(int('42'))
# Converte de string para float.
print(float('1.625'))
# What ?!?
print(float('banana'))
|
ad1c7fa54f34b9731e1d2b47553d8906319a3aac | Insper/design-de-software-exercicios | /pages/funcao/raw/funcao/funcoes2.py | 420 | 3.875 | 4 | """
Programa que converte de milhas para quilômetros. Versão melhor documentada.
@author: Profs. de Design de Software
"""
# Função que converte um valor de distância
# dado em milhas para quilômetros.
def converte_milhas_para_km(distancia_mi):
distancia_km = 1.60934 * distancia_mi
return distancia_... |
8be892363d6ef14af6e197d7740b81ca29eb80b9 | Insper/design-de-software-exercicios | /challenges/forma-trios/solution.py | 465 | 3.75 | 4 | def separa_trios(lista = []):
lista_trios = []
for i in range(len(lista)):
if i%3 == 0:
lista_aux = []
lista_aux.append(lista[i])
if i > len(lista) - 2:
lista_trios.append(lista_aux)
elif i%3 == 1:
lista_aux.append(lista[i])
if i > len(lista) - 2:
... |
ddf9f09fef556cfd9a6cce796aec973e3ff58d6d | Insper/design-de-software-exercicios | /challenges/cria-logins-unicos/solution.py | 415 | 3.875 | 4 | def login_disponivel(nome, existentes):
if nome not in existentes:
return nome
i = 1
while '{0}{1}'.format(nome, i) in existentes:
i += 1
return '{0}{1}'.format(nome, i)
nomes = []
nome = input('Digite um nome: ')
while nome != 'fim':
novo_nome = login_disponivel(nome, nomes)
n... |
cffa0d6511354405905524cd83dc3e0620342b67 | frclasso/estatistica_geral_puc_minas_2020 | /resolucao_python/unidade_1/script_5.py | 2,112 | 3.78125 | 4 | import statistics
import math
from typing import List
class EscoreZ:
"""O objetivo de se calcular o escore Z é expressar em unidades de
desvio padrão quanto um determinado número está distante da média
Para o cálculo do escore Z é necessário conhecer a média eo desvio padrão"""
def __init__(self, dad... |
4175ba2285d9bbf75518d2cf562ab5b84d7d090d | frclasso/estatistica_geral_puc_minas_2020 | /resolucao_python/unidade_2/exemplo_3.py | 2,041 | 3.546875 | 4 | import pandas as pd
import math
data = {
'Homicidio(H)': [12, 39, 18, 69],
'Furto(F)': [379, 106, 20, 505],
'Assalto(A)': [727, 642, 57, 1426],
'Total': [1118, 787, 95, 2000]
}
df = pd.DataFrame(data, index=['Estranho(E)', 'Conhecido(C)', 'Ignorado(I)', 'Total'])
df.index.name = 'Criminoso'
print(df)
... |
b37096b91445ec469a408700d1a794c5eaddba06 | SemiMaks/automobile_class | /car.py | 1,193 | 3.703125 | 4 | from vehicles import Automobile
# Класс Car представляет легковой автомобиль.
# Он является подклассом класса Automobile.
class Car(Automobile):
# Метод __init__ принимает аргумегты для фирмы-
# -изготовителя, модели, пробега, цены и количества дверей.
def __init__(self, make, model, mileage, price, doo... |
ba1b2293666b87652ba97dd7ef9c77fba75da509 | salarsen/dojoPython | /python/averagelist.py | 83 | 3.71875 | 4 | a = [1, 2, 5, 10, 255, 3]
avg = 0
for item in a:
avg += item
print avg/len(a)
|
5273bca922d340a35a967606708bd64309117f44 | salarsen/dojoPython | /class_files/week5_session4.py | 602 | 3.578125 | 4 | class Computer(object):
def __init__(self,ram=4,os="linux"):
self.cpu = "i5",
self.ram = ram,
self.hard_drive = "Seagate",
self.os = os,
self.turned_on = False
def boot(self):
self.turned_on = True
print "powered on"
def run_program(self, program):
... |
49ab14774b4e9c902769a68abf526d7e8dfdcdc3 | salarsen/dojoPython | /python/multiple.py | 146 | 3.578125 | 4 | a = [2,4,10,16]
def multiply(arr,multiplier):
for num in range(0,len(arr)):
arr[num] = arr[num] * multiplier
multiply(a,5)
print a
|
eb1320f3cb90424fbf9c586baa13baceec78cca2 | yudhiesh/Classic_Computer_Science_Problems_In_Python | /chapter_1/fib.py | 1,125 | 3.796875 | 4 | from functools import lru_cache
from typing import Dict, Generator
memo: Dict[int, int] = {0: 0, 1: 1}
# Recursive approach
def fib1(n: int) -> int:
if n < 2:
return n
return fib1(n - 1) + fib1(n - 2)
# Memoized implementation
def fib_memo(n: int) -> int:
if n not in memo:
memo[n] = f... |
631adb3b8c55b72d29134f171b0db8e8073f6360 | samlee916/Python-The-Beginner-Python-Programming-Course | /TheForLoop.py | 181 | 4.46875 | 4 | #An example of using a for loop in Python
for num in range(0,10): #range(start, end)
print(num)
#prints out 0-9
#printing out 0,1,2,5
for num in (0,1,2,5):
print(num)
|
40a9c85fad216cd0bd7673aac0f0bfff3b135972 | szekai/Machine-Learning-in-Trading | /utils.py | 2,630 | 3.5 | 4 | """Utility functions"""
import os
import pandas as pd
import matplotlib.pyplot as plt
def symbol_to_path(symbol, base_dir="data"):
"""Return CSV file path given ticker symbol."""
return os.path.join(base_dir, "{}.csv".format(str(symbol)))
def get_data(symbols, dates):
"""Read stock data (adjus... |
15f16e858f63632ac462de1629a132bca74bfd1c | ibrahimediz/Work | /MyContacts/main_contactList.py | 2,060 | 3.65625 | 4 | archive=[]
allowCharacters="123456"
def menu():
print("_"*25,
"""\n\n LIBRARY MENU
\n1- Add Books
2- Search Books
3- List All Authors
4- List All Books
5- Delete Book
6- Exit
""",
"_"*25,sep="")
def bookAdd():
if menu_Choose=="1":
bookAdd=input("Please enter the name of the book ... |
278445b14cdb1266f534124b9454c289cab78491 | vikingden8/Python3_Essential_Training_Excercise_Files | /04-Variables/02_variable_strings.py | 300 | 4.03125 | 4 | #!/usr/bin/python3
def main():
content = "this is a text"
print(content)
x = 45
content = "this is a format text with number :{}"
print(content.format(x))
content = '''\
This is a text
Line after line
more text
'''
print(content)
if __name__ == '__main__':
main() |
48b51f75ee86ada7912be4cefcb8e733b604b60e | vikingden8/Python3_Essential_Training_Excercise_Files | /06-Loops/02_for.py | 402 | 3.78125 | 4 | #!/usr/bin/python3
def main():
# for files
fh = open("lines.txt")
for line in fh.readlines():
print(line, end="")
# for collections, like list
list = [1, 2, 3, 4, 5, 6, 7, 8]
for number in list:
print(number)
# for strings
content = "This is a line of text."
for c... |
3b352023541d2371527c0f42ec618303a32d8487 | ankursharma319/python_misc | /misc_labs/lab6.py | 850 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Nov 20 11:52:24 2015
@author: as3g15
"""
def eval_f(f, xs):
"""
Takes a function f = f(x) and a list xs of values
that should be used as arguments for f. The function
eval_f applies the function f subsequently to
every value x in xs, and returns a list f... |
e1fbe48d4d647b722c5a71b93554ae61e74664c4 | ankursharma319/python_misc | /misc_labs/lab7.py | 1,503 | 3.96875 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
def newton(f, x, feps, maxit):
"""
Takes a function f(x) and an initial guess x
for the root of the function f(x), an allowed
tolerance feps and the maximum number of iterations
that are allowed maxit, and returns the ... |
99fe7f6f80e335e7ae308c07df3f59b75252c382 | ankursharma319/python_misc | /misc_labs/training3.py | 482 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 26 12:46:34 2015
@author: as3g15
"""
import math
def degree(x):
"""Returns x radians converted into degrees"""
return x*(180.0/math.pi)
def min_max(xs):
"""Returns a tuple consisiting of xmin and xmax
in the list xs"""
return min(xs), max(xs)
de... |
04b786d39396d36eb2bcd002f1ed4249d686b79d | vidhlakh/SQLiteExploration | /createTable.py | 304 | 3.515625 | 4 | import sqlite3
conn = sqlite3.connect("mydatabase.db") # or use :memory: to put it in RAM
cursor = conn.cursor()
# create a table
cursor.execute("""CREATE TABLE albums
(title text, artist text, release_date text,
publisher text, media_type text)
""") |
0f81c28ec6facf7cb3e4d1e88eeeb27d1bece693 | JordanWalker28/Data-Mining-and-Machine-Learning | /data_mining_cw3-master 2/part3_attributeReduction.py | 2,535 | 3.65625 | 4 | #!/usr/bin/python3
''' F20DL
Coursework 1
Part 3: Reducing Number of Attributes
Author: Cameron McBride
Group: 9
'''
import sys
import os
class reduce_attributes():
def __init__(self,filename):
self.filename = filename
def newFile(self,oldName): # returns new filename for reduced attributes
inner_directory = ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.