blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
a6dfbaef0f73c44129e38d93bc199b37b44753eb | Bahram3110/d2_w1_t2 | /task2.py | 586 | 4.46875 | 4 | s = "Hello Python3"
print(len(s))
#Task 2
"""
Write a script that takes
in a string and prints its length.
HINT:
Question: What do you mean by length?
Answer: The character count of a string.
Ex: 'hello!' # --> 6
"""
#Translate
#Задача 2
#«»»
#Написать сценарий, который принимает
#в строку и печатает ее длину.
#ПОДСК... |
a83738a443e36f36ff112211b04f8d06c2d619fd | alexsoulfear/hillel_homework | /testing_task_7.py | 346 | 3.890625 | 4 | def fibonaci_nums_sum(leingth_of_the_string):
fibonaci_nums = ['1', '1']
sum = 0
for i in range(leingth_of_the_string - 2):
fibonaci_nums += [str((int(fibonaci_nums[i + 1])) + (int(fibonaci_nums[i])))]
for i in range(leingth_of_the_string):
sum += int(fibonaci_nums[i])
return print(s... |
6f4cb546a1b21960580c43910a6dd28bde012312 | czr1803/kryptos | /ml/ml/feature_selection/xgb.py | 2,683 | 3.578125 | 4 | import operator
import random
def xgb_embedded_feature_selection(model, importance_type='all', percentage=0.9):
"""Perform feature selection using XGBoost embedded method.
Args:
model(xgboost.core.Booster): XGBoost model trained.
importance_type(string):
'weight' - the number of t... |
e394b207d5de82626ff03d0a2324f7706de4821e | shabbirkagalwala/Python-AutomateTheBoringStuffWithPython | /tableprinter.py | 817 | 3.703125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 23 22:24:37 2017
@author: shabbirkagalwala
"""
tableData = [
['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']
]
def colWidth(tableData):
colWidths = [0] * len(... |
27fe70fa450d1c0717f2d95258a459f661c0d503 | tstokes64/python-challenge | /PyBank/main.py | 1,177 | 3.53125 | 4 | import csv
import os
import sys
sys.stdout = open("Solutions_PyBank.txt", "w")
with open('budget_data.csv', newline= '') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
next(csv_reader)
months = []
profits_losses = []
monthly_net = []
for row in csv_reader:
month... |
5ae35a77414600a564e65a175e39c781591e325e | takatogoto/textmining | /code/ch05/list5-3_n-gram-frequency-sentense-generation.py | 2,288 | 3.546875 | 4 | # -*- coding: utf-8 -*-
# リスト 5-3 生成した単語 N-gram 頻度データから文を生成するプログラム例
def gennext(words, dic): # N-gram辞書dicと直前の1語/2語から、次の語を選んで返 す
grams = len(words) # 2-gramか3-gramかを、与えたwordが2語か3語かによっ て決める
if grams==2:
matcheditems = np.array(list(filter( (lambda x: x[0][0] == words[1]),
dic.items() )... |
1e15a1b90359244ec0adf4e2bdf46285fd0dc390 | Agnesyuan/leetcode_ | /numsum_#167.py | 1,044 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。
函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2。
说明:
返回的下标值(index1 和 index2)不是从零开始的。
你可以假设每个输入只对应唯一的答案,而且你不可以重复使用相同的元素。
示例:
输入: numbers = [2, 7, 11, 15], target = 9
输出: [1,2]
解释: 2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。
"""
class Solution:
... |
8a6ab9b2d7683f159a56009f3237cc6553b764de | ogzhnxd/Pirple-Python-is-Easy | /Pirple Python is Easy/Project 1 - Connect 4/Connect 4.py | 7,007 | 3.6875 | 4 | ##################################################
## Project #1: Connect 4
##################################################
## Author: Oğuzhan GÜVERCİN
## Author Email: ogzhngvrcn00@gmail.com
##################################################
# Importing needed libraries
from termcolor import colored, cprint
# Ini... |
b47a85223a43a52e4f95fcbc4cb82a7fd9389b35 | sxu11/Algorithm_Design | /Basic/P253_MeetingRoomsII.py | 1,342 | 3.8125 | 4 |
'''
Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), find the minimum number of conference rooms required.
Example 1:
Input: [[0, 30],[5, 10],[15, 20]]
Output: 2
Example 2:
Input: [[7,10],[2,4]]
Output: 1
'''
# Definition for an interval.
# class Interval... |
fbe6b1aca63ff600a95ea0ec493483bd500c18ba | Voltaire-EGY/projects | /ch2.py | 186 | 4.21875 | 4 | def oddoreven(a):
if a.is_integer() is True:
return "This number is even"
else:
return "This number is odd"
print(oddoreven(float(input("Enter a number: "))/2))
|
a4885fa24e4199155e25514e539c7e4234c8f7f6 | bio-tarik/PythonUnitTesting | /pytest/Proj02/test_foocompare.py | 496 | 3.796875 | 4 | """
Learning unit testing on Python using py.test.
Tutorial: https://docs.pytest.org/en/latest/assert.html
"""
class Foo(object):
"""
Type created to exemplify the usage of conftest.py
"""
def __init__(self, val):
self.val = val
def __eq__(self, other):
return self.val... |
f4fc8bc05a80ab38c83cc439e05fc9aeab0c9595 | Long0Amateur/Self-learnPython | /Chapter 6 Strings/Problem/8. Student vs Prof addresses.py | 457 | 4.3125 | 4 | # A program prints out a message indicating either all addresses
# are student or professor addresses entered
# @.student.college.edu and @prof.college.edu
n = eval(input('How many email addresses you will be entering?'))
for s in range(n):
s = input('Enter those addresses:')
if s[-20] in '@stud... |
765a04c3a56b33c7c0f770fb33a65b0d04652b42 | rayanamounikarani/rayanamounikarani | /table.py | 235 | 3.671875 | 4 | '''
n=int(input())
for i in range(1,n+1):
for j in range (1,11):
print("{} * {} = {}".format(i,j,i*j),end=" ")
print()
'''
i=1
sum1=0
while i<=10:
print(i,end=' ')
sum1=sum1+i
i=i+1
print("\n",sum1)
|
59239c6d0ff812b9c5147d019e78100807fcb5ad | sung2ne/python_study | /project_bmi/01.bmi.py | 420 | 3.75 | 4 | """
1. BMI 지수 : 체중(kg) / 키(m)^2
1. BMI 지수 : 체중(kg) / (키(cm)/100)^2
"""
# 거듭제곱을 구하는 함수
def pow(v):
return v**2
# 키 입력
w = int(input("체중(kg)을 입력해주세요 : "))
t = int(input("키(cm)를 입력해주세요 : "))
# BMI 지수 계산
bmi = w / pow(t / 100)
if bmi < 18.5:
print("저체중")
elif bmi >= 25:
print("비만")
else:
print("정상")
|
07c8b6b29926288d91dd4c2448869a033c51c55f | JackZhao604/TEST | /test/lianbiao/check_cicle.py | 1,231 | 3.5625 | 4 | #!/user/bin/python
# -*- coding=utf-8 -*-
# 给定一个链表,判断链表中是否有环。
#
# 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
#
#
#
# 示例 1:
#
# 输入:head = [3,2,0,-4], pos = 1
# 输出:true
# 解释:链表中有一个环,其尾部连接到第二个节点。
class Node():
def __init__(self,item):
self.item = item
self.next = None
... |
9b967aeeec7f5d33d32e9fe34f3dffec1714f67a | orifake/leetcode-python | /src/Occurrences After Bigram.py | 441 | 3.671875 | 4 | from typing import List
class Solution:
def findOcurrences(self, text: str, first: str, second: str) -> List[str]:
words = text.split()
ans = []
for i in range(len(words) - 2):
f, s, t = words[i], words[i + 1], words[i + 2]
if f == first and s == second:
... |
4f8fcf6c80495eb0514dca2e986a72e0efc623e1 | wei4444/leetcode-solutions | /172 Factorial Trailing Zeros/172-1.py | 234 | 3.578125 | 4 | # time log(n), space 1
class Solution:
def trailingZeroes(self, n: int) -> int:
i = 5
r = 0
while(i <= n):
r += n // i
i *= 5
return r
print(Solution().trailingZeroes(200)) |
e01d198d1eb700dd50b8faa9d52290d793967600 | alvillaraza/Data-Structures | /binary_search_tree/binary_search_tree.py | 5,091 | 4.25 | 4 | """
Binary search trees are a data structure that enforce an ordering over
the data they store. That ordering in turn makes it a lot more efficient
at searching for a particular piece of data in the tree.
This part of the project comprises two days:
1. Implement the methods `insert`, `contains`, `get_max`, and `for... |
602aac143326fd69a95fe90fa9b23261ab73484a | sayan1995/Binary-Search-4 | /problem3.py | 817 | 3.71875 | 4 | '''
Time Complexity: O(max(nlogn, mlogm)) -> Which ever sorting is greater
Space Complexity: O(k) -> k is To save the result of the intersection
Did this code successfully run on Leetcode : Yes
Explanation: Use 2 pointer approach to find the intersection of the 2 arrays
'''
class Solution:
def intersect(self, nums... |
0bfc383d5796bb013fed1c2be69c54b6fd9150e7 | yyildiz/London-Tubes | /main.py | 628 | 3.609375 | 4 | import csv
N = 5
start_point = "East Ham"
visited = []
current_stops = [start_point]
for i in range(N):
temp = []
visited.extend(current_stops)
for stop in current_stops:
f = open("tubeLines.csv", "r")
reader = csv.reader(f)
for row in reader:
if(row[... |
73273565ae047b4f268175f6a3261f29a6d50f02 | amandamorris/codewars | /who_likes_this.py | 529 | 3.90625 | 4 | def likes(names):
"""Returns text describing the names that like a post"""
length = len(names)
if not names:
return "no one likes this"
elif length == 1:
return "%s likes this" % (names[0])
elif length == 2:
return "%s and %s like this" % (names[0], names[1])
elif len... |
2920c6938085ca347dbcf4bf10ae03864b3fa4cc | MostlyFocusedMike/work_schedule | /json_functions.py | 1,350 | 3.875 | 4 | import json
from collections import OrderedDict
def read_list(file):
'''
Reads file and stores it as a list.
If the file is empty, it returns an empty list
'''
try:
with open(file) as f_obj:
contents = json.load(f_obj)
except FileNotFoundError:
contents = []
retu... |
30cf6ce4e17b11b737037403033fb10a5acbdb23 | blaire101/LeetCode | /lcof_finger/Array/easy.findNumberIn2DArray.py | 887 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
@file: easy.findNumberIn2DArray.py
@date: 2020-10-06 11:23 AM
@desc: 剑指 Offer 04. 二维数组中的查找
@url : https://leetcode-cn.com/problems/er-wei-shu-zu-zhong-de-cha-zhao-lcof/
"""
# [
# [1, 4, 7, 11, 15],
# [2, 5, 8, 12, 19],
# [3, 6, 9, 16, 22],
# [10, 13, 14, 17,... |
37f2a21c9da41bb4aa24fe5f50506cfd37829b6f | xiaomojie/NowCoder | /offer/61.扑克牌中的顺子.py | 1,214 | 3.78125 | 4 | # -*- coding:utf-8 -*-
"""
从一副扑克牌中抽5张,判断这五张是否是连续的,2~10为数字本身,A为1,J为11,Q为12,K为13,大小王为可以变成
"""
'''
思路:输入的就是数字,0表示的是大小王,首先先对数组排一个序,然后统计0的个数,然后在遍历数组统计gap的个数,
如果前一个元素和后一个元素相等,那么直接返回false,如果不想等则计算gap值,最后比较0的个数是不是大于等于gap值。
'''
class Solution:
def IsContinuous(self, numbers):
# write code here
if not number... |
5e972e48e00bee73a40a082e2adbe66528b34416 | Korimse/Baekjoon_Practice | /baekjoon/1920.py | 518 | 3.59375 | 4 | n = int(input())
nlist = list(map(int, input().split()))
m = int(input())
mlist = list(map(int, input().split()))
def binary_search(a, start, end, target):
while start <= end:
mid = (start+end)//2
if target == a[mid]:
return True
elif target < a[mid]:
end = mid -1
... |
4b0d474aadc9ca7e706aedff09a4bc27678918e0 | chrisortman/CIS-121 | /k0765197/assignment03.py | 443 | 3.890625 | 4 | name = raw_input("What is your name? ")
quest = raw_input("What is your quest? ")
if len(name) + len(quest) > 20:
airspeed_velocity_of_an_unladen_swallow = raw_input("What... is the airspeed velocity of an unladen swallow? ")
if len(name) + len(quest) == 20:
favorite_color = raw_input("What... is your favor... |
7263bef64f220c27d9f465ce04252e48fffba5f8 | mikenavarroro/ProgramacionII | /Challenge/nemo.py | 250 | 3.515625 | 4 | n = int(input())
cadena = input()
position = 1
for i in range(len(cadena)):
if cadena[i] == ' ':
position += 1
if cadena[i] == 'N' and cadena[i+1] == 'e' and cadena[i+2] == 'm' and cadena[i+3] == 'o':
print(position)
|
85b12f4a1999e778a6dc5bcd283d901b09367eb0 | npricejones/chemspacedim | /chemspacedim/tools/__init__.py | 1,879 | 3.78125 | 4 | import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
fs = 20
def histogram2d(x,y,bins=100):
"""
Create a 2D histogram of data represented by the two dimensions x and y
x: Array of data values in 'x'
y: Array of data values in 'y'
bins: Number o... |
2dc98b327c0432e1953be64d91144b35932b301e | MohammadUmer526/PythonCrashCourse | /Chapter05/If Statements.py | 2,599 | 4.1875 | 4 | cars=['audi','bmw','toyota']
'''
#checking equality
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
bike='honda'
bike=='honda'
print(bike)
'''
''''
#checking inequality
request_topping = 'mushrooms'
if request_topping != 'anchovies':
print("Hold the anchovie... |
854a5787aa52633bfbd8f5acaf6b109d0646b065 | PilarPinto/holbertonschool-machine_learning | /math/0x02-calculus/17-integrate.py | 536 | 3.8125 | 4 | #!/usr/bin/env python3
'''Integral of a polynomial'''
def poly_integral(poly, C=0):
'''Polynomial integrate'''
if type(poly) is not list or len(poly) == 0 or type(C) is not int:
return None
intg_list = [C]
for index in range(len(poly)):
if type(poly[index]) is not int and type(poly[... |
632fd381e125d058929821b4192f35f081b20a73 | n1rjal/DSA-JS | /Sorting/mergeSort vs bubbleSort.py | 1,544 | 3.828125 | 4 | from datetime import datetime
import math
import random
def merge(arr1, arr2):
i = 0
j = 0
arr1_length = len(arr1)
arr2_length = len(arr2)
result_arr = []
while i < arr1_length and j < arr2_length:
if arr1[i] < arr2[j]:
result_arr.append(arr1[i])
i += 1
... |
a5c20cdde210ce8e14d1f71c216d53d3b32a7599 | mmariani/meuler | /009/009.py | 299 | 3.828125 | 4 | #!/usr/bin/env python3
def triplet(tot):
for a in range(1, tot+1):
for b in range(a+1, tot+1-a):
c = 1000-b-a
if a*a + b*b == c*c:
return(a, b, c)
def run():
a, b, c = triplet(1000)
print(a*b*c)
if __name__ == '__main__':
run()
|
e63631ca6d1a15e933c94264acbbb29d959a325b | elsayed-hussein/ProgrammingFoundationsCourses | /02.BeyondTheFundamentalsCourse/Ch06/add-values.py | 982 | 3.515625 | 4 | # define the sourse of data as a file with r- reading, t- text mode
infile = open('values.txt', 'rt')
# define where the output distenation of data as a file with w- writing, t- text mode
outfile = open('values-totaled.txt', 'wt')
print('Processing input')
sum = 0
# for loop will check each line of the source file ... |
ab40170a736a3adf0a601b43e84156b65be8c88d | panchyni/PseudogenePipeline | /_pipeline_scripts/1_2_A_1_getBlastFromOrtho.py | 1,210 | 3.515625 | 4 | #This script is intended to take an ortholog file with just two gene names
#and remove lines from a blast to create an m8 blast results file with only
#the orthologous gene pairs specified by the ortholog file
#Created by David E. Hufnagel on 3-8-2012
"""
Algorithm:
1) iterate through ortholog file
a) iter... |
d2e85fb59f9234522742b22dc31af7da1ca282de | Aasthaengg/IBMdataset | /Python_codes/p03547/s138804955.py | 130 | 3.9375 | 4 | X, Y = input().split()
x_i = ord(X)
y_i = ord(Y)
if x_i < y_i:
print('<')
elif x_i > y_i:
print('>')
else:
print('=')
|
976e1c9b6c79cf908b518802d881917f87387c09 | carolynyen/DojoAssignments | /Python/parenvalid.py | 395 | 3.625 | 4 |
def parenvalid(str):
countleft = 0
countright = 0
for i in range(len(str)-1, 0, -1):
if str[i] == ')':
countright += 1
if str[i] == '(':
countleft += 1
if countleft > countright:
return False
if countleft != countright:
return False
... |
0818d0dcc339669d7d3bf46c206aecd992984ed9 | hackademymx/future-developers-practica | /Agustina-Lorenzo.py | 336 | 3.875 | 4 | dia= int(input("Ingrese un numero: "))
if dia == 1:
print ("Lunes")
elif dia == 2:
print ("Martes")
elif dia == 3:
print ("Miercoles")
elif dia == 4:
print ("Jueves")
elif dia == 5:
print ("Viernes")
elif dia == 6:
print ("Sabado")
elif dia == 7:
print ("Domingo")
else:
print ("El nume... |
4fd551b6218992caafee36223c6552842d8e1e98 | hj-merry/dayworkspace | /acm/ACM/cf/BoyorGirl.py | 87 | 3.59375 | 4 | str1 = set(list(input()))
print("CHAT WITH HER!" if len(str1)%2==0 else "IGNORE HIM!")
|
5ff750923774ae9cf2833dcb45b9c7b535370724 | wttttt-wang/leetcode_withTopics | /Array/Stack/mini-parser**.py | 1,384 | 3.6875 | 4 | """
Mini Parser
@ Stack
@ Corner case: 1. "[]" vs "[0]" 2. "12" or "-123" (single number not list)
@ Note: we need 'l' to record the start ind of an number to take care of empty number
(Different from 'basic-calculator' where number=0 can also be putted to stack as it has no effect to final result.)
"""
class ... |
071204fcdc28108483ad5953cc902493d45a6de1 | gowthambittu/python-learning | /Longest_prefix.py | 340 | 3.65625 | 4 | def longestprefix(strs):
l_prefix=""
shortest_str= min(strs,key=len)
if not strs:
return l_prefix
for i in range(0,len(shortest_str)):
if(all([x.startswith(shortest_str[:i+1]) for x in strs])):
l_prefix= shortest_str[:i+1]
else:
break
return ... |
b02288d2843c4ce4ddd1647530f01d05b1a04836 | BiplabG/python_tutorial | /Session II/problem_4.py | 402 | 4.3125 | 4 | """4. Write a python program to print first n fibonacci sequence. Take n input from the user.
Hint: A fibonacci sequence follows this rule: F(n+1) = F(n) + F(n-1) where first two numbers are 0 and 1 of the sequence.
0 1 1 2 3 5 8 13 ..."""
num = int(input("Enter the number you want fibonacci sequence up to: \n"))
a... |
90bc5361c60d5f5fea0748b963b2674819af0724 | jscarlton/pythonScripts | /reimbeerse/reimbeerse.py | 684 | 3.859375 | 4 | #!/usr/bin/python
# Calculator for subtracting alcohol amounts from reimbursements
total = raw_input("Please enter the total bill: ")
food = raw_input("Please enter the amount spent on food: ")
alcohol = raw_input("Please enter the amount spent on alcohol: ")
total = float(total)
food = float(food)
alcohol = float(al... |
6fb151bcb55289059da69f9415e3d904d2d73d5d | ArtemiiLulevich/-pythonProgramming | /modImport/dateAndTime.py | 632 | 3.59375 | 4 | # import time
#
# print("Epoch on this system starts at " + time.strftime('%c', time.gmtime(0)))
#
# print("Time zone {0} - {1}".format(time.tzname[0], time.timezone))
#
# if time.daylight != 0:
# print("\tDaylight Saving Time is in effect for this location")
# print("\tThe DST timezone is " + time.tzname[1])
#... |
f61bcb24445b4eedc14a3cfb353d4db4102f6dd1 | lajapathy/python-practice | /pycharm_programs/statsTree/StatsTreeNode.py | 1,243 | 3.71875 | 4 | class StatsTreeNode(object):
# Class variable
_id = 0
# initializes a node
def __init__(self, data, parent=None, level=0):
self.data = data
self.children = []
self.parent = parent
self.level = level
self.id = StatsTreeNode._id
StatsTreeNode._id += 1
... |
1fdac2cd2f3e335a5b9e5a6c362eb78f1b0bfca5 | brindaban/Euler_project | /problem3.py | 542 | 3.546875 | 4 | def isPrime(number):
maxFactor = round(pow(number,0.5));
counter = 2
while counter <= maxFactor:
if number % counter == 0:
return False
counter = counter+1
return True
def findLargestPrimeFactor(number):
counter = 2
limit = number/2
while counter < limit:
... |
30526795737945bbb063247d6ae54efcfd5346a3 | diegoami/datacamp-courses-PY | /plotting/plot___29.py | 310 | 3.53125 | 4 | # Import plotting modules
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
auto = pd.read_csv('../data/auto.csv')
# Print the first 5 rows of the DataFrame
print(auto.head())
# Plot the pairwise joint distributions from the DataFrame
sns.pairplot(auto)
# Display the plot
plt.show()
|
8a0b1e1f3f071b87456c6eecfd36cd108f13846c | ssandyy/pythonpro | /return.py | 195 | 3.84375 | 4 | # use of "return" keyword
a,b=int(input("enter first number=")),int(input("enter second number="))
def add(a,b):
return(a+b)
print(add(a,b))
# or
'''sum=add(11,22)
print(sum)'''
|
42c58722609123e241495b024255868ec4b1480f | smohapatra1/scripting | /python/practice/start_again/2020/11022020/Index_range_innumarator.py | 200 | 4 | 4 | index=0
for i in 'abcd':
print ("The index is {} and the letter is {} ".format(index, i))
index +=1
#OR another way
index=0
word = "abcd"
for i in word:
print (word[index])
index +=1 |
ee121fdc9239700a10c6284c3106213ee47e3f01 | VundaRoy/NumpySamples | /collection/booleanArray.py | 119 | 3.5 | 4 | import numpy as np
a=np.array([[1,2],[3,4],[5,6]])
bool_idx = (a>2)
print(bool_idx)
print(a[bool_idx])
print(a[a>3]) |
ad1ca00f84c6c3100ba8fa0dfbc01e68d7d48035 | cuzai/pythonStudy | /study/numpyTest.py | 1,300 | 3.53125 | 4 | import numpy as np
li = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
array = np.array(li) # array() : 리스트를 행렬화한다. Dynamic typing : 리스트 내의 원소는 하나의 형으로 통일해야 함
print(array, '\n')
print(array + 1)
print(array.shape) # 행렬이 몇 콤마 몇인지 알려줌(앞이 더 큰 차원)
print(array.ndim) # 행렬이 몇차원인지
print(array.size) # 행렬 내... |
58c527ca3fd0868e9ce6e799b51a2d5a3fa08b6b | marcello-sousa/MAC122 | /EP3/ep3.py | 4,311 | 3.53125 | 4 | ''' Marcelo de Sousa, nº USP: 4897669, Prof. MAnoel Marcilio '''
import pilha
from time import time
'''Funcao que compara item a item dois elementos da lista TAB, returndo True se i <= j, False caso contrario'''
def compara(i, j):
if i[0:40] < j[0:40]: return True #nome
elif i[0:40] > j[0:40]: return ... |
7b5671ad048b14fc75f8a507c3496c136da749dc | SaiVK/Leetcode-Archive | /code/Reorder-List.py | 509 | 3.53125 | 4 | class Solution(object):
def reorderList(self, head):
a = []
tHead = head
while tHead:
a.append(tHead)
tHead = tHead.next
def fill(h, index=0):
print index
if (len(a) == 0):
return None
if ((index % 2) == 0)... |
81cacc35a1000f6ea60da30a6cdece8c870aef60 | gyanesh94/Coding | /codingTests/okay/4.py | 1,282 | 3.578125 | 4 | stores = [1, 5, 20, 11, 16]
houses = [5, 10, 17]
# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
def solutionA(stores, houses):
# write your code in Python 3.6
result = []
for i in range(0, len(houses)):
minDiff = 1000001
closestStoreIndex = -1
... |
5d2542be90b4a47284a58d8fd35a02f15ba3eeba | vagner-goulart/game_forca | /forca.py | 3,737 | 3.671875 | 4 | import random
lista_palavras_secretas = []
with open('palavras_secretas.txt', 'r') as arquivo_palavras:
for linha in arquivo_palavras:
lista_palavras_secretas.append(linha.strip())
tamanho_lista_palavras_secretas = len(lista_palavras_secretas) - 1
num_palavra_aleatoria = random.randint(0, tamanho_lista_... |
70f5d29ec045d1d77b088bd727c758a5464f6d4e | RiflerRick/codemonk2017 | /NumberTheory/MoguLovesNumbers1.py | 2,391 | 4.03125 | 4 | """
This solution of the problem will use the eratosthenes algorithm to generate prime numbers till r.
"""
import math
# def answer1(l, r):
# found=[]
# count=0
# for i in range(2, r+1):
# if i not in found:
# # print('prime found: '+str(i))
# if i>=l:
# count... |
49dba2b7798b01639dbecfd11d8e6aedfd496c30 | Amit0412/GIT-REV-JS | /main.py | 1,596 | 3.828125 | 4 | # This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
def show(name):
y=int(input("Enter 1 for addition or 2 for retrival"))
if y==1:
if name=="Ha... |
3ff7a7f40e5b600fb50bc23908a2912203962fb3 | manikos/EDX | /6.00x Files/W2_L4_P5_function_without_if.py | 377 | 3.609375 | 4 | x=1
lo=2
hi=3
z=min(max(x,lo),max(lo,hi))
print 'z=', z
##x=5
##lo=2
##hi=3
##
##z=min(max(x,lo),max(lo,hi))
##print 'z=', z
##
##x=2
##lo=2
##hi=3
##
##z=min(max(x,lo),max(lo,hi))
##print 'z=', z
##
##x=3
##lo=2
##hi=3
##
##z=min(max(x,lo),max(lo,hi))
##print 'z=', z
##
##x=4
##lo=3
##h... |
50d1e5c4ca62204c920f5cf8af51e34bcd3f9557 | sombra721/Python-Exercises | /Sorting Searching and Data Structure/bubble sort.py | 407 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Mar 12 19:10:06 2014
@author: Michael
"""
def bubblesort(inputList):
for i in xrange(len(inputList)-2, -1, -1):
for j in xrange(i, len(inputList)-1):
if inputList[j] > inputList[j+1]:
inputList[j], inputList[j+1] = inputList[j+1], inpu... |
a933aa099413915b46b473edddfa2b988f4bf35d | QI1002/exampool | /Cracking_the_Coding_Interview/8-5.py | 965 | 3.796875 | 4 |
def addset(result, data):
if (not data in result):
result.append(data)
def parentheses(org, n):
if (org == "" and n == 1):
return ["()"]
else:
result = []
stack = []
if (n == 1):
base = [org]
else:
base = parentheses(org, n-1)
... |
0fda49d563184ae08799394e541697ef745c9ffc | d1p013/testing | /GeneralPythonCodes/Chapter2_DataStructures/lists.py | 2,747 | 4.53125 | 5 | '''
Python Lists
Examples and Playground
'''
print("----------------")
# List in Python
x = [10, 20, 30, 40, 50]
print(x)
print(type(x))
print("----------------")
# Indexed Item
print(x[0])
# Negative Indexing
print(x[-1])
print("----------------")
# Slicing a List
print(x[1:3])
# Tail of a List
print(x[1:])
... |
2c476e182c917a62afbeaf9b46f9bad38250ef5e | netletic/pybites | /323/intersection.py | 335 | 3.625 | 4 | from typing import Any
from typing import Iterable
from typing import Set
def intersection(*args: Iterable) -> Set[Any]:
iterables = [set(iterable) for iterable in args if iterable]
return set.intersection(*iterables) if iterables else set()
if __name__ == "__main__":
print(intersection({1, 2, 3}, {2, 3... |
b4bcfb39788d5ff125118bb9678865b2123a1480 | Akif-Mufti/Machine-Learning-with-Python | /pandas1.py | 512 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Mar 27 15:11:14 2017
@author: user
"""
# define an array
# series
import numpy
import pandas
myarray = numpy.array([1, 2, 3])
rownames = ['a', 'b', 'c']
myseries = pandas.Series(myarray, index=rownames)
print(myseries)
print(myseries[0])
print(myseries['a'])
# dataframe
mya... |
54f71649446f2e98c793dbd853ba6eb6a6079bbf | JMRBDev/1DAW | /Programacion/Workspace Folder - Jose Rosendo/Ejercicios de clase/Illustrated Guide to Python3/Ejercicios/Chapter 13/exercise1.py | 287 | 4.28125 | 4 | # Write an if statement to determine whether a variable holding a year is a leap year.
year = int(input("Introduce un año: "))
if (year%4 == 0 and year%100 == 0) or (year%4 == 0 and year%400 != 0):
print(year, "is a leap year.")
else:
print(year, "is not a leap year.") |
b6f8f27f168f832af1541db63bbdd1633555858c | Pseudonium/Cell-simulator | /cell_sim v0.1.2.py | 11,818 | 3.78125 | 4 | import tkinter as tk
#import pdb
class Cell:
#ref_dict allows the coords to act as a pointer to the cell.
ref_dict = {}
"""active_cells allows the grid to determine sim_cells.
Thus, it reduces the number of cells the grid needs to simulate.
"""
active_cells = set()
def __init__(
self, coords... |
05d072c761369a6b849b8732ba83d26a5da7a9ca | alanwooo/lab | /interview/algorithm/interview.py | 285 | 4.0625 | 4 | import os
# 输入一个小于20的正整数n的条件下穷举出n位二进制数
def print_binary(x):
num = sum((2**n for n in range(x)))
for i in range(num + 1):
#print((bin(i)[2:]).zfill(x))
print( ('%0' + str(x) + 'd') % int(bin(i)[2:]))
print_binary(3)
|
a9db8ef29c98917cef01307b51dc7332f1582ab6 | JulyKikuAkita/PythonPrac | /cs15211/containsDuplicate.py | 2,811 | 3.734375 | 4 | __source__ = 'https://leetcode.com/problems/contains-duplicate/description/'
# https://github.com/kamyu104/LeetCode/blob/master/Python/contains-duplicate.py
# Time: O(n)
# Space: O(n)
#
# Description: Leetcode # 217. Contains Duplicate
#
# Given an array of integers, find if the array contains any duplicates.
# Your f... |
c2cd67a84f3828588f1748dd84019c566511f769 | hank6315/Python | /Python-Thread_Processing/multi_process.py | 632 | 3.5625 | 4 | from multiprocessing import Process, Value, Array,Lock
import time
def add_100(numbers, lock):
for i in range(100):
time.sleep(0.01)
for i in range(len(numbers)):
with lock:
numbers[i] += 1
def main():
lock = Lock()
shared_array = Array('d', [0.0 , 100.0 , 200.0])... |
f56c2992a6acaaa692b559e181a21a5b07404750 | elzbyfar/python-for-practice | /ideas/python-practice.py | 868 | 4.46875 | 4 | # Practice Questions:
# 1. Write a program that takes an array of numbers (also known as a list of numbers) and makes a new list of only the first and last elements of the given list. Write the code inside a function.
# property_tax_by_location_per_year = {
# "NYC": 10000,
# "Englewood": 7000,
# "San Antonio... |
268794a983d7cfbe7913047bcce0f55ee6c83542 | llconnor/Battleship | /Ship.py | 5,589 | 4.25 | 4 | class ShipLenException(Exception):
"""Exception raised for ships being too long or too short
"""
def __init__(self, message):
self.message = message
class ShipOutOfBoundsException(Exception):
"""Exception raised for ships being too long or too short
"""
def __init__(self, message):
... |
9db8b02b3f3683422c28b4deb38d20ba803ca870 | isaniovitor/software-engineering-degree | /Semestre_3/linguagem/5. (Atividade de Programação) Encontrando lexemas/quest.py | 247 | 3.984375 | 4 | def counting_lexemes(code, lexeme):
cont = 0
while (code.find(lexeme) != -1):
code = code[code.find(lexeme) + len(lexeme) : len(code)]
cont += 1
return cont
code = input()
lexeme = input()
print(counting_lexemes(code, lexeme)) |
aa7fd412eecbee37a33111acdee9cdcd1b3eaa24 | AlinGhenescu/Test | /main.py | 125 | 3.984375 | 4 | name = input("Please enter your name: ")
print("Hello "+name+"!")
print(f"Hello {name}, have a nice day!")
#print(type(name)) |
4030852dcbc0aaea9d0f8ead5a650a55b9ab1d79 | onlyphantom/py-networking | /helpers/echo-server.py | 1,653 | 3.828125 | 4 | # =====================================================
# Purpose:
# Illustrate the Socket > Bind > Listen > Accept
# > Receive > Send > Close paradigm illustrated in
# 2_tcpipmodel.md
# socket.socket(IPv4, TCP)
# socket.bind((Host, Port))
# socket.listen() # ready to accept connections
# socke... |
b16ef60a4ad61b0b5e92b3ee35fce7da769f45fc | laippmiles/Leetcode | /476_数字的补数.py | 831 | 3.546875 | 4 | '''
给定一个正整数,输出它的补数。补数是对该数的二进制表示取反。
注意:
1.给定的整数保证在32位带符号整数的范围内。
2.你可以假定二进制数不包含前导零位。
示例 1:
输入: 5
输出: 2
解释: 5的二进制表示为101(没有前导零位),其补数为010。所以你需要输出2。
示例 2:
输入: 1
输出: 0
解释: 1的二进制表示为1(没有前导零位),其补数为0。所以你需要输出0。
'''
class Solution:
def findComplement(self, num):
"""
:type num: int
:rtype: int
"... |
70368c0407a70dbaa8c1040ac91a355ca6b28b58 | Gioyik/5-Aniversario-MozillaHispano | /tool.py | 170 | 3.515625 | 4 | #!/usr/bin/python
import hashlib
email = raw_input('Email address? ')
salt = '#ioe12'
hash = hashlib.sha256(email + salt)
print (salt.encode('hex'), hash.hexdigest())
|
8570119d73df79d3c093345e01f29bcd87740ab8 | sommano/pythonHW | /l101/Chap6ex6.py | 295 | 3.796875 | 4 | #from test import testEqual
def is_odd(n):
if n % 2 != 0:
return False
else:
return True
num = [10, 5, 1, 0]
for x in num:
is_odd(x)
#testEqual(is_odd(10), False)
#testEqual(is_odd(5), True)
#testEqual(is_odd(1), True)
#testEqual(is_odd(0), False) |
88a91571264b03003f705f4a96e40071f79a50f1 | Zwlin98/SoftPracticeWork | /exp2/Board.py | 3,131 | 3.609375 | 4 | class Position:
leftUp = 1
rightUp = 2
leftDown = 3
rightDown = 4
class RectInfo:
def __init__(self, color, sx, sy, size):
self.color = color
self.sx = sx
self.sy = sy
self.size = size
class Color:
color = 1
class Grid:
def __init__(self, k):
sel... |
2fb4ac9e0784440e8b6bcc4f61c9e62d6fadc845 | Priyanka-Kothmire/LOOP | /counter_table8.py | 119 | 3.609375 | 4 | i=30
sum=0
while i<=420:
if i%8==0:
print(i)
sum=sum+i
i=i+1
print("total sum :",sum)
|
43d760a82c39da2a2195dc695438120ea7ada946 | ynicekyhh/python_basic | /python_ch2_8/mystring.py | 603 | 3.796875 | 4 | # class MyStr
class MyStr:
def __init__(self):
self.s = s
def __truediv__(self, other):
return self.s.split(other)
def __radd__(self, other):
return other + self.s
def __add__(self, other):
return self.s + other
def __mul__(self, other):
return MyStr(sel... |
a80e310d0af3d816d175ab5d110692da06c66ae5 | cpe342/PythonCourse | /Lists/list_comp_inter.py | 191 | 3.796875 | 4 | num1=[1,2,3,4]
num2=[3,4,5,6]
answer=[]
answer=[n for n in num1 if n in num2]
print(list(answer))
names=["Ellie","Tim","Matt"]
answer2=[n[::-1].lower() for n in names]
print(list(answer2)) |
8382bf011b1d6fa813c21dcb59fbf02cd9ec77ae | cry999/AtCoder | /beginner/097/C.py | 1,679 | 3.53125 | 4 | def kth_substring(s: str, K: int) -> str:
kth_word = '' # K 番目の文字列
kth_word_len = 0 # K 番目の文字列の長さ
n = len(s) # s の文字列の長さ
# 最初の文字から順番に決定していく。
while K > 0:
# 探索した文字列を格納する。
d = set()
# 例えば 'c' で始まる文字列に対して、'a'、 'b'で
# 始まる文字列の総数
prev_count = 0
... |
2b70e78a3e496439ce65e3eb46b993155d50c6a3 | tomato3391/algorithm | /[easy] positions_of_large_groups.py | 878 | 3.828125 | 4 | # In a string S of lowercase letters, these letters form consecutive groups of the same character.
# For example, a string like S = "abbxxxxzyy" has the groups "a", "bb", "xxxx", "z" and "yy".
# Call a group large if it has 3 or more characters. We would like the starting and ending positions of every large group.
# T... |
84806db8304b6bb9b25f9aced5bcb078492bae2a | helen5haha/pylee | /matrix/SpiralMatrix.py | 827 | 4.21875 | 4 | '''
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You should return [1,2,3,6,9,8,7,4,5].
'''
def spiralOrder(matrix):
m = len(matrix)
if 0 == m:
return []
... |
06addbf1ae3410cae0bbd69f2c8a772dec272206 | aguilargallardo/DS-Unit-3-Sprint-2-SQL-and-Databases | /lambproj/moduleone.py | 2,774 | 3.796875 | 4 | import sqlite3
conn = sqlite3.connect('rpg_db.sqlite3')
#cursor
cur = conn.cursor()
#execute method
def execute_query(query):
cur.execute(query)
results = cur.fetchall()
print(results)
print("How many charcters are there?")
x = execute_query("SELECT count(character_id) FROM charactercreator_character")
... |
7244f05dcfae19e7ace96efb5c21f528ede53ad5 | HawkinYap/Leetcode | /jz_five.py | 557 | 3.9375 | 4 | # -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.stack1 = []
def push(self, node):
# write code here
self.stack1.append(node)
def pop(self):
# return xx
stack2 = []
while self.stack1:
stack2.append(self.stack1.pop())
pop_node... |
532206f44fe8a30a97b26d434becf15db4b39873 | TFT-Dai/UChicago-kattis | /MPCSPE 2017-18/A Full-fill-ing Problem.py | 404 | 3.546875 | 4 | #https://uchicago.kattis.com/problems/uchicagoplacement.fill
def fill(a, i, v, x):
if i < 0 or i >= len(a):
return
if a[i] != v:
return
if a[i] == x:
return
a[i] = x
fill(a, i-1, v, x)
fill(a, i+1, v, x)
N, I, X = map(int, input().split())
arr = list(map(int, input().sp... |
3e945aa3c6e3df2eda981b34a6c5c9f2c003cfea | WHeesters/PythonHelp | /Lesson4_lists_tuples_sets.py | 4,115 | 4.375 | 4 | import sys
print(sys.version)
print("================================================")
print("LISTS")
print("================================================")
courses = ["History", "Math", "Physics", "CompSci"]
courses_2 = ["Education", "English"]
nums = [1, 2, 4, 5, 7, 3, 0, 9]
different_list = list("123456789") #... |
097fd9067da4ae4757507f9356a030ad69aee9d0 | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/INTERVIEW-PREP-COMPLETE/notes-n-resources/Data-Structures-N-Algo/_DS-n-Algos/_Another-One/data_structures/Trie/Trie.py | 2,259 | 4.15625 | 4 | """
A Trie/Prefix Tree is a kind of search tree used to provide quick lookup
of words/patterns in a set of words. A basic Trie however has O(n^2) space complexity
making it impractical in practice. It however provides O(max(search_string, length of longest word)) lookup
time making it an optimal approach when space is ... |
31df64cd72cca0ece3491348380029a5c2e1b452 | trilliwon/LeetCode | /easy/convert-sorted-array-to-binary-search-tree.py | 778 | 3.84375 | 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 node(self, nums, start, end):
median = (start+end)//2
node = TreeNode(nums[median])
if start == end:
... |
f0e8eb03d1d82b9b9935895ffc7d7a369c9b3ceb | sangoncalves/KDITransportation2020 | /code/Code/FormalModeling/mountain_paths_filtering.py | 1,036 | 3.59375 | 4 | '''
This file parse the mountain paths dataset and filter
the needed information based on the schema.
@carbogninalberto
'''
import pandas as pd
if __name__ == "__main__":
pd.options.mode.chained_assignment = None
print("1. Loading CSV file into a pandas dataframe...")
# loading the elaborated d... |
02104a12b1f41911ad123d50d0e80537d665b44d | cseharshit/Python_Practice_Beginner | /08.mass_distance_volume.py | 653 | 4.1875 | 4 | def calculate_mass():
d,v= map(float,input("Enter Density and Volume: ").split())
return d*v
def calculate_density():
m,v= map(float,input("Enter Mass and Volume: ").split())
return m/v
def calculate_volume():
m,d= map(float,input("Enter Mass and Density: ").split())
return m/d
if __name__=... |
434b1f253eff31d5b6877e1114dc61f756b60263 | akshay-s-022/APS-2020 | /Code Library/pattern_11.py | 255 | 3.796875 | 4 | n=5
for i in range(n):
for j in range(n + 1):
if ((j == 0 or j == n) or i == 0 and j != 0 and j != n or i == n - 1 or
i == n // 2):
print("*", end="")
else:
print(" ", end="")
print()
|
318d0a4675709fe7a85b48e455435ecf0e5809f8 | jwmarion/DC_PythonDictionary | /wordSumary.py | 249 | 3.75 | 4 | #ex4
def word_histogram(input):
tdict = {}
for word in input.split():
if tdict.get(word) == None:
tdict[word] = 1
else:
tdict[word] += 1
return tdict
print word_histogram("to be or not to be")
|
ea7af52d3f8d55755f9cac893c7ec8e3ef460596 | cs-fullstack-2019-fall/python-review-functions1a-cw-insideoutzombie | /index.py | 3,545 | 4.28125 | 4 | ### Problem 1
# Create a ```printNumbers``` function to print integers from -25 to 20 to the console (print in the function)
def printNumbers():
for x in range(-25, 21, 1):
print(x)
printNumbers()
# ### Problem 2
# Create a function called checkPassword. Send two string variables to the
# checkPassword fu... |
c37eb9bbb60636c8f514044edc37044683d71890 | Saengsorn-Wongpriew/6230403955-oop-labs | /saengsorn-6230403955-lab4/problem4.py | 265 | 3.859375 | 4 | num_lst =
input("Enter the list of numbers(delimited by a comma): ").split(",")
print(num_lst)
try:
index_lst = int(input("Enter an index: "))
print(num_lst[index_lst])
except IndexError:
print("The list has no element at index", index_lst)
|
4ad26a1e643743e955a33addaa1af3c4243fb389 | MKDevil/Python | /学习/6、第六部分 - 类和OOP/30、类的设计/listers.py | 4,148 | 3.5 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
class ListInstance(object):
"""
使用 __dict__ 列出实例属性
"""
def __str__(self):
return '<Instance of %s, address %s:\n%s>' % (
self.__class__.__name__, id(self), self.__attrnames())
def __attrnames(self):
# result = ''
fo... |
2f48d15f2ad418172727a851123a0e16ae380b81 | raxxar1024/code_snippet | /leetcode 051-100/91. Decode Ways.py | 1,107 | 4.0625 | 4 | """
A message containing letters from A-Z is being encoded to numbers using the following mapping:
'A' -> 1
'B' -> 2
...
'Z' -> 26
Given an encoded message containing digits, determine the total number of ways to decode it.
For example,
Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).
The n... |
a58489fb4a041e2eec16b9cfe1930cbbcb401e8b | samuelfranca7l/PythonExercises | /exercicios/PythonExercicios_Desafio016.py | 129 | 4.0625 | 4 | import math
num = float(input('Insira um número: '))
print('O número {} tem a parte inteira {}'.format(num, math.trunc(num)))
|
3878847a5cfae8f5ec5b083f82b304c2e58a0b98 | Shishir-rmv/oreilly_math_fundamentals_data_science | /linear_regression/task1.py | 416 | 3.5625 | 4 | """
Below we have some predicted and actual values.
Calculate the total loss as the sum of squares by
completing the code below.
Then execute the script by typing this command in the terminal:
python3 task1.py
"""
predicted_vals = [6.67, 8.61, 10.55, 12.49, 14.43, 16.37]
actual_vals = [5, 10, 10, 15, 14, 15]
lo... |
62441b6df3a70343dc02a3bacecacac81da2657f | musram/python_progs | /real_python_tutorails/pandas_expore/pandas_3.py | 591 | 4.28125 | 4 | #https://realpython.com/pandas-settingwithcopywarning/#example-of-a-settingwithcopywarning
import pandas as pd
import numpy as np
if __name__ == "__main__":
data = {"x": 2**np.arange(5),
"y": 3**np.arange(5),
"z": np.array([45, 98, 24, 11, 64])}
index = ["a", "b", "c", "d", "e"]
df = p... |
63f63f7077f0cb5bc30391a6f4d7ff7d0372bf69 | HonniLin/leetcode | /history/167.py | 674 | 3.703125 | 4 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
@File : 167.py
@Time : 2020/03/30 22:31:34
@Author : linhong02
@Desc : None
"""
class Solution(object):
def twoSum(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.