blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
70d935319fcb560475b7fe4cc1b772e5df53cf77 | Herebert1706/Practicas-de-Estructura-de-Datos | /Recursividad.py | 442 | 3.78125 | 4 | def naturales(x): //Aqui estoy definiendo una funcion en donde utilizare la variable x
if x<101: //Hago un if en donde le doy la condicion que x sea menor que 100
print(x) //Mando a imprimir los numeros
x=x+1 //Aqui incremento el numero de 1 en 1
return naturales(x) //Regreso la funcion d... |
a88a7974a6c84f1fb9838ad0ef2fe2ee2705563f | yymin1022/CAU-Computational-Thinking-and-Problem-Solving-Assignment1 | /문제6.py | 1,409 | 3.59375 | 4 | import random
player1 = str(input('1 플레이어의 이름은? '))
player2 = str(input('2 플레이어의 이름은? '))
# 현재 진행중인 라운드
round = 1
# 두 플레이어의 위치를 출발지점(0)으로 초기화
current1 = 0
current2 = 0
while current1<30 and current2<30:
# 플레이어의 주사위 값
dice1 = random.randint(1, 6)
dice2 = random.randint(1, 6)
# 각 플레이어의 현재 위치에 주... |
d2ee40453faed04f6e08bacf0862fe762daca518 | amarnadhreddymuvva/pythoncode | /armstrong.py | 199 | 4.03125 | 4 | num=int(input("eneter a number"))
sum=0
temp=num
while(temp>0):
digit=temp%10
sum=sum+digit**3
temp=temp//10
if (num==sum):
print(("armstrong number"))
else:
print("not")
|
7513fc5f2fb44654ffa11d470903ad6f61dec95a | fritzreece/euler-solns | /Problem24/permute.py | 601 | 3.765625 | 4 | from math import ceil
def factorial(n):
res = 1
while n > 0:
res *= n
n -= 1
return res
# assume perms are zero indexed
def nth_perm(string, n):
string = "".join(sorted(string))
if n == 0:
return string
# the index in the sorted string of the character that will be fir... |
c70d4fbcdf636d8dba4c3fc81e33ebe27ac533e1 | AlessandroFMello/EstruturaDeRepeticao | /Exercício014.py | 723 | 3.703125 | 4 | import msvcrt
while True:
arr = []
arrP = []
arrI = []
contador = 0
arr.append(int(input('Digite um número:\n')))
while contador < 9:
arr.append(int(input('Digite outro número:\n')))
contador += 1
for x in arr:
if x % 2 == 0:
arrP.append(x)
... |
37313952d959a583da36c0b839ddd39f60651416 | rduvvi/MyPythonWorks | /Operators.py | 1,149 | 4.21875 | 4 | # Python operators used to perform operation on operands.
# Arithmetic Operators * ,/,-
x=4
y=5
print(x+y)
# Comparison Operators Likewise,you can try (x < y, x==y, x!=y, etc.)
print(('x > y is',x>y))
num1=5
num2=6
res = num1 + num2
res += num1
print(("Line 1 - Result of + is ", res))
# Logical Operators - AND,NO... |
48a1d2b0e77eb550a32dfb1f21dad375c9d8a834 | kavya199922/python_tuts | /Day-3/py_json.py | 927 | 3.859375 | 4 | #loading json data from file
#serialization:json=>python dict
#read data (json) from a file:
# convert:python(dict)
import json
with open('dat_json.json','r') as f:
data=json.load(f)
print((data))
str1='''
{
"23": {
"name": "Jonas",
"email": "jonas23@gmail.com",
"role": "manager... |
e1b2c1ab3b48a9b14b49f12fd0b9fcc890d5307d | aprilxyc/coding-interview-practice | /leetcode-problems/1213-intersection-of-two-arrays.py | 1,866 | 3.90625 | 4 | class Solution:
def arraysIntersection(self, arr1: List[int], arr2: List[int], arr3: List[int]) -> List[int]:
# O(N) where N is the length of the longest array
# O(N) space where N is the length of the longest array
# keep pointers on all 3 arrays
num1 = num2 = num3 = 0
... |
8390b5fa589a2464e80224c346a4c774055301bb | MarijnJABoer/AwesomePythonFeatures_Marvel | /marvel_universe.py | 3,962 | 3.703125 | 4 | class MarvelCharacter:
"""
Creates a character from the Marvel universe
"""
# class atribute
location = "Earth"
def __init__(self, name: str, birthyear: int, sex: str):
self._name = name
self.birthyear = birthyear
self.sex = sex
def __repr__(self):
return f... |
624b07553a025dd27f0071708a0900b13885104a | katiakata1/Codewars_python | /detect_pangram.py | 742 | 4.0625 | 4 | #A pangram is a sentence that contains every single letter of the alphabet at
#least once. For example, the sentence "The quick brown fox jumps over the
#lazy dog" is a pangram, because it uses the letters A-Z at least once
#(case is irrelevant).
#Given a string, detect whether or not it is a pangram. Return True if... |
4bce2b3fa1ebe1d3715bd892351acf7f4e4eae14 | syw2014/DL-Course | /course/cs231n/assignment1/classifier/linear_svm.py | 4,704 | 3.78125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author : Jerry.Shi
# File : linear_svm.py
# PythonVersion: python3.5
# Date : 2017/4/13 9:08
# Software: PyCharm Community Edition
import numpy as np
from random import shuffle
def svm_loss_naive(W, X, y, reg):
"""
A simple implementation of ... |
d0c6ce4565c351df61c091e9f4fc4e7be2f0b946 | jogusuvarna/jala_technologies | /polymorphism.py | 426 | 4.0625 | 4 | '''Runtime Polymorphism with Data Members/Instance variables, Repeat the above
process only for data members.'''
class Student:
def __init__(self,m1,m2):
self.m1=m1
self.m2=m2
def __add__(self, other):
m1=self.m1+other.m1
m2 = self.m2 + other.m2
s=Student(m1,m2)
... |
0af3c7f157a30bd9bda21fbc5fa9ca56bd2c634e | nishathapa/CB | /Day2/loop.py | 195 | 3.640625 | 4 | line = input("Enter your fav line")
letters = {}
for ch in line:
if ch in letters:
letters[ch]=letters[ch] + 1
else:
letters[ch]= 1
print(letters)
# print(letters["a"]) |
2e09c4f0904a5e47f4b1f0282204b7de207fc547 | wang550564900/pythoncode | /py_homework/day4homework.py | 4,123 | 4 | 4 | # class Father(): #声明父类
# def __init__(self,a,b):#给类设置属性
# self.a=a
# self.b=b
# #方法一
# def add(self):# 类的方法add
# return self.a+self.b
# #方法二
# def sub(self):
# return self.a - self.b
# class Son(Father):#声明子类继承父类
# def print_add(self):
# ... |
d1b88eccde187b0cead92d3d4172a6bf05d0519e | tabboud/code-problems | /problems/interview_cake/07_temperature_tracker/temperature_tracker.py | 1,587 | 4.0625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class TempTracker(object):
def __init__(self):
self.temps = {}
self.max_temp = None
self.min_temp = None
self.sum_of_temps = 0.0
self.num_of_temps = 0
def insert(self, new_temp):
""" Record a new temperature """
... |
03eb7da30f494d9e7c5e1748e72e5a43bf95d01f | harishdots/csv_to_nested_json | /csv_to_json/csv_to_json_tree.py | 2,354 | 3.859375 | 4 | import json
from itertools import repeat
class ConvertCsvToJsonTree:
"""
This class is used to to convert CSV data into json hierarchy tree
"""
def __init__(self, csv_data):
""" Initialising class """
self.max_column = 0
self.csv_data = csv_data
def create_parent_tree(sel... |
6e92a2bbc8b495738d36e989f074d2a06aacb18f | Ars187/Algorithms | /Binary search.py | 675 | 4.09375 | 4 | #Binary search
def binsearch(lst,item,beg,end):
if end>=beg:
mid=(beg+end)//2
if lst[mid]==item: #If element is present at the middle itself
return(mid)
elif lst[mid]>item: #If element is smaller than mid, then it can only be present in left subarray
return(... |
6d23891e169054151d934c057d59ad8e0bac393a | huyngopt1994/python-Algorithm | /green/green-08-sort/increase.py | 1,198 | 4.09375 | 4 | # Build bubble sort
my_list = []
def bubble_sort(my_list):
for i in range(len(my_list) - 1):
for j in range(i + 1, len(my_list)):
# try to swap if my_list[i] = my_list[j]
if my_list[i] > my_list[j]:
temp = my_list[i]
my_list[i] = my_list[j]
... |
6b2884b7b4e2e7d945aa49aa2515c55a51ae06e3 | mihirkelkar/hackerrank_problems | /mth-to-last-linked-list.py | 1,151 | 3.96875 | 4 | #!/usr/bin/python
class node:
def __init__(self, value):
self.value = value
self.next = None
class linkedlist:
def __init__(self):
self.head = None
self.tail = None
self.counter = 0
def add_node(self, value):
x = node(value)
if self.head == None:
self.head = x
self.tail = x
self.counter +... |
0d627725a9c25d8e42de083e34e6aec8a7bb358c | fernandobd42/Mutation-Tool---Python | /operatorLines.py | 1,696 | 3.625 | 4 | import os # the 'os' module provides functions to interact with the operating system
import re # the 're' module provides functions to interact with regular expression operations
from data import Data # Import the class Data of file data.py
# the class OperatorLines is used to get the operators and lines of the origin... |
7e31c62c7ab22b4f692c934b51ebe1e2f291cc04 | immortalChensm/python | /demo2/demo22.py | 515 | 3.984375 | 4 | '''
错误异常处理
try........except..........else
程序会尝试着执行语句,当语句出现错误时会匹配到except的对应错误
如果没有就执行esle语句
'''
try:
#print(3/0)
print(num)
except NameError as e:
print("不存在此变量")
except ZeroDivisionError as e:
print("被除数不能为0")
print("*"*20)
try:
print(5/0)
except:
print("程序出现了异常")
try:
print(nums)
exc... |
a1bb5a853291d8fa4424e4d417fdaaeba6cf470b | ianbialo/Cryptography | /app/keys_generator/prime.py | 3,610 | 3.59375 | 4 | from os import path
import random
from app.keys_generator.xorshift import XORShift
from app.utils.file_manager import read_file, write_file
from app.utils.modular_arithmetic import square_and_multiply
def _generate_possible_prime(n_bits: int = 128) -> int:
"""
Generate an odd random number of n_bits bits
... |
313202d0d0730500dc1fd277739c0b4d20095ecf | clarkkarenl/codingdojo_python_track | /python_stack/python_OOP/call_center/call_center.py | 3,668 | 4.25 | 4 | # Assignment: Call Center
# Karen Clark
# 2018-07-05
# You're creating a program for a call center. Every time a call comes in you need a way to track that call. One of your program's requirements is to store calls in a queue while callers wait to speak with a call center employee.
# You will create two classes. One c... |
bf99b29a2c1445c8bae49125a0137b751af5e5c7 | rakeshksatapathy/python | /Maximum_Perimeter_Triangle.py | 669 | 3.8125 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
#!/usr/bin/python
import sys
def Maximum_Perimeter_Triangle(n,arr) :
combo3_list=[]
triangle_list=[]
for i in xrange(n-1) :
if arr[i]+arr[i+1]>arr[i+2] and arr[i+1]+arr[i+2]>arr[i] and arr[i+2]+arr[i]>arr[i+1] :
... |
6eafcd2336a044a24472238edb9e7b94fb28f733 | jcasarru/coding-challenges | /python/4.py | 518 | 4.28125 | 4 | '''
Create a program that asks the user for a number and then prints out a list of all the divisors of that number.
(If you don’t know what a divisor is, it is a number that divides evenly into another number. For example, 13 is a divisor of 26 because 26 / 13 has no remainder.)
'''
from math import floor
random = i... |
f918742754c615effcd3852c59714e97f7ebb05c | arturfil/data-structures-and-algorithms | /linked_lists/double_linked_list.py | 501 | 3.90625 | 4 | # Here just as the name suggest, the list has a pointer to the next and previous node which allows for faster search of values
# But is the same amount of time to delte or insert
class DoubleNode(object):
def __init__(self,value):
self.value = value
self.next = None
self.prev = None
a = DoubleNode("Head... |
dceaf2a381fe1cddc5eb44bf370b6f245d964a91 | focussash/Dynamic-Connect-4 | /Assignment 1.py | 9,673 | 3.765625 | 4 |
#Here, state will be a an array of 2 lists, First contain x coordinates of pieces, second contain y coordinates.
#In both arrays, first 6 entries are player A and next 6 are player B. The 3rd, single element of state dictates who is the moving player, 1 for A(X) and -1 for B(O).
#The 4th element is utility,1 for p... |
9af72152c8c14f53cfd9e06fc0ada38f99558456 | ashishsahu1/ImageProcessing | /InvisibilityCloak/background.py | 713 | 3.53125 | 4 | #------------------------------------------------------------------------------
#first step is to click a background image
#second step select the colour
#it should remove every pixel which is red and change with background
#------------------------------------------------------------------------------
#importing libr... |
282b9ab8996c8b69492f34404345159ba4aae0ac | bitcocom/python | /Python중급1/section4/4-3-1.py | 1,299 | 3.78125 | 4 | #리스트 자료형(순서O, 중복O, 수정O, 삭제O)
#선언
a = []
b = list()
c = [0, 0, 1, 2]
d = [0, 1, 'car', 'apple', 'apart']
e = [0, 1, ['car', 'apple', 'apart']]
#인덱싱
print('#=====#')
print('d - ',type(d),d)
print('d - ',d[1])
print('d - ',d[0]+d[1]+d[1])
print('d - ',d[-1])
print('e - ',e[-1][1])
print('e - ',e[-1][1][4])
print('e - ',... |
6f6134c34b980363974571f21e64c746b602daf5 | chelseealee/swarch | /server-master/client.py | 2,578 | 3.6875 | 4 | """
The Client is slave:
- it sends only the player inputs to the server.
- every frame, it displays the server's last received data
Pros: the server is the only component with game logic,
so all clients see the same game at the same time (consistency, no rollbacks).
Cons: lag between player input and screen di... |
8a0dacf1f937a131717fff1e53bedbb07209b1a4 | DylanBarrett/IT1040-Mizzou | /BarrettDylanAnimals/Animal.py | 816 | 4.125 | 4 | import random
# This program creates a class named
# Animal and stores information about an animal.
class Animal:
# The __init__ method initializes the attribute
def __init__(self, animal_type, name):
self.__animal_type = animal_type
self.__name = name
a = random.randint(1,3... |
4d02ec010dd06b51657f0a7209da9bbfc0e5cc69 | ClaudiaStrm/Introducao_ciencia_da_computacao | /02-01_raiz.py | 1,090 | 3.8125 | 4 | '''O programa deve receber os parâmetros a, b, e c da equação ax2+bx+c, respectivamente,
e imprimir o resultado na saída da seguinte maneira:
Quando não houver raízes reais imprima: esta equação não possui raízes reais
Quando houver apenas uma raiz real imprima: a raiz desta equação é onde X é o valor da raiz
Quan... |
7678e0c931404b167888bc265f26f4e6e0b597be | Henryzhaoheran/boo-vscode | /listgen.py | 477 | 4.0625 | 4 | # List generator P42
# 列表生成式和列表生成器的不同
l = ("{}*{}".format(x, x) for x in range(1, 11))
print(l)
"""
print(next(l))
print(next(l))
print(next(l))
print(next(l))
"""
for idx in range(1, 11):
print(next(l), end = ' ')
print()
#判断为偶数
l1 = ("_{}_".format(x) for x in range(1, 11) if x%2 == 0)
print(l1)
"""
print(next(... |
4bf7015c7579f72c48db9dd2ff0177171921092f | rmesquita91/bdpython | /dadosimc.python.py | 743 | 3.859375 | 4 | import sqlite3
# criar uma conexão e um cursor
con = sqlite3.connect('dadosimc.db')
cur = con.cursor()
#SQL linguagem criar tabela
sql = 'create table dados'\
'(id integer primary key,'\
' nome varchar (100) NOT NULL,'\
'altura varchar(10)NOT NULL,'\
'peso varchar(10)NOT NULL... |
f6df97239d04a174750ec44fc165c4df01763fdb | payscale/payscale-course-materials | /python/software_engineering/solutions/employee_example.py | 742 | 3.921875 | 4 | class Employee:
def __init__(self, name, job_title, job_location):
self.name = name
self.job_title = job_title
self.job_location = job_location
def greeting(self):
return f"Hello, my name is {self.name} and I am a {self.job_title}"
def estimated_salary(self):
if se... |
a381a61c093506f8592138f288c93ee4a22266b2 | smartarch/qoscloud | /cloud_controller/analyzer/objective_function.py | 4,496 | 3.53125 | 4 | """
This module contains the class creating the objective function expression. The objective is represented as an integer
expression which is supposed to be added to CSP solver.
The abstract class ObjectiveFunction can be used to implement new objective functions.
"""
import time
from abc import abstractmethod
from typ... |
10657ac14bfe925ca5560da05c6308c670e7a82c | noahadelstein/mathemagic | /sample_python/attendee (2013).py | 1,150 | 3.5625 | 4 | #-------------------------------------------------------------------------------
# Name: attendee.py
# Purpose: keeps track of name, company, state, and email address
#
# Author: Adrienne Sands
#
# Created: 22/05/2013
# Copyright: (c) Adrienne Sands 2013
#---------------------------------------------... |
3ca75c9d38a50e449c9dacc317045deff0a6f680 | bimarakajati/Dasar-Pemrograman | /Materi/Materi 7 Pengulangan Bersarang/nestloop.py | 329 | 4.03125 | 4 | for i in range(1,4): # Outer Loop
print ("Outer Loop ke - ",i)
for j in range(1,3): # Inner Loop
print (" - Inner Loop ke - ",j)
print("selesai")
a = 1
while (a < 4) :
print ("Outer Loop ke - ",a)
b = 1
while (b < 3) :
print ("* Inner Loop ke - ",b)
b+=1
a+=1
print ("")
print("s... |
b458910d53b2e63d4732adff493764bcc6ddc11d | Magorx/ray_tracing | /vector.py | 2,836 | 3.765625 | 4 | from math import sqrt, sin, cos
class Vector:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def dot(self, other):
return self.x * other.x + self.y * other.y + self.z * other.z
def cross(self, other):
return Vector(self.y * other.z - self.z * other.... |
f5d2c2ab691ae22d532358f7046c5847db421a17 | road-to-koshien/kevin-leetcode-challenge | /LEETCODE/coin change(WIP).py | 1,071 | 3.828125 | 4 | # You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.
# Example 1:
# Input: coins = [1, 2, 5], amount = 11
#... |
7040ff09c5d9c8ebf2a5a3cca5c05f912bb22e94 | wintersalmon/tic-tac-toe | /tests/test_board.py | 3,664 | 3.953125 | 4 | '''
TestCase For Board
'''
from unittest import TestCase, main
from tictactoe.board import Board
class TestBoardCreate(TestCase):
'''Represents Board Create TestCases'''
def test_crete_invalid_size(self):
'''Test Board Creation with INVLID number'''
self.assertRaises(ValueError, Board, 1)
... |
ab5dd6a3c424eac9a5ac8d1159b4476d2290e571 | abbyschantz/cs35 | /hw0/hw0pr2.py | 5,875 | 3.703125 | 4 | # hw0pr2.pr
#
# Eliana Keinan, Liz Harder, Abby Schantz
import os
import os.path
def count_files():
""" counts the number of .txt files in the folder
"""
L = os.listdir("phone_files")
os.chdir( "phone_files" )
count = 0
for foldername in L[1:]:
files = os.listdir(folde... |
9ba53a27428c23be311befd2bb5822d83eab8ef0 | mkozigithub/mkgh_info_python | /20190111 FCSA Learning Time/Files/PythonBeyondTheBasics/07_iterables_iteration/reduce.py | 899 | 4.1875 | 4 | # reduce repeatedly applies a function to elements of a sequence, reducing them to a single value
from functools import reduce
import operator
sum = reduce(operator.add, [1, 2, 3, 4, 5])
print(sum)
# functionally equivalent to:
numbers = [1, 2, 3, 4, 5]
accumulator = operator.add(numbers[0], numbers[1])
f... |
abd817de2e101f5c4e97a5096398d926dd6d4256 | siddharth20190428/DEVSNEST-DSA | /DI017_Binary_tree_level_order_traversal.py | 785 | 3.9375 | 4 | """
Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level).
----------------
Constraints
The number of nodes in the tree is in the range [0, 2000].
-1000 <= Node.val <= 1000
"""
from DI015_Trees import TreeNode
def levelOrder(root):
if... |
4083fb2b010e8d798ecbdf22fe69a75f40a78804 | vkd8756/Python | /ll/circular_doubly_ll.py | 2,098 | 3.6875 | 4 | class Node:
def __init__(self,data):
self.data=data
self.next=None
self.prev=None
class Cdll:
def __init__(self):
self.head=None
def epush(self,x):
temp=self.head
new_node=Node(x)
if not temp:
self.head=new_node
sel... |
d2bf036b43b44391f48f9a8e3f7d180ca777a6be | jaykiran/Beginner_Programming_challenges_lco | /python_answers/question6.py | 278 | 3.9375 | 4 | f = int(input("enter free bytes"))
u = int(input("enter used bytes"))
o = int(input("enter deleted bytes"))
n = int(input("enter created bytes"))
disksize = f+u
currentlyused = u-o
currentlyused = currentlyused + n
currentlyfree = disksize - currentlyused
print(currentlyfree) |
efa216210ab36330d6a58baf9f83952349f81c8f | ThyagoHiggins/LP-Phython | /Aulas e Exercicios/Exercicios/Lista 2/Exercicio 1.py | 789 | 3.875 | 4 | sal = float(input('Informe o salário: R$ '))
if sal <= 600.00:
desconto= sal*0.07
print(f'O valor de contribução ao INSS é de {desconto:.2f}\n'
f'Logo seu Salário final é R$ {sal-desconto:.2f}')
if sal >= 600.01 and sal <= 800:
desconto = sal * 0.08
print(f'O valor de contribução ao INSS é ... |
00c404216a2a2f4de4c8fa82c2ae341ce35e6f20 | FredThx/turing | /turing.py | 4,891 | 3.609375 | 4 | '''Une emulation de machine de turing
Exemple : voir siracuse.py
Auteur : fredThx
'''
class Turing:
'''Une machine de T.
'''
droite = 1
R = 1
D = 1
gauche = -1
G = -1
L = -1
b = " "
def __init__(self, etats = None, data = None, start_right = False):
'''
- eta... |
8d16e63f7eeaf5f9190f4bc3b7d4787e51a43e89 | ichsankurnia/Python-Basic | /list/string.py | 1,722 | 4.1875 | 4 | string = "HeLo PyThOn"
print("string: ", string)
print("string.capitalize()", string.capitalize())
print("string.upper()", string.upper())
print("string.lower()", string.lower())
print("string.casefold()", string.casefold())
print("'hello'.center(11,'-')", "hello".center(11,'-'))
print("string.count(o)", "hello python... |
5e653af5a3fb799c1cc33e2d0c5a2e8e8c691a57 | clintreyes/num_model | /count_substrings.py | 581 | 3.6875 | 4 | gene = 'AGTCAATGGAATAGGCCAAGCGAATATTTGGGCTACCA'
def freq(letter,text):
j = 0
for i in text:
if(i == letter):
j += 1
return j
print("The frequency of A in string gene is %d" %freq('A',gene))
print("The frequency of C in string gene is %d" %freq('C',gene))
print("The frequency of G in string gene is ... |
d8c6337fdac7d51141617fb028d3514118f2160a | srikanthpragada/PYTHON_27_AUG_2020 | /demo/funs/sorted_demo.py | 330 | 3.71875 | 4 | nums = [-10, 10, 20, 5, -50, 1]
names = ['Java', 'javascript', 'python', 'C#', "SQL"]
for n in sorted(nums, key=abs):
print(n, end=' ')
print("\nSorted Names ignoring case")
for n in sorted(names, key=str.upper):
print(n, end=' ')
print("\nSorted Names by length")
for n in sorted(names, key=len):
print(n... |
26c10d3b1ac6ccca2beababd253b5a3bd2f297f9 | shishengjia/PythonDemos | /数据分析/read_tab_delimited.py | 1,140 | 3.765625 | 4 | # encoding: utf-8
"""
@author: shishengjia
@time: 2017/10/12 下午12:45
"""
"""
this format can be read in almost the same way as CSV fles,
as the Python module csv supports so-called dialects that
enable us to use the same principles to read variations of
similar fle formats—one of them being the tab delimited format.... |
12c28a5a778a7764b41780b10fbd4324c369688d | Jungeol/algorithm | /leetcode/easy/172_factorial_trailing_zeroes/hsh2438.py | 439 | 3.53125 | 4 | """
https://leetcode.com/problems/factorial-trailing-zeroes/
Runtime: 68 ms, faster than 5.51% of Python3 online submissions for Factorial Trailing Zeroes.
Memory Usage: 12.8 MB, less than 100.00% of Python3 online submissions for Factorial Trailing Zeroes.
"""
class Solution:
def trailingZeroes(self, n: int) -> ... |
92578a4d2ea658a02029df6288200900ba1d402a | RainMoun/python_programming_camp | /day6/session_6.1.py | 2,151 | 3.578125 | 4 | menu_university = {
'浙江': {
'杭州': {
'下沙区': {
'杭州电子科技大学': {},
'浙江工商大学': {},
'浙江理工大学': {}
},
'西湖区': {
'浙江大学': {},
},
},
'宁波': {
'江北区': {
'宁波大学': {}
... |
d205c02a95d5c23852a46286401dffdd17a6246e | iphakman/playing_with_python | /exercises/faboulous_fred.py | 621 | 3.5625 | 4 | import random
L = []
R = []
def agregar1():
g = random.randint(1, 9)
L.append(g)
def adivina():
j = input("insert number: ")
R.append(int(j))
agregar1()
total = 0
cnt = 0
guess = 0
while guess == 0:
for a in L:
print("{}".format(a))
cuenta = len(L)
circulo = 0
while ... |
4423a39d17bb6e87d9e8cdb3db56ddaac686cf1d | mallireddy09/Python | /Programs/interview.py | 2,192 | 3.921875 | 4 |
1 What is Python?
2 What are the benefits of Python?
3 What are the key features of Python?
4 What type of language is Python? Programming or Scripting?
5 What are the applications of Python?
6 What is the difference between list and tuple in Python?
7 What are the global and local variables in Python?
8 Define... |
22d8bba70ab69f3ee2c253e273761562f391ebfe | urvashi04/python-task | /prob6.py | 845 | 3.890625 | 4 | #!/usr/bin/python3
#python Program which performs similar operation like "CAT" shell command
choice = int(input("Enter you Choice : \n 1. Cat \t2.Cat -b\t3.Cat -s\t4.Cat -E\n:"))
#OPEN the FILE
file=open("readfile.txt","r")
#Normal Reading like cat function
if choice==1:
print(file.read())
#With -b option
elif c... |
856b39c58639e7f4d3ccf6c518ff6ccf55951bc8 | wiput1999/Python101 | /1 Class 1/Homework/5.py | 260 | 3.609375 | 4 | import math
w = float(input("Weight :"))
h = float(input("Height :"))
M = math.sqrt((w*h)/3600)
D = 71.84*w**0.425*h**0.725/10000
B = 0.0003207*h**0.3*(1000*w)**(0.7285-0.0188**(3+math.log(10,w)))
print("Mosteller :",M)
print("Dubois :",D)
print("Boyd :",B) |
9e2975f5b69458ce9a9e888b756e06de98133169 | digant0705/Algorithm | /LeetCode/Python/389 Find the Difference.py | 1,135 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Find the Difference
===================
Given two strings s and t which consist of only lowercase letters.
String t is generated by random shuffling string s and then add one more
letter at a random position.
Find the letter that was added in t.
"""
import collections
class Solution(o... |
78c465e7092094239851d7aec9199840f12a068c | anc1revv/coding_practice | /leetcode/medium/single_number.py | 418 | 3.96875 | 4 | '''Given an array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?'''
def single_number(input_array):
for num in input_array:
return rev_string
def main():
input_a... |
131385104d133e4391a503f0effd9e27a915d03b | jaehyunan11/leetcode_Practice | /rotate_array.py | 1,811 | 3.84375 | 4 | # Input: nums = [1,2,3,4,5,6,7], k = 3
# Output: [5,6,7,1,2,3,4]
# Explanation:
# rotate 1 steps to the right: [7,1,2,3,4,5,6]
# rotate 2 steps to the right: [6,7,1,2,3,4,5]
# rotate 3 steps to the right: [5,6,7,1,2,3,4]
# Input: nums = [-1,-100,3,99], k = 2
# Output: [3,99,-1,-100]
# Explanation:
# rotate 1 steps to ... |
1504208b08ca80d8af779c500850ccf98f524f83 | allenkim/algorithm-work | /UVA/136-UglyNumbers/uglynumbers.py | 675 | 3.546875 | 4 | uglyNumbers = list();
uglyNumbers.append(1);
for i in range(1499):
x = uglyNumbers[0]
uglyNumbers.remove(x)
temp1 = 2*x
temp2 = 3*x
temp3 = 5*x
temp = temp1
j = 0
while j < len(uglyNumbers):
if uglyNumbers[j] > temp :
uglyNumbers.insert(j, temp)
elif uglyNumbers[j] < temp :
j += 1
continue
if t... |
cd565f682f43ed2859068fc76ce3b92af67a9819 | chin8628/Pre-Pro-IT-Lardkrabang-2558 | /Prepro-Onsite/W1_D3_Salary.py | 488 | 3.703125 | 4 | """ W1_D3_Salary """
def main(salary, addition):
""" this is function """
if salary >= 50000.01:
addition = 0.04
elif salary >= 25000.01:
addition = 0.07
elif salary >= 15000.01:
addition = 0.10
elif salary >= 7000.01:
addition = 0.12
else:
addition = 0.15... |
ca4149f385a7ff762da411ab7b033541d02d2e42 | Jian-jobs/leetcode-notes | /solutions/240.py | 797 | 3.640625 | 4 | """
{
"author": "Yucheng Huang",
"difficulty": "medium",
"link": "https://leetcode.com/problems/search-a-2d-matrix-ii/description/",
"beats": 0.1394,
"category": ["array"],
"tags": ["BST"],
"questions": []
}
"""
"""
思路
- 从右上角开始,类似BST的搜索
"""
class Solution:
def searchMatrix(self, matri... |
0f087446e76772475cbe1b2d2872454dfa24bcfc | MrHamdulay/csc3-capstone | /examples/data/Assignment_7/schmat029/util.py | 2,420 | 3.65625 | 4 | #-------------------------------------------------------------------------------
# Name: module1
# Purpose: creates grid functions for 2048
#
# Author: Matthias
#
# Created: 27-04-2014
# Copyright: (c) Matthias 2014
# Licence: <your licence>
#------------------------------------------... |
f417f3f1a7944249510d327fa307ac395f80d02c | llimllib/personal_code | /javascript/bitofphysics/data.py | 23,272 | 3.578125 | 4 | [
{"name": "lastbounce",
"title": "Last Bounce",
"explain_before": """Storing dx and dy as values is a way of saying which way
we are going. This can be done in other ways. the changes here use lastx and
lasty to calculate dx and dy. lastx,lasty simply says where we were last time.
The essential difference with the two... |
57a8102a0fbde9a2ebb592a4dc77a1a55c2db5bc | viphiter/pythonStudy | /demo1/test01.py | 337 | 3.71875 | 4 |
class Person(object):
def __init__(self,name,age):
print('自动构造对象',self)
self.name = name
self.age = age
def show(self):
print(f'姓名为:{self.name},年龄为:{self.age}')
def __del__(self):
print('对象销毁',self)
p = Person('苏大强','64')
p.show()
del p |
3064d072d30a61881997be0cfba155a6867d6426 | lennertjansen/dataprocessing | /Homework/Week3/convertCSV2JSON.py | 465 | 3.609375 | 4 | # Convert CSV to JSON
import csv
import pandas
import json
# open csv file and create and open json file
csvfile = open('2016_top19.csv', 'r')
jsonfile = open('2016_top19.json', 'w')
# specify the fieldnames of the columns of interest
fieldnames = ("Country", "gdp_per_capita")
# read into new json file and write th... |
2bacece6b82e5e442d68e9c4b5b8f42e817d104f | JianboTang/a2c | /a2c.py | 2,500 | 3.5625 | 4 | # -*- coding: utf-8 -*-
""" Convert to Chinese numerals """
# Define exceptions
class NotIntegerError(Exception):
pass
def to_chinese(number):
""" convert integer to Chinese numeral """
chinese_numeral_dict = {
'0': '零',
'1': '一',
'2': '二',
'3': '三',
'4': '四',
... |
252151be7bff8f1a086aa320a8c179b316b576b9 | SergiBaucells/DAM_MP10_2017-18 | /Tasca_1_Python/src/exercici_2_python.py | 565 | 3.859375 | 4 | def calcula_qualificacio(puntuacio):
if puntuacio > 1.0:
resultat = "Ha de ser entre 0.0 i 1.0!!!"
elif puntuacio >= 0.9:
resultat = "Excel·lent"
elif puntuacio >= 0.8:
resultat = "Notable"
elif puntuacio >= 0.7:
resultat = "Bé"
elif puntuacio >= 0.6:
resultat... |
ee347129aca4f85feadf7d652a9f18aabaaa0d2b | drgmzgb/Python-Advanced- | /#2 Tuples and Sets/Py Adv 2L2 Average Student Grades.py | 682 | 3.984375 | 4 | # Py Adv 2L2 Average Student Grades - using dictionaries, average
# input / 4
# Scott 4.50
# Ted 3.00
# Scott 5.00
# Ted 3.66
# output / Ted -> 3.00 3.66 (avg: 3.33)
# Scott -> 4.50 5.00 (avg: 4.75)
grades = int(input())
res = {}
for n in range(grades):
name, grade = input().split()
if name not in res:
... |
bab0914cec7c850bcc9e28e64cfb56b6cda86867 | cddas/python27-practice | /exercise-1.py | 479 | 4.09375 | 4 | import time
name, age = raw_input("Give me your name and age: ").split(" ")
years_to_centenary = 100 - int(age)
current_year = time.strftime("%Y")
current_year = int(current_year)
message = "Hi " + name + ". You will turn 100 years in the year - " + str( current_year + years_to_centenary )
repeat_times = ... |
1534e6f44547a52966ba3655305444554e607fc5 | agonzalez777/Sphero-BB8-Phone-Home | /spheroBB8_phone_home.py | 5,658 | 3.8125 | 4 | import urllib2
import requests
from datetime import datetime
import json
from math import radians, cos, sin, atan2, degrees, asin, sqrt
import time
import sys
import BB8_driver
import pytz
iss_pass_url = "http://api.open-notify.org/iss-pass.json"
iss_now_url = "http://api.open-notify.org/iss-now.json"
def calculate_i... |
e26ed640de1c229f0592a5489998371b8544bcb0 | quinnajames/lexcheck | /lexcheck.py | 1,464 | 3.578125 | 4 | import sys
from collections import defaultdict
def alphagramify(word):
alphagram = ''.join(sorted(list(word)))
return alphagram
def find_typos(list_of_lists):
typo_lines = []
for num, answers in enumerate(list_of_lists,start=1):
if answers == None:
typo_lines.append(num)
return... |
fb0eeafe7eb45b469d151b4ed7e97672191d87b6 | buy/leetcode | /python/15.three_sum.py | 1,153 | 3.703125 | 4 | # Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
# Note:
# Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
# The solution set must not contain duplicate triplets.
# For exampl... |
6cb22747e3870ac4b4ad00bd20e1421a9b4cb35a | bmanandhar/python-practice | /06_morse_encode.py | 1,495 | 4.3125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 17 09:44:12 2018
@author: bijayamanandhar
"""
# 06 Morse Encode
# Build a function, `morse_encode(str)` that takes in a string (no
# numbers or punctuation) and outputs the morse code for it. See
# http://en.wikipedia.org/wiki/Morse_co... |
0c87119b5214805f2db3cdfc1087bc785cb7bec0 | 3rmack/python_proj | /str.format.py | 1,158 | 3.796875 | 4 | s = "{0} was {age}. {age} is a good age."
y = s.format("nick", age="25")
print(y)
list = ["one", "two", "three"]
pattern = "1 is {0[0]}, 2 is {0[1]}, 3 = {0[2]}"
str = pattern.format(list)
print(str)
import decimal
print("{0} {0!s} {0!r} {0!a}".format(decimal.Decimal("93.4")))
print("{0} {0!s} {0!r} {0!a}".format("df... |
fbfca29f454d252100bf18ed9d2f7e48a6620609 | pdvelez/miscellaneous_exercises | /recursion/sum_positive_integers.py | 423 | 4.0625 | 4 | """
This exercise can be found at
http://www.w3resource.com/python-exercises/data-structures-and-algorithms/python-recursion.php
"""
def sum_positive_integers_mult_2(n):
"""
Sum of positive integers of n+(n-2)+(n-4)...(until n-x <= 0)
"""
if n <= 0:
return n
else:
return n + sum_p... |
1ddfb71d135632b5f732bd61725419a4308769c4 | dararod/python-101 | /cashier/app.py | 1,413 | 3.96875 | 4 | # Aplicacion de Maquina Registradora
# int = Integer (EN) -> Numero Entero (ES)
# str = String (EN) -> Cadena de Caracteres (ES) Textos o Letras
def caja_registradora():
lista_de_productos = obtener_lista_de_productos()
mostrar_resumen(lista_de_productos)
def crear_producto(nombre_del_producto, precio):
prod = ... |
2444527d25b4063875ef45f20aaaaaff82299ffe | vipulshah31120/PythonDataStructures | /JugglingAlgo.py | 1,115 | 3.9375 | 4 | #d = by which number we want to rotate
# Function to left rotate arr[] of size n by d
def leftrotate(arr, d, n) :
g_c_d = gcd(d, n) #d = d % n
for i in range (g_c_d) :
temp = arr[i] # move i-th values of blocks
j = i
while 1 :
k = j+d ... |
6909396573a8bd7e1df2f306d8d1ea539334fd7b | cq146637/Advanced | /6/6-4.py | 877 | 4.0625 | 4 | """
创建可管理的对象属性
"""
from math import pi
class Circle(object):
"""
使用内置的property函数为类创建可管理属性
fget,fset,fdel对应相应的属性
"""
def __init__(self, radius):
self.radius = radius
def getRadius(self):
# 使用访问器使得取值能够更加灵活,并且能隐藏相关的操作
return self.radius
def setRadius(sel... |
d4683b1cdfab0273c172533dadf29202a04e263a | SandyHoffmann/ListasPythonAlgoritmos | /Lista 1/SH-PCRG-AER-Alg-01-Ex-13.py | 249 | 3.90625 | 4 | #Pegando base e altura
b = float(input("Me de a base do triangulo: "))
h = float(input("Me de a altura do triangulo: "))
#Fazendo o calculo de área de triangulo
calculo = (b*h)/2
#Exibindo resultado
print(f'A área do triangulo é de {calculo}')
|
6ae4cad02e48d8a353a104753c2cc5f539536aa0 | DavidMutchler/RoseboticsCS1Tools | /Grader/csse120-grading/201430/Session16_Test2_201430/solution/src/m2.py | 4,632 | 3.84375 | 4 | """
Test 2, problem 2.
Authors: David Mutchler, Chandan Rupakheti, their colleagues,
and SOLUTION by David Mutchler. April 2014.
""" # DONE: PUT YOUR NAME IN THE ABOVE LINE.
def main():
""" Calls the TEST functions in this module. """
test_problem2a()
test_problem2b()
def test_problem2a(... |
399757235de5ba4badd976d78699a0f622430a8e | manuel-martinez-dev/rps_1 | /rps beta 1.py | 3,953 | 4.125 | 4 | #!/usr/bin/env python3
"""This program plays a game of Rock, Paper, Scissors between two Players,
and reports both Player's scores each round."""
import random
import sys
from colorama import init
from colorama import Fore, Back, Style
print(Fore.RED, Style.DIM + "Are you ready to play ROCK, PAPER, SCISSORS?"'\n')
pri... |
619de3e1284ac42a2e492a9b79895b6d75dd5b37 | git874997967/LeetCode_Python | /mid/leetCode3.py | 787 | 3.71875 | 4 | #3. Longest Substring Without Repeating Characters
def lengthOfLongestSubstring2(s):
# use the queue to save length only but not the actual string
dq, result = [],0
for char in s:
while char in dq:
dq.pop(0)
dq.append(char)
result = max(result, len(dq))
return resul... |
434f97d4ac50db41bcd1b7b4a56760417119a835 | alaguraja006/pythonExcercise | /listEx.py | 305 | 3.71875 | 4 | ls = [10,20,'hai',-10,23.03]
print(ls)
print(ls[3])
print(ls[3:5])
print(ls*3)
print(len(ls))
print(ls[::-1])
ls.append(40)
print(ls)
ls.remove('hai')
print(ls)
del(ls[1])
print(ls)
ls.insert(1,1000)
ls.sort()
print(ls)
ls.sort(reverse=True)
print(ls)
print(max(ls))
print(min(ls))
ls.clear()
print(ls) |
de3af90f7ce91bca90328ad11e1bc1103e38f483 | d4rkr00t/leet-code | /python/leet/950-reveal-cards-in-increasing-order.py | 584 | 3.546875 | 4 | # Reveal Cards In Increasing Order
# https://leetcode.com/problems/reveal-cards-in-increasing-order/
# medium
import collections
def deckRevealedIncreasing(deck: [int]) -> [int]:
N = len(deck)
index = collections.deque(range(N))
ans = [None] * N
for card in sorted(deck):
ans[index.popleft()] ... |
95336dd2dae8606c598432134d0df67bf7eb88aa | joyce04/coding_practice | /algorithm_practice/recursion/reverse_string.py | 393 | 3.6875 | 4 | # reverse a string
def reverse_loop(sent):
n_str = []
for i in range(len(sent)-1, -1, -1):
n_str.append(sent[i])
return ''.join(n_str)
def reverse_recursive(sent):
size = len(sent)
if len(sent) == 1:
return sent
last_char = sent[size-1]
return last_char + reverse_recursive(sent[0:size-1])
pri... |
4d2e78a90cc9bb35658e3cc7d090d6363f029963 | Juan128524/proyecto1 | /main.py | 133 | 3.53125 | 4 | print("HOLA")
print("bienvenido al mundo de python")
print("Nombre: Juan Avila")
print("Paralelo: Septimo C")
i=8
c=10
a=i*c
print(a)
|
2787e04b5298440019ebcaae48e8bad4d2b2385f | claudioPOO/ejericio2-unidad3 | /claseManejadorHelado.py | 1,870 | 3.6875 | 4 | from claseHelado import Helado
from claseSabor import Sabor
class ManejaHelado:
__pedido=[]
def __init__(self):
self.__pedido=[]
def cargarPedido(self,sabores):
i=len(self.__pedido)
print('Carga de pedidos(finalice con 0)-------')
pedido=int(input('Numero de pedido: ... |
4bfd96041b6901b1d920f86b358063e9d2a806bd | rsiew11/TicTacToe | /main.py | 8,336 | 3.765625 | 4 | from Tkinter import Tk, Button, Label
from tkFont import Font
from Board import Board
import socket
class GUI:
def __init__(self):
self.app = Tk()
self.app.title('TicTacToe')
self.app.resizable(width=False, height=False)
self.font = Font(family="Helvetica", size=100)
self.bo... |
d7d25a847ca805c5161e5c043fcff2704ff1719b | avonhatten/trumpSlackBot | /slackbot/trump.py | 458 | 3.515625 | 4 | #!/usr/bin python
import os
from donaldbot import DonaldBot
theDonald = DonaldBot()
# Get the current directory's path
dirname = os.path.dirname(os.path.abspath(__file__))
# Construct the path to the book
book = os.path.join(dirname, 'trumpData.txt')
# Have the bot read the book
theDonald.read(book)
response = raw_... |
d6228eac499e8a4e3b8dad41873d3606395f1667 | dhermes/project-euler | /python/complete/no042.py | 1,254 | 3.953125 | 4 | #!/usr/bin/env python
# By converting each letter in a word to a number corresponding to
# its alphabetical position and adding these values we form a word
# value. For example, the word value for SKY is
# 19 + 11 + 25 = 55 = t_(10). If the word value is a triangle number
# then we shall call the word a triangle word.... |
9fbb155a090664cced56bf6deeb5f229a70aca70 | bthowe/data_science | /estimation/statistics/statistical_tests/a_b_testing/bayesian_a_b.py | 1,072 | 3.59375 | 4 | import numpy as np
import matplotlib.pyplot as plt
def calc_distributions(successes_A, failures_A, successes_B, failures_B, num_samples=1000):
"""Draws num_samples from beta distributions where alpha and beta are determined by the number of successes and
failures. This only holds for binary outcome since beta ... |
17f8b6715d8006f8d04176b7bfc80eb62b7cf693 | rydevera3/A-Primer-on-Scientific-Programming-with-Python-Solutions | /Chapter 1/1plus1.py | 372 | 3.984375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jul 31 21:32:07 2014
@author: rdevera
"""
# Chapter 1: Exercise 1
# The first exercise concerns some very basic mathematics. Write a Python program
# that stores of the result of the computation 1+1 in a variable and then prints the
# value of the variable.
# assign a vari... |
66b96196ed88e96bca4c8d9b3f130ca058e6c368 | meghnavarma0/DSA-Python | /DP/ugly.py | 409 | 3.640625 | 4 | def maxDiv(a, b):
while a % b == 0:
a /= b
return a
def isUgly(no):
no = maxDiv(no, 2)
no = maxDiv(no, 3)
no = maxDiv(no, 5)
return 1 if no == 1 else 0
def nthUgly(n):
i = 1
count = 1
while count < n:
i += 1
if isUgly(i):
count += 1
ret... |
6b011144b50b1584ba3bf72b0087022165202155 | tangly1024/learning_python | /Chapter-4-Functional-Programming/higher_function_return_function.py | 1,956 | 3.734375 | 4 | # coding=utf-8
"""
函数作为返回值
“闭包(Closure)” 相关参数和变量都保存在返回的函数
"""
"""
举例,可变参求和函数
"""
def calc_sum(*args):
ax = 0
for n in args:
ax = ax + n
return ax
# 但是,如果不需要立刻求和,而是在后面的代码中,根据需要再计算怎么办?可以不返回求和的结果,而是返回求和的函数:
def lazy_sum(*args):
def sum():
ax = 0
for n in args:
ax =... |
98b85680f2a2981ea1b34be126fbc1fff7784762 | aravindsbr/json_parser | /test_json_parser.py | 786 | 3.515625 | 4 | import unittest
import json
from json_parser import json_data, extracting_values_from_json
from unittest.mock import patch
class JSONParserTest(unittest.TestCase):
def test_extracting_values_from_json(self):
"""
Unit test case to test the json_extract function
"""
# expected
... |
4e1e184f9ad078411889a6b4f1102790fc0d3e7b | bak-minsu/geditdone | /geditdone/generichelpers.py | 339 | 3.75 | 4 | class Stack:
items = []
def __init__(self, items = []):
if items != None and len(items) > 0:
self.items = items
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[-1] if len(self.i... |
0cdff944d2ec29ef309a3a990b93a1454aef8237 | mrdhindsa/Artificial-Intelligence | /tictactoe/tictactoe.py | 4,495 | 3.984375 | 4 | """
Tic Tac Toe Player
"""
import math
import copy
X = "X"
O = "O"
EMPTY = None
def initial_state():
"""
Returns starting state of the board.
"""
return [[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY]]
def player(board):
"""
Returns player who h... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.