blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
fd68907e5ce80fd24fd34ad9f1513053a775afdf | yang7988/python-foundation | /function/function_varargs.py | 1,104 | 4.09375 | 4 | # 可变参数
# 有时你可能想定义的函数里面能够有任意数量的变量,也就是参数数量是可变的,这可以通
# 过使用星号来实现
def total(a=5, *numbers, **phonebook):
print('a', a)
# 遍历元组中的所有项目
for single_item in numbers:
print('single_item', single_item)
# 遍历字典中的所有项目
for first_part, second_part in phonebook.items():
print(first_part, second_part)
... |
bffa23cabee003626574364df8122db90274db38 | Getaante/Student-Management-System | /db_creation.py | 945 | 4.3125 | 4 | import sqlite3
# Create a db and connect it to the python file using sqlite3
sqliteConnection = sqlite3.connect('student_database.db')
#Cursor class is an instance using which you can invoke methods that execute SQLite statements,
#fetch data from the result sets of the queries
cursor = sqliteConnection.cursor()... |
54974ba1534ac0d6f3378c35426a6fa7949f193e | agatamar/ProsteZadanka | /ex15.py | 369 | 3.5 | 4 | def dividers(number):
return_list=[]
if isinstance(number,int) and number>0:
for i in range(1,number+1):
if number%i==0:
return_list.append(i)
return return_list
else:
return None
print(dividers(24))
# zwróci [1,2,3,4,6,8,12,24]
print(dividers(0))
#zwró... |
7c55b996c45ff63dae262b0b03386f28d49af4dd | agatamar/ProsteZadanka | /ex7.py | 1,175 | 3.78125 | 4 | from collections import OrderedDict,Counter
# wersja z biblioteką collections i metodą Counter
def count_character(text, letter):
t=text.lower()
count=Counter(t)
r=count[letter]
return r
# Wersja ze zwykłym dict() i niewiadomą kolejnoscią wyswietlania par klucz:wartosc
def count_all_characters1(text):... |
68d78e699855f1e07d5057389ef401475a1bdf24 | xqr-star/Python | /selenium自动化测试/dropdown.py | 976 | 3.546875 | 4 | # 定位下拉框 然后点击
from selenium import webdriver
import time
import os
from selenium.webdriver.common.action_chains import ActionChains
driver = webdriver.Chrome()
# / \ 正则表达式
file = "file:///" + os.path.abspath("E:\BIT—比特\测试\selenium2html\drop_down.html")
driver.get(file)
driver.maximize_window()
# 使用xpath定位... |
2ef6228c1253f70a1845927289276386e7c2728f | 769978445/GitHubApi567 | /HW04a.py | 1,262 | 3.546875 | 4 | """SSW567 HW04a
Xiangyu Wang"""
import requests
import json
def get_repo_info(user_id='769978445'): # Given a user <ID>
output = [] # initial output
user_url = 'https://api.github.com/users/{}/repos'.format(user_id) # To retrieve a user's list of repositories
res = requests.get(user_url)
repos = j... |
5f730d5aee6b2f1ba5c09664febbd7cdb08d38be | haptikfeedback/python_basics | /word_count.py | 237 | 3.78125 | 4 | def word_count(string):
string = string.lower()
word_dictionary = dict()
list_of_words = string.split()
for word in list_of_words:
word_dictionary[word] = list_of_words.count(word)
return word_dictionary
|
9371f748fbc333cd46c61b40cc7f2ff15a6de4a2 | iamukasa/tweetsum | /lyrics.py | 523 | 3.546875 | 4 | from bs4 import BeautifulSoup
import requests
import sys
import textsummariser as summarise
URL = str(sys.argv[1])
page = requests.get(URL)
html = BeautifulSoup(page.text, "html.parser") # Extract the page's HTML as a string
# Scrape the song lyrics from the HTML
lyric =str( html.find("div", class_="lyrics").get_t... |
81cb2ebaec577595469384c1046271e14e9853a1 | MAMBA-python/course-material | /Exercise_notebooks/On_topic/12_Databases/examples/contacts.py | 946 | 3.953125 | 4 | import os
import sqlite3
def create_tables(conn):
conn.execute("CREATE TABLE contacts (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, email TEXT)")
conn.commit()
def connect(path="contacts.db", syncdb=False):
"""
Connects to the database and ensures there are tables.
"""
if not os.p... |
355842473cb56d43287adcac8225e1530790e67a | kovalevvjatcheslav/euler | /task1/task1.py | 139 | 3.609375 | 4 | summary = 0
for i in range(1, 1000):
if i % 3 == 0:
summary += i
if i % 5 == 0:
summary += i
print(summary)
|
f876a21bcaa21c0cd88c57d9985b56eda5e922de | rezabehjani/docker-compose | /index.py | 299 | 3.59375 | 4 | import os
print (os.getcwd())
print (os.listdir())
f = open("file_share.txt", "a")
f.write("Now the file has more content!\r\n")
f.close()
#open and read the file after the appending:
f = open("file_share.txt", "r")
print(f.read())
f = open("file_share.txt", "a")
f.write("reza\r\n")
f.close()
|
94329723e48d4557cfa84fcc7d5eefa22a5d250a | HYnam/Python-basic | /square.py | 376 | 4.375 | 4 | # Q2.
# There is a function we are providing in for you in this problem called square. It takes one integer and
# returns the square of that integer value. Write code to assign a variable called xyz the value 5*5 (five
# squared). Use the square function, rather than just multiplying with *.
xyz = 5
def square(num):
... |
2bc6f4e7a06e61808ee6051ef26438f84b739326 | pmurph829/Compsci_119 | /Projects/Lab 4/Lab #4.py | 1,745 | 3.765625 | 4 | # Peter Murphy
import random as r
def GetANumber(Message="Enter a number between 0 and 999 --- "):
Result = -1
try:
while Result < 0 or Result > 999: Result = int(input(Message))
except: Result = GetANumber(Message)
return Result
def Main():
HurklePosition = [r.randrange(1000),r.randrange... |
bf8e66607d7e04543af2347f2fef44912a7d04ad | pmurph829/Compsci_119 | /Practice/GetPositive.py | 299 | 4.375 | 4 | # Task = function that asks the user to enter a number that is >= 0, asks again if not positve
def GetPositive ():
N = float(input("Enter a number greater than or equal to zero --- "))
while N <= 0:
N = float(input("Enter a number greater than or equal to zero --- "))
return N
|
d53468dbf759fb05b626bd068e25611694da038f | pmurph829/Compsci_119 | /Practice/Loops.py | 690 | 4.25 | 4 | # Do a thing x amount of times
# Counter Loop: Need 3 things:
# 1) define counter to some value
# 2) Test if it has reached a termininating value
# 3) Something that changes counter
# Counter starts at 0, but ends when counter is <= N, so it will actually print N + 1
def Loop(N):
counter = 0
while (counter <= ... |
a10e1a0d26d1ca2b8a393da6a870ecaefc6c972c | pmurph829/Compsci_119 | /Practice/Command Line interface.py | 708 | 3.875 | 4 | # Command Line Interface
# Commands:
# QUIT
# OPEN
# SAVE
# PRINT
# NEW
def Command_Open()
return
def Command_Save()
return
def Command_Print()
return
def Command_New()
return
def Main()
MoreToDo = True
while MoreToDo:
Command = input("Enter a command --- ")
Command = Comma... |
b8bab151f01d536431eee12c30cb3b37ef0b380c | deepaksadashiv92/My-New-City-Friend | /final/final/app/models.py | 2,033 | 3.65625 | 4 | """
Definition of models.
"""
from django.db import models
# every class creates a table with their attributes. These attributes have constrictions.
#These tables are used in the post method to save data which is generated by forms
class Customer(models.Model):
Cust_Name = models.CharField(max_length=50)
Cust... |
dc8ca6cf9b66bc1b39e56885c2f051fa594a62c6 | dushshantha/Algorithms | /Stacks-CorrectFormat.py | 384 | 3.671875 | 4 |
def correctFormat(s):
st = []
memo = {'(': ')', '[' : ']', '{' : '}'}
for c in s:
if c in memo:
st.append(c)
elif len(st) == 0 or memo[st.pop()] != c:
return False
#print(st)
return not st
if __name__ == "__main__":
assert correctFormat("()([]{})") == T... |
4a7948dbf7d015b025ecd166b4d9609edecada16 | dushshantha/Algorithms | /Fibonacci.py | 1,010 | 3.890625 | 4 | import random
def fib(i):
memo = {0: 0,
1: 1}
return fibHelper(i, memo)
# Recursion with Dynamic Programming
def fibHelper(i, memo):
if i in memo:
return memo[i]
memo[i] = fibHelper(i - 1, memo) + fibHelper(i - 2, memo)
return memo[i]
# Non recursive better performance in Spac... |
260b335faa99cae88e93db2885d83bae4e4c064a | dushshantha/Algorithms | /buildTreeFromList.py | 827 | 3.9375 | 4 | class Node:
def __init__(self, data, left = None, right = None):
self.data = data
self.left = left
self.right = right
def buildTree(l, start, end):
if start == end:
return Node(l[start])
center = (start + end) // 2
tree = Node(l[center])
if start < center:... |
84f7fbc78229dd1c62e41e065d14863f043240fd | dushshantha/Algorithms | /OneAway.py | 1,004 | 4 | 4 | '''
There are three type of edits. Insert, delete or replace. Given 2 strings , find out if the 2 are just one edit (or 0) away.
pale -> ple = True
pale -> bale = True
pales -> pale = True
pale -> bake = False
'''
def isOneAway(s1, s2):
if len(s1) == len(s2): # replace
return isOneReplaceAway(s1,s2)
e... |
6ac7d2a071c24c690d0c23586e44b12522caef08 | dushshantha/Algorithms | /SortStack.py | 931 | 4.1875 | 4 | '''
Sort values in a stack. You can use an temp stack if you like
'''
def push(s, x):
s.append(x)
def pop(s):
if s:
return s.pop(-1)
return None
def peek(s):
return s[-1]
def isEmpty(s):
return True if s else False
def sort(s):
if not s:
return s
s_tmp = []
v = pop(... |
0e5fdc898ce26ee636cc56b1350f55241142e962 | dushshantha/Algorithms | /PalindromePermutation.py | 439 | 4.0625 | 4 | '''
Given a string, write a function to check if it is a permutation of a palindrome.
'''
def isPalinPerm(s):
a = [False] * 26
for c in s:
if c != ' ':
a[ord(c) - ord('a')] = not a[ord(c) - ord('a')]
count = 0
for i in a:
if i:
count += 1
return coun... |
e6ad8921ac9fb6874d8466c4aaa876c5b6880b68 | dushshantha/Algorithms | /Non-DecreasingArray.py | 1,045 | 4.15625 | 4 | '''
You are given an array of integers in an arbitrary order. Return whether or not it is possible to make the array non-decreasing by modifying at most 1 element to any value.
We define an array is non-decreasing if array[i] <= array[i + 1] holds for every i (1 <= i < n).
Example:
[13, 4, 7] should return true, sin... |
e0cb9722eb6a70891511a09b4afe531d0b2bde28 | arozrai/removeFiles-project99 | /RemoveFiles.py | 1,926 | 3.8125 | 4 | import time
import os
import shutil
def main():
path = input("Which folder will you want to apply this program on? ")
days = int(input("Delete files over what days old: "))
seconds = time.time() - (days * 24 * 60 * 60)
print(seconds)
pathExists = os.path.exists(path)
deletedFoldersCount = 0... |
2ddf45896b8e38280d40f2396b5da58d5820bc4c | Jitendrap1702/Coding_Ninjas_Intro_to_Python | /strings/compress_string.py | 258 | 3.546875 | 4 | from itertools import groupby
def compressString(s):
new=[list(g) for k,g in groupby(s)]
for i in new:
if len(i)==1:
print(i[0],end='')
else:
print(i[0]+str(len(i)) ,end='')
s=input()
compressString(s)
|
6d48af9fc25243f98d75a7c8bba9bdf58ba86dd3 | Jitendrap1702/Coding_Ninjas_Intro_to_Python | /Conditions And Loops Python/fibonacci.py | 339 | 4.59375 | 5 | # It is used to find nth fibonacci number
n=int(input("enter a number"))
def fibonacci_seq(n):
a=0
b=1
if n==1:
print(a)
elif n==2:
print(a,b)
else:
print(a,b,end=" ")
for _ in range(n-2):
c=a+b
a=b
b=c
print(b,end=" ")... |
3ed7a1baece41ff371924c5a93da49a9863c5000 | Jitendrap1702/Coding_Ninjas_Intro_to_Python | /Searching And Sorting/insertion_sort.py | 258 | 3.921875 | 4 | def insertion_sort(arr):
for i in range(1,len(arr)):
key=arr[i]
j=i-1
while j>=0 and key<arr[j]:
arr[j+1]=arr[j]
j-=1
arr[j+1]=key
arr=list(map(int,input().split()))
insertion_sort(arr)
print(arr)
|
dec041ba936cdeac9d82558e90814a2c202a377f | eastglow-zz/mypython | /plot_simple.py | 453 | 3.78125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 23 20:43:23 2021
@author: donguk
"""
import numpy as np
import matplotlib.pyplot as plt #Visit here: https://matplotlib.org/stable/index.html
x = [1, 2, 3]
y = [5, 3, 8]
plt.plot(x,y)
plt.xlabel('x-label')
plt.ylabel('y-label')
plt.title('This ... |
24d3e6a5dd33e53689ab11f39dc9aa0f09c25a40 | vkrvj/python-prgm | /beginner lvl/naturalmum.py | 65 | 3.6875 | 4 | num=int(raw_input())
a=0
for i in range(1,num+1):
a=a+i
print a
|
1fe205f9119231c20bf17b67fad7aba7f45dfabc | vkrvj/python-prgm | /player/uptolowtoup.py | 159 | 3.859375 | 4 | w=list(input())
for i in range(len(w)):
if w[i].islower():
w[i]=w[i].upper()
else:
w[i]=w[i].lower()
print("".join(str(x) for x in w))
|
03a8de30c7c5306ad393fb9d92c6416f8a8ddc4d | reniass/ProjectEuler | /problem6.py | 300 | 3.765625 | 4 | def sumSquares(n):
sum = 0
for number in range(1, n+1):
sum += number ** 2
return sum
def squareSum(n):
sum = 0
for number in range(1, n+1):
sum += number
return sum ** 2
print(sumSquares(100))
print(squareSum(100))
print(squareSum(100) - sumSquares(100)) |
68431470d9c7f0e0b595a11450360debd80546be | iweyy/WIA2004-Operating-Systems | /Lab 6/dining_philosopher.py | 3,033 | 3.828125 | 4 | import threading
import time
class Semaphore():
def __init__(self, initial):
self.lock = threading.Condition(threading.Lock()) # to avoid concurrence
self.value = initial
def up(self):
with self.lock:
self.value += 1 #inc... |
b130628a272e8e9c0ee8a701c32717500e5c69e0 | lovtens/deep-learning-2019 | /3주차/linear_regression.py | 1,056 | 3.53125 | 4 | import tensorflow as tf
x_data = [1,2,3]
y_data = [1,2,3]
W = tf.Variable(tf.random_uniform([1],-1.0,1.0))
b = tf.Variable(tf.random_uniform([1],-1.0,1.0))
X = tf.placeholder(tf.float32, name="X")
Y = tf.placeholder(tf.float32, name="Y")
hypothesis = W * X + b
cost = tf.reduce_mean(tf.square(hypothesis -Y))
#l... |
ff91ab3f676c8bd6e3cc503e94277b24974e915f | raj9226/session4 | /venv/session4c.py | 390 | 3.90625 | 4 | data=[10,20,90,80,90]
#lengh=len(data)
#print(lenght)
print(len(data))
print(max(data))
print(min(data))
#iterete in list
for i in range(len(data)):
print(data[i])
#Enhanced for loop/For-Each loop
for elm in data:
print(elm)
print("--------------")
print([x**2 for x in data])
print("--------------------")
num... |
d8d0d550f44e37919e129303663d7db1d7afd428 | acgrafton/melon-delivery-report | /produce_summary.py | 897 | 3.703125 | 4 | def generate_produce_summary(one_file):
"""Prints produce summary for one day'
Loop through text file and print out number of melons delivered and revenue."""
for line in one_file:
line = line.rstrip()
words = line.split('|')
melon = words[0]
count = words[1]
amou... |
830ffaca9019cb0f5807ef71ae90145bc26d99ad | Jom901/Coding-Challenges | /stage4/Challenge4.py | 2,179 | 3.578125 | 4 | #################################################################################################
#Jonathan Medina Morales #
#This program is part of a the challenge programs for CODE2040's applications in November 2014 #
#This program receives a JSON with a date and a time interval.The objective of t... |
2fa665613064a2d193d3f17de0555643d4b8be81 | vsantanait/House-Hunting-Raise | /ps1b.py | 2,660 | 4.25 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 17 05:50:32 2021
@author: vanessamsantana
"""
#Factoring in a raise every 6 months
#Have user input a semi-annual salary raise (semi_annual_raise) a decimal percentage
# After the 6th month, increase salary by that percentage. In crease by same % a... |
98ab19876854436620a77b2b32d3b541d07743c6 | PapicAleksandar/ProgramiranjeVezbe | /drugi(19.11).py | 97 | 3.703125 | 4 | str1 = input("Prvi string:")
str2 = input("Drugi string:")
print(str1[0:3]+str1[0:3]+str2[-3:]) |
d676961ce4fef0482c2543522b64e3d69527ecf9 | KayleighPerera/COM411 | /Basics/Week2/and_operator.py | 337 | 4.15625 | 4 | # ask user what they saw and heard
print("what did i hear")
hear = input()
print("what did i see")
see = input()
# determine what message should be displayed
if ( (hear == "grr") and (see == "Two red eyes") ):
print("\nThere is a scary creature, i should get out of here!")
else:
print("\nI am a little sacred but ... |
1cbe04a14a7f75e81a79dd3d068fa5f065bb7edd | KayleighPerera/COM411 | /Basics/Week2/bot.py | 540 | 4.03125 | 4 | # Ask user for the direction of brush
print("towards which direction should i paint (up,down, left or right?)")
direction = input()
# Determine which message to display
if (direction == "up"):
print("\ni am paining in an upward direction")
elif (direction == "down"):
print("\ni am painting in an downward direction... |
9d43f4fc8d4a803366426f62e9948afd63a0b57e | KayleighPerera/COM411 | /data/sets/set_from_list.py | 503 | 3.96875 | 4 | def observed():
observations = []
for count in range(7):
print("please enter an item")
item = input()
observations.append(item)
return observations
def run():
print("counting observations...")
observations = observed()
observations_set = set()
for observation in observations:
occurr... |
3bc89ec30f14882be14b46f076dcac149fe08d68 | KayleighPerera/COM411 | /Basics/Week2/repetitions/for_loop/simple.py | 330 | 3.921875 | 4 | # ask how many mountains to display
print ("how many mountains should i display?")
mountains = int(input())
# display mountains
print("\nDisplaying...")
for mountain in range (mountains):
print("""
--
/ \\_
/^ \\
/ ^ \\
_/ ^ ^ ^\\_
/ ^ ^ ... |
43d8699f5cb3f59845ba20e086391fbe686b8c6d | cyyc290/0924 | /hw03/main.py | 920 | 3.796875 | 4 | v=3.14
class Ellipse(object):
def __init__(self,longsemiaxis,shortsemiaxis):
self.longsemiaxis=longsemiaxis
self.shortsemiaxis=shortsemiaxis
def area(self):
return self.longsemiaxis*self.shortsemiaxis*v
class Circle(Ellipse):
def __init__(self,semiaxis):
self.longsemiax... |
378dedbac39f1136e56422596b36b2116110b16a | zjg540066169/Bioinformatics_learning | /UCSD/Finding Hidden Messages in DNA (Bioinformatics I)/Week 2/Approximate_Pattern_Count.py | 913 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 10 21:42:58 2019
ApproximatePatternCount(Text, Pattern, d)
count ← 0
for i ← 0 to |Text| − |Pattern|
Pattern′ ← Text(i , |Pattern|)
if HammingDistance(Pattern, Pattern′) ≤ d
count ← count + 1
... |
009c817b850e09e8460b47ab6e3f3e7570206619 | zjg540066169/Bioinformatics_learning | /UCSD/Genome Sequencing (Bioinformatics II)/Week 1/Eulerian_Cycle_Problem.py | 6,456 | 3.625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 24 07:47:11 2019
Input: The adjacency list of an Eulerian directed graph.
Output: An Eulerian cycle in this graph.
Randomly select a starting point S, randomly search for a path from S to S,
which forms a cycle.
while True:
If there is no nod... |
9e145d2052874d5c9f05c8d1e0ab6af4d9445271 | zjg540066169/Bioinformatics_learning | /UCSD/Genome Sequencing (Bioinformatics II)/Week 1/Hamiltonian_Graph.py | 5,467 | 3.625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 22 19:07:57 2019
@author: jungangzou
"""
class node(object):
def __init__(self, ID):
#self.attribute = attribute
self.ID = ID
self.edge = []
def add_new_edge(self, ID):
self.edge.append(ID)
de... |
0dcd2260c400dc870ea242b0b907059af225d6a8 | CatherineShm/git_new | /Kurs/0004_b.py | 311 | 4 | 4 | first_name = input("imie: ")
last_name = input("nazwisok: ")
b_year = input("rok ur: ")
profession = input("zawod: ")
result = f"""
{"imie i nazwisko:"} {first_name:>10}{last_name.capitalize()}
{"============================="}
{"rok urodzenia:"} {b_year:<10}
{"zawód:"} {profession}
"""
print(result) |
8336321e68b561f8e52c0472e574d8930fa479d8 | wtnb-s/weather_app | /data/flask/codes/getPlotMap.py | 3,622 | 3.5 | 4 | from sklearn.linear_model import LinearRegression
from codes import const
import numpy as np
import pandas as pd
import geopandas as gpd
import matplotlib.pyplot as plt
# 日較差算出
def getDailyRange(data):
# 欠測値を置換
data = data.replace(-999.0, np.nan)
dailyRange = data['MaxTemp'] - data['MinTemp']
return da... |
db8a9eae447ad25e53908291c41d9f4d57f2b0d5 | djudjuu/mazerobot-python | /test_neuroevolution.py | 1,341 | 3.53125 | 4 | import mazepy
#simple fitness function -- how close do we get to the goal at the end of
#a simulation?
def fitness(robot):
return -mazepy.feature_detector.end_goal(robot)
#initialize maze stuff with "medium maze"
mazepy.mazenav.initmaze("medium_maze_list.txt","neat.ne")
mazepy.mazenav.random_seed()
#create initial... |
dda4c5bdaf0687cbaf95909514f2b1ecf8c3948f | marek-iiasa/Code | /Catalogue.py | 2,379 | 3.75 | 4 | """
This is a simple catalog app
"""
import json
'''class book:
def __init__(self, title, author):
self.title = title
self.author = author'''
class catalog:
def __init__(self, books):
self.books = books
#new_book = input('would you like to ad a new book? (y/n)')
try:
... |
71a8bfc1314f21ea5a844dd695f5e14c116e5047 | gopricy/crack_coding_interview | /pocket_gems/131.palindrome-partitioning.py3 | 1,392 | 3.734375 | 4 | #
# [131] Palindrome Partitioning
#
# https://leetcode.com/problems/palindrome-partitioning/description/
#
# algorithms
# Medium (35.24%)
# Total Accepted: 115.3K
# Total Submissions: 327.2K
# Testcase Example: '"aab"'
#
#
# Given a string s, partition s such that every substring of the partition is a
# palindrome... |
18020b737fbaa2742453ba24ee91a09c4598dfa4 | fernandomflopes/algoritimos | /fibonacci/fast_doubling.py | 399 | 3.796875 | 4 | # code from https://www.nayuki.io/page/fast-fibonacci-algorithms
#
def _fib(n):
if n == 0:
return (0,1)
else:
a,b = _fib(n//2)
c = a * (b * 2 - a)
d = a * a + b * b
if n % 2 == 0:
return (c, d)
else:
return (d, c + d)
def fib(n):
if n... |
0d9dc891e34a697c1e42fafcb0f59a6e7df26713 | amandal1810/micro-projects | /weather.py | 893 | 3.921875 | 4 | #asks for the name of a city/state/country and shows the weather forecast for that city/state/country in your web browser using the Yahoo Weather API
import urllib2, urllib, json
import os
baseurl = "https://query.yahooapis.com/v1/public/yql?"
#yql_query = "select wind from weather.forecast where woeid=2460286"
print "... |
ee80b60e31c7c86cd47767d6ba9a22d3a6a544db | ajpagente/Fraternal | /display/string_format.py | 1,993 | 3.5 | 4 | from abc import ABCMeta, abstractmethod
from colorama import Fore, Back, Style
class BaseStringFormatter(metaclass=ABCMeta):
@abstractmethod
def table_header(self, string):
pass
@abstractmethod
def field(self, string):
pass
@abstractmethod
def sub_field(self, string):
... |
96069046b1bcf949e8c61ce758afbda7007e60dd | DylanLennard/Udacity_Project_3_Automation | /users.py | 981 | 3.578125 | 4 | # -*- coding: utf-8 -*-
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import xml.etree.cElementTree as ET
import pprint
import re
"""
Your task is to explore the data a bit more.
The first task is a fun one - find out how many unique users
have contributed to the map in this particular area!
The function process_map... |
f8f61d7ce9e622f29ca77fc466d1d209426ddb38 | devmohit-live/Adv_Python_Rev | /Collections files/Deques.py | 472 | 3.875 | 4 | from collections import deque
# A list like container woth fast append and pop on either end (Double ended queue)
d=deque()
d.append(1)
d.append(2)
d.appendleft(3)
d.appendleft(4)
print(d)
print('pop',d.pop())
print('pop left',d.popleft())
# Supports count and extend as normal list container
d.extendleft([7,8,9])
prin... |
9628c8bc6cdc0c20841b924dc573acb462b053ad | devmohit-live/Adv_Python_Rev | /Collections files/default_dicionarie.py | 978 | 4.375 | 4 | '''
here we can give an initial value to dictionary, we can to the same with normal dictionary using setdefault() method too but it is fast,
also here we can give the datatype as default value ex d(list) nad the values will support the opration of that partivular datatype, ex:
d['mohit'].append()
defauldict() => takes ... |
f762d5610b4f757a51a38305b1aec9bf846b3d37 | TestowanieAutomatyczneUG/laboratorium-6-pauljackals | /src/ex2_valid_password/ex2_valid_password.py | 1,797 | 3.75 | 4 | class ValidPassword:
def valid_password(self, password):
"""Takes a string and checks for required characters
>>> vp = ValidPassword()
>>> vp.valid_password('fEr!gr9ht')
True
>>> vp.valid_password('FER!GR9T')
True
>>> vp.valid_password('4r3ff')
False
... |
f693ddebd56136aac4d222c496128c1c7233c17b | rafael-miranda10/freecodecamp_python_opencv | /FreeCodeCamp/01/draw.py | 1,072 | 3.59375 | 4 | import cv2 as cv
import numpy as np
blank = np.zeros((500,500,3), dtype='uint8')
cv.imshow('Blank', blank)
img = cv.imread('photos/3.jpg')
cv.imshow('Image', img)
#1 - Paint the image a certain colour
#blank[:] = 0,0,255
#blank[200:300, 300:400] = 255,0,0
#cv.imshow('Green', blank)
#2 - Draw a Rectangle
#thickness... |
c2581ff757b4fb988aafc88d116dfeb346b9fe91 | ayushbij27/Python-Programming-Examples | /longest_in _speech.py | 269 | 3.859375 | 4 | import os
import sys
a=["This is a longest sentence","where are you","What is your name"]
b=[word for sublist in a for word in sublist.split()]
max_value=len(b[0])
word=b[0]
for i in b:
if(len(i)>max_value):
max_value=len(i)
word=i
print max_value
print word |
298443c85e6ddb6d17598b2e0b7ed7a8d6c6d376 | AUT-CE-Archive/AUT-CE-AD | /Algorithms/Merge_Sort.py | 640 | 3.96875 | 4 | from random import randint
def merge_sort(arr):
if len(arr) > 1:
middle = len(arr) // 2
L_arr = arr[:middle]
R_arr = arr[middle:]
merge_sort(L_arr)
merge_sort(R_arr)
i = j = k = 0
while i < len(L_arr) and j < len(R_arr):
if L_arr[i] < R_arr[j]:
arr[k] = L_arr[i]
i += 1
else:
arr... |
950629988da1dfc447ed396dcf2b4e6c606ee436 | weedySeaDragon/plantuml-documentation | /doc/dev/jinja-2cols-ex.py | 5,173 | 3.6875 | 4 | # You can use the following in a python console/workspace to see examples of:
# - jinja namespace() (reference a variable in the outer scope (loop))
# - passing a value into a template (use a dictionary with each entry = "variable_name": variable_value
# - slice() jinja filter (can be used to split a list into colum... |
ef13e1037cae37126fe2a001315fa16caa40bd0a | aboubakrs/365DaysofCode | /Day2/Day 2.py | 413 | 4.03125 | 4 | #L'interpréteur de Python peut être utilisé comme Calculatrice de Bureau
calcul_un = 2+3
calcul_deux = 3 + 8
calcul_trois = 22/5
calcul_quatre = 22//5
calcul_cinq = 3 - 14
print("Le resultat de 2+3 = " ,calcul_un)
print("Le resultat de 3+8 = " ,calcul_deux)
print("Le resultat de 22/5 = " ,calcul_trois)
print... |
4b27c42bd6bb87a3e7fa5d7586597f236e781f44 | aboubakrs/365DaysofCode | /Day19/Day 19 - Exo1.py | 1,129 | 3.828125 | 4 | #Valeurs Par Défaut pour les paramètres
print("Exercice : Valeurs par défaut pour les paramètres")
#Définition de la Fonction
def question(annonce, essais =4, please ='Oui ou non, s.v.p.!'):
while(essais>0):
reponse = input(annonce)
if reponse in ('o', 'oui', 'O', 'Oui', 'OUI'):
return ... |
46b1ebec59a0f1807534895f324a1db4243e3c9f | aboubakrs/365DaysofCode | /Day13/Day 13 - Exo1.py | 284 | 3.53125 | 4 | #Ca joue un peu avec les fonctions
print("Exercice : C'est ma première Fonctionkh Simple !")
#Définition d'une Fonction
def tableMultiplicationPar7():
n = 1
while(n < 11):
print(7, "*", n, "=", n*7)
n = n + 1
#Appel de La Fonction
tableMultiplicationPar7() |
31c64d6099155b6a768f790b57b8746bc1e9d718 | mayankbhandari1310/ProgrammingPractice | /SPOJ Classical 200 problems/AggressiveCowsID297.py | 1,895 | 3.625 | 4 | '''
Farmer John has built a new long barn, with N (2 <= N <= 100,000) stalls. The stalls are located along a straight line at positions x1,...,xN (0 <= xi <= 1,000,000,000).
His C (2 <= C <= N) cows don't like this barn layout and become aggressive towards each other once put into a stall.
To prevent the cows from hu... |
084e360131ae9057efb9e47cffdd11502388713b | mayankbhandari1310/ProgrammingPractice | /Data Structures/Sorting.py | 6,062 | 3.96875 | 4 | import random
'''
Bogosort, don't call it. Just don't. Okay fine, maybe with 2-3 elements
'''
from itertools import permutations
def bogosort(arr):
def check_if_sorted(arr):
length = len(arr)
for ix in range(length-1):
if arr[ix] > arr[ix+1] :
return False
return True
length = len(arr)
perm = permuta... |
b79d86058a250d3b8a46297d706dc4cec91b101f | hanyberg/Python | /övn2_5.py | 154 | 4.1875 | 4 | word=input("Please write a word you want to have printed backwards and in uppercase.\n")
#print(word.upper())
#print(word[::-1])
print(word[::-1].upper()) |
ede41742194167cd2760a4b8a536ac7ec589bc33 | hanyberg/Python | /övn2_4.py | 127 | 4.09375 | 4 | x=int(input("What is your starting number"))
y=int(input("What is your ending number"))
for i in range (x,y+1):
print(i) |
c80e6f2bee992011dbf0bcda18185826ad5de13a | hanyberg/Python | /birthday.py | 118 | 3.984375 | 4 | for i in range (3):
print("Hip Hip Hurra!")
for i in range (3):
for y in range (2):
print ("Hipp hipp")
print ("HURRA!")
|
3a48e9b7e387dfb3885971cdb06662b68b9ab843 | joe-jordan/tran | /tran/__init__.py | 1,431 | 3.9375 | 4 | class TransactionError(Exception):
pass
class Transaction:
"""a class to encapsulate SQL-transaction-like behaviour for python
function calls. Especially useful for large complex objects whose methods
have side effects; like modifying lists, dicts, numpy arrays and networkx
Graphs."""
def __ini... |
45081c3ed3ad8c11fe1b4f36af447a4cc82fa88e | meghanrosetighe/SoftDesSp15 | /toolbox/ml/learning_curve.py | 1,234 | 3.9375 | 4 | """ Exploring learning curves for classification of handwritten digits """
import matplotlib.pyplot as plt
import numpy
from sklearn.datasets import *
from sklearn.cross_validation import train_test_split
from sklearn.linear_model import LogisticRegression
data = load_digits()
num_trials = 10
train_percentages = rang... |
4e2f12c583e411e35520364e4ff9bf00540bcbf7 | guoliangxd/interview | /huawei/Python/getrabbitfor.py | 329 | 3.890625 | 4 | #计算斐波那契数列-循环版
def getRabbit(mon):
m1 = 1
m2 = 1
if mon <= 2:
return 1
else:
for i in range(mon - 2):
temp = m2
m2 = m1 + m2
m1 = temp
return m2
while True:
try:
print(getRabbit(int(input())))
except:
break
|
fd24ac2af09d40e8e9396c37b82fda6d43e37956 | guoliangxd/interview | /huawei/Python/encrypt.py | 812 | 3.75 | 4 | while True:
try:
key = input().lower()
data = input()
mapList = {}
index = 'a'
for char in key:
if char in mapList.values():
continue
else:
mapList[index] = char
index = chr(ord(index) + 1)
for i ... |
fcf96894444740df173b1517e8cdf260daa9ec2e | guoliangxd/interview | /huawei/DeKe/count1.py | 214 | 3.734375 | 4 | while True:
try:
num = int(input())
count = 0
while num != 0:
if num % 2 == 1:
count += 1
num //= 2
print(count)
except:
break |
231999403e493a4f05caa30ccd5bddf39ed0ad3b | guoliangxd/interview | /huawei/Python/MySort.py | 860 | 3.75 | 4 | def mySort(rawStr):
result = ''
alpha = []
for char in rawStr:
if char.isalpha():
if len(alpha) == 0:
alpha.append(char)
continue
for i in range(len(alpha)):
if char.lower() >= alpha[i].lower():
if i == len(a... |
dde663b1b8e11db32671248b04f96e98011bc967 | faquino012/RetoSem3 | /pregunta3.py | 1,377 | 3.828125 | 4 | #Declaración de variables y lista
cant = int(input(f'Cuantos alumnos registrará?\n'))
alumnos = dict()
#Ingresar los datos de cada alumno
for j in range(cant):
nom = input(f'Cual es el nombre del alumno N° {j + 1}?\n')
canNot = int(input(f'Cuantas notas ingresará para el alumno {nom}?\n'))
notas = []
#... |
502c604cafcb1cbe7c4b9992e6a4903ec30e1ab6 | SoniaB77/Exercise_14_Functions | /RockPaperScissors.py | 3,809 | 4.40625 | 4 | import random
# Things to consider: ROCK, PAPER, SCISSORS.
# - User input which only accepts values of R,P or S which correlate to Rock, Paper, Scissors.
# - Have the computer randomly select rock, paper or scissors.
# - Need variables to display the user wins along with the computer wins and any draws.
# ~ consider... |
d5f8b7b319e7e18f7e0d1f4fc982ecb005b9200c | augustomy/Curso-PYTHON-01-03---Curso-em-Video | /ex026.py | 340 | 3.90625 | 4 | x = input('Digite uma frase: ')
aux = x.strip()
aux2 = aux.upper()
aux3 = aux2.count('A')
print('Quantidade de letras A na frase digitada: {}'.format(aux3))
aux4 = aux2.find('A')
print('Posição da primeira letra A: {}'.format(int(aux4+1)))
aux5 = aux2.rfind('A')
print('Posição da última letra A: {}'.format(int(... |
84a8eeb6981e92bd1355422b53aedf5a31ec895c | augustomy/Curso-PYTHON-01-03---Curso-em-Video | /ex024.py | 735 | 4.21875 | 4 | #nomecidade = input('Digite sua cidade: ')
#nsemespacos = nomecidade.strip() #ELIMINA OS ESPAÇOS DA ESQUERDA (COMEÇO) E DA DIREITA (FINAL)
#nupper = nsemespacos.upper() #PADRONIZA A CIDADE EM LETRAS TODAS MAIÚSCULAS
#aux = nupper.split() #SEPARA AS PALAVRAS (EM CASO DE PALAVRAS COMPOSTAS)
#resultado = 'SANTO' in au... |
bf8289f4661f75d5a81ad77fb5f5cb097efb1b31 | augustomy/Curso-PYTHON-01-03---Curso-em-Video | /ex016.py | 196 | 3.640625 | 4 | import math
x = float(input('Digite um número: '))
i = math.trunc(x)
print('O número digitado foi {} e possui \033[4;36mparte\033[m \033[4;36minteira\033[m \033[4;32m{}\033[m.'.format(x,i))
|
53bf9060f48a784f8f1135f7fc15fd579bbd386a | augustomy/Curso-PYTHON-01-03---Curso-em-Video | /ex031.py | 321 | 3.890625 | 4 | km = float(input('Digite a distância da viagem em km: '))
if km <= 200:
passagem = 0.5 * km
print('Distância informada: {} km\nValor da passagem: R${:.2f}'.format(km, passagem))
else:
passagem = 0.45 * km
print('Distância informada: {} km\nValor da passagem: R${:.2f}'.format(km, passagem))
|
5063ee1f3df2d97e4906d177169192ec69bd81f0 | augustomy/Curso-PYTHON-01-03---Curso-em-Video | /ex006.py | 292 | 4.0625 | 4 | x = float(input('Digite um número: '))
d = x * 2
t = x * 3
r = x ** 0.5
# r = pow(x, 0.5)
print('O dobro de \033[7m{}\033[m é \033[1;32m{}\033[m.\nO triplo de \033[7m{}\033[m é \033[1;32m{}\033[m.\nA raiz quadrada de \033[7m{}\033[m é \033[1;32m{}\033[m.'.format(x, d, x, t, x, r))
|
59c9217df5caec91cfba1982688c200251a99289 | augustomy/Curso-PYTHON-01-03---Curso-em-Video | /ex035.py | 426 | 3.84375 | 4 | a = float(input('Reta 01: '))
b = float(input('Reta 02: '))
c = float(input('Reta 03: '))
if abs(b-c) < a < b+c and abs(a-c) < b < a+c and abs(a-b) < c < a+b:
print('\033[1;32mSim, é possível formar um triângulo com as dimensões informadas:\033[m {}, {}, {}'.format(a, b, c))
else:
print('\033[1;31mNão é p... |
eee0d2d5967f7035da069fba0b54b52b6e141148 | augustomy/Curso-PYTHON-01-03---Curso-em-Video | /ex023.py | 256 | 4.0625 | 4 | x = int(input('Digite um número de 0 a 9999: '))
m = x // 1000 % 10
c = x // 100 % 10
d = x // 10 % 10
u = x // 1 % 10 #DIVISÃO DE x POR 10 E PEGA O RESTO DESSA DIVISÃO
print('Unidade: {}\nDezena: {}\nCentena: {}\nMilhar: {}'.format(u, d , c, m))
|
78673b8dab1f73c2f4179dc587babf63f8fed67d | augustomy/Curso-PYTHON-01-03---Curso-em-Video | /desafio025aula09.py | 150 | 3.65625 | 4 | nomec = input('Digite o nome completo de uma pessoa: ')
teste = 'SILVA' in nomec
print('A pessoa informada possui SILVA no nome: {}.'.format(teste)) |
d00a21fb5fc8c700623edf77c8e2b35cc1ed2153 | augustomy/Curso-PYTHON-01-03---Curso-em-Video | /desafio023aula09.py | 493 | 3.984375 | 4 | #MANEIRA NÃO ESTÁ 100% CORRETA
#x = input('Digite um número inteiro de 0 a 9999: ')
#u = x[3]
#d = x[2]
#c = x[1]
#m = x[0]
#print('Unidade: {}\nDezena: {}\nCentena: {}\nMilhar: {}'.format(u, d, c, m))
#MANEIRA 100% CORRETA
x = int(input('Digite um número de 0 a 9999: '))
m = x // 1000 % 10
c = x // 100 %... |
294604b6de2fcad7e53ec81fd5e16fa7c91145e4 | griffs37/CA_117 | /q3_061.py | 381 | 3.6875 | 4 | #!usr/bin/env python
import sys
def main():
for password in sys.stdin:
total = 0
uppers = 0
lowers = 0
digits = 0
others = 0
for c in password:
if c.isupper():
uppers = 1
if c.islower():
lowers = 1
if c.isdigit():
digits = 1
else:
others = 1
total = lowers + uppers + digits... |
f5a3d2ac3d096a804887868cff89e9312b9dac46 | griffs37/CA_117 | /queue.py | 517 | 3.5625 | 4 | class PQ(object):
def __init__(self):
self.d = {}
self.N = 0
def exch(self, i, j):
self.d[i], self.d[j] = self.d[j], self.d[i]
def swim(self, k):
while k > 1 and self.d[k//2] < self.d[k]:
self.exch(k, k//2)
k = k//2
def insert(self, v):
self.N += 1
self.d[self.N] = v
self.swim(self.N)
d... |
be34af8e34402a4848e38b3c6fb0c8c3c11c82b7 | griffs37/CA_117 | /password_012.py | 625 | 3.609375 | 4 | #!/usr/bin/env python
import sys
def password(line):
upper = 0
digit = 0
lower = 0
special = 0
i = 0
while i < len(line):
if line[i].isupper():
upper = 1
elif line[i].isdigit():
digit = 1
elif line[i].i... |
c6a1c1b50d85a0ce2a0473f86851bd22b8b81b5e | esayre/PER-networks | /ClusterComparison/clusterschemes.py | 1,624 | 3.546875 | 4 | from __future__ import division
from FinalCode2 import list_of_list_of_clusters
import math
'''--------------------------------------------------------------------------'''
def cluster_comparison(list1,list2):
UNION = len(list(set().union(list1,list2)))
INTERSECTION = len(list(set(list1) & set(list2)))
ra... |
7e1e1f81599aebe18cd17dddf1e038ce0fa414b0 | moksh999/Attendance-Using-Face-Recognition | /face_rec.py | 5,176 | 3.53125 | 4 | import face_recognition as fr
#import os
import cv2
import face_recognition
import numpy as np
#from time import sleep
def get_encoded_faces():
"""
looks through the faces folder and encodes all
the faces
:return: dict of (name, image encoded)
"""
encoded = {} # dictionary with key as name o... |
1b3756f1094b2ecfa35f12f0f7b4c6f6c216c2e3 | ferpoletto/Login-postgres | /menu.py | 2,355 | 3.609375 | 4 | from administrador import *
class Menu:
def mostra_menu_ADM(self):
print('=' * 30)
print('{:^30}'.format('MENU DO ADM'))
print('=' * 30)
op = int(input('1 - CADASTRAR NOVO USUARIO\n'
'2 - INATIVAR USUARIO\n'
'3 - ALTERAR USUARIO\n'
... |
b00677116234b9dd4705c2314df86e7add3a03de | Oluwatobi09/past_python_programs | /hydrology.py | 212 | 4.28125 | 4 | print (' WELCOME ')
num1 = eval(input('How many numbers do you want to print? '))
for i in range (1,num1+1):
num2 = eval(input('enter number '))
a=num2**3
print(num2,'^3 is ',a)
print('end of program')
|
354ad707d25bf0441bc46a94aa314b33e8ab9499 | pdebuyl-lab/tidynamics | /tidynamics/_correlation.py | 4,213 | 3.5 | 4 | import numpy as np
from .core import autocorrelation_1d, correlation_1d
import itertools
def acf(data):
"""Autocorrelation of the input data using the Fast Correlation Algorithm.
Computes the autocorrelation for all time lags in the input data. The numerical results for
large lags contain fewer samples th... |
e976ee9815e421bf703036b3143cc44dc69f6d8d | hockidogg/375_cs | /chapter02/geussing_game.py | 397 | 3.984375 | 4 | #
def main():
print("im thinking of a number between 1 and 100")
magic_number = 55
guess = 0
while guess != magic_number:
guess = eval (input)("what is your guess")
if guess < magic_number:
print ("your to low")
elif guess > magic_number:
print("your... |
79f68e82e31f815ffd50fcef346195b70bfaca15 | MorrisGlr/Transcribing_DNA_into_RNA | /Rosalind_Transcribing_DNA_into_RNA.py | 433 | 4.03125 | 4 | file = open('rosalind_rna.txt', 'r') #tells python to read a file
dna = file.readlines() #we give all of the data in the file a name so that we can work with it. remember, the data is a one item list in this case
dnastring = ''.join(dna) #convert list into str... |
d4395a10e69839af6de916850c51b330c4319c0b | yuhaoyin/UCLA-20W-ECE219-LargeScaleDataMining | /project5-twitter-application/project5_code.py | 62,551 | 3.65625 | 4 | #!/usr/bin/env python
# coding: utf-8
# ## PART 1 - Popularity Prediction
# <font size=4> **Question 1**: Report the following statistics for each hashtag, i.e. each file:
# - Average number of tweets per hour;
# - Average number of followers of users posting the tweets per tweet (to make it simple, we average ov... |
96c3d48f0224b53b07bfb135666612edb78d4b34 | Luksos9/LearningThroughDoing | /automateboringstuff/workingWithExcelSpreadsheets/updatingSpreadsheet.py | 1,230 | 3.9375 | 4 | """This program updates cells in a spreadsheet of produce sales.
program will look through the spreadsheet, find specific kinds of produce, and update their prices.
Program does the following:
1.Loops over all the rows
2.If the row is for garlic, celery, or lemons, changes the price"""
# ! python3
import openpyxl
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.